title,body,link,tags,view_count,is_answered,score,answer_count
Unit testing in Flutter passing BuildContext,"<p>I have a method in a Dart class, which accepts <code>BuildContext</code> parameter, as follows:</p>

<pre><code>class MyClass {

  &lt;return_type&gt; myMethodName(BuildContext context, ...) {
        ...
        doSomething
        return something;
    }
}
</code></pre>

<p>I want to test that the method works as expected: </p>

<pre><code>import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
...

void main() {
  MyClass sut;

  setUp(() {
    sut = MyClass();
  });

  test('me testing', () {

    var actual = sut.myMethodName(...);        

    expect(actual, something);
  });
}
</code></pre>

<p>Of course, it won't work, because the method <code>myMethodName</code> needs a parameter <code>BuildContext</code> type. This value is available throughout the application itself, but not sure where to get that from in my unit tests. </p>
",https://stackoverflow.com/questions/56277477/unit-testing-in-flutter-passing-buildcontext,"['unit-testing', 'dart', 'flutter']",24804,True,56,4
Coroutines - unit testing viewModelScope.launch methods,"<p>I am writing unit tests for my viewModel, but having trouble executing the tests. The <code>runBlocking { ... }</code> block doesn't actually wait for the code inside to finish, which is surprising to me.</p>

<p>The test fails because <code>result</code> is <code>null</code>. Why doesn't <code>runBlocking { ... }</code> run the <code>launch</code> block inside the ViewModel in blocking fashion?</p>

<p>I know if I convert it to a <code>async</code> method that returns a <code>Deferred</code> object, then I can get the object by calling <code>await()</code>, or I can return a <code>Job</code> and call <code>join()</code>. <strong>But</strong>, I'd like to do this by leaving my ViewModel methods as <code>void</code> functions, is there a way to do this?</p>

<pre><code>// MyViewModel.kt

class MyViewModel(application: Application) : AndroidViewModel(application) {

    val logic = Logic()
    val myLiveData = MutableLiveData&lt;Result&gt;()

    fun doSomething() {
        viewModelScope.launch(MyDispatchers.Background) {
            System.out.println(""Calling work"")
            val result = logic.doWork()
            System.out.println(""Got result"")
            myLiveData.postValue(result)
            System.out.println(""Posted result"")
        }
    }

    private class Logic {
        suspend fun doWork(): Result? {
          return suspendCoroutine { cont -&gt;
              Network.getResultAsync(object : Callback&lt;Result&gt; {
                      override fun onSuccess(result: Result) {
                          cont.resume(result)
                      }

                     override fun onError(error: Throwable) {
                          cont.resumeWithException(error)
                      }
                  })
          }
    }
}
</code></pre>

<pre><code>// MyViewModelTest.kt

@RunWith(RobolectricTestRunner::class)
class MyViewModelTest {

    lateinit var viewModel: MyViewModel

    @get:Rule
    val rule: TestRule = InstantTaskExecutorRule()

    @Before
    fun init() {
        viewModel = MyViewModel(ApplicationProvider.getApplicationContext())
    }

    @Test
    fun testSomething() {
        runBlocking {
            System.out.println(""Called doSomething"")
            viewModel.doSomething()
        }
        System.out.println(""Getting result value"")
        val result = viewModel.myLiveData.value
        System.out.println(""Result value : $result"")
        assertNotNull(result) // Fails here
    }
}

</code></pre>
",https://stackoverflow.com/questions/55765190/coroutines-unit-testing-viewmodelscope-launch-methods,"['android', 'kotlin', 'android-livedata', 'kotlin-coroutines']",16242,True,33,8
Is Angular component unit testing actually unit testing?,"<p>I'm starting to learn unit testing, and understand the primary objective is to test a system in isolation. Therefore, any dependencies should be stubbed, mocked, etc. </p>

<p>According to the Angular documentation on testing, you should mock whatever is provided via dependency injection. So far, so good. But then, as shown in the code below, you can simply import other required modules, components, directive, pipes through a shared or feature module.</p>

<p>Is this really unit testing then? If the target system under test is a component, isn't this actually testing its entire module?</p>

<p>Or is this just a concession that it'd be near impossible to mock all the requirements in a real world application?</p>

<pre><code>beforeEach(async(() =&gt; {
  const routerSpy = createRouterSpy();

  TestBed.configureTestingModule({
    imports:      [ SharedModule ],
    declarations: [ HeroDetailComponent ],
    providers: [
      { provide: ActivatedRoute, useValue: activatedRoute },
      { provide: HeroService,    useClass: TestHeroService },
      { provide: Router,         useValue: routerSpy},
    ]
  })
  .compileComponents();
}));
</code></pre>
",https://stackoverflow.com/questions/56984970/is-angular-component-unit-testing-actually-unit-testing,"['angular', 'unit-testing', 'jasmine']",768,True,3,3
CloudTableClient Unit Testing,"<p>How do I write unit tests for classes that depend on Azure Table Storage, i.e. <code>Microsoft.Azure.Cosmos.Table.CloudTableClient</code>?</p>

<p>I found this GitHub issue, <a href=""https://github.com/Azure/azure-storage-net/issues/465"" rel=""noreferrer"">Azure Storage is still hard to unit test / mock</a>, but I didn't find any clues in it other than methods are now <code>virtual</code>.</p>

<hr>

<p><code>MyService</code> takes a dependency on <code>CloudTableClient</code> and internally gets a reference to a <code>CloudTable</code> to query the table.  In my example here I'm doing a simple lookup by partition and row key:</p>

<pre class=""lang-cs prettyprint-override""><code>public MyService(CloudTableClient tableClient
            , ILogger&lt;MyService&gt; logger) { }

public async Task&lt;MyMapping&gt; GetMappingAsync(string rowKey)
{
    var table = GetTable();
    var retrieveOp = TableOperation.Retrieve&lt;MyMapping&gt;(""MyPartitionKey"", rowKey);
    var tableResult = await table.ExecuteAsync(retrieveOp);
    return tableResult.Result as MyMapping;
}

private CloudTable GetTable()
{
    return tableClient.GetTableReference(""FakeTable"");
}
</code></pre>
",https://stackoverflow.com/questions/58957600/cloudtableclient-unit-testing,"['c#', 'unit-testing', 'moq', 'azure-table-storage']",4277,True,7,1
Angular Unit Testing: Is this code worth unit testing?,"<p>I have just began unit testing in angular. I am having a hard time figuring out what should be covered in unit tests in the application. Should I be testing the below code? </p>

<p>If I do I will be essentially be passing a valid value of <code>mode</code> and checking if correct values for various properties of <code>defaultProperties</code> were emitted by <code>this.propertiesSource</code>. Isn't it like writing the same code all over again and more? And this is just one example, application is full of such instances. </p>

<p>If I don't test such things then probably my code coverage will be negligible. </p>

<p>Here is an example of code from component:</p>

<pre><code> mode: string;
  defaultProperties = {
    editable: this.editable,
    showToolbar: this.showToolbar,
    viewMode: this.viewMode,
    editMode: this.editMode,
    showPopup: this.showPopup,
    formSavedClicked: this.formSavedClicked,
    cancelClicked: this.cancelClicked,
    refresh: this.refresh,
  };
  private propertiesSource = new BehaviorSubject(this.defaultProperties);
</code></pre>

<p><strong>Method to be tested:</strong></p>

<pre><code> setGridMode(mode) {
    this.mode = mode;
    if (mode === ""edit"") {
      this.propertiesSource.next({
        editable: true,
        showToolbar: true,
        viewMode: false,
        editMode: true,
        showPopup: false,
        formSavedClicked: this.formSavedClicked,
        cancelClicked: this.cancelClicked,
        refresh: false,

      });
    } else if (mode == ""save"") {
      this.propertiesSource.next({
        editable: false,
        showToolbar: false,
        viewMode: true,
        editMode: false,
        showPopup: false,
        formSavedClicked: this.formSavedClicked,
        cancelClicked: this.cancelClicked,
        refresh: true,
      })
      // more code..multiple if else block like above
    }  
   }
</code></pre>
",https://stackoverflow.com/questions/56681338/angular-unit-testing-is-this-code-worth-unit-testing,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",516,False,1,2
Unit Testing CoroutineExceptionHandler,"<p>Hello I have this code that uses coroutines and I want to unit test it :</p>

<p>My problem is that my exception is never catched by the <code>CoroutineExceptionHandler</code>.</p>

<p>My code looks something like the following :</p>

<pre><code> fun request() {
    val handler = CoroutineExceptionHandler { _, throwable -&gt; liveData.value = Resource.error(throwable.message) }

    viewModelScope.launch(handler) {
        liveData.value = Resource.loading()
        val result = withContext(Dispatchers.IO) { useCase.request() }
        liveFdDetails.value = Resource.success(result)
    }
}
</code></pre>

<p>And my test :</p>

<pre><code>fun testError() = runBlocking {

    //Given
    val observer: Observer&lt;Resource&lt;Data&gt;&gt; = mock()
    whenever(useCase.request()).thenThrow(Error(""MSG""))
    viewModel.liveData.observeForever(observer)

    //When
    viewModel.request()

    //Then
    inOrder(observer).apply {
        verify(observer).onChanged(Resource.loading())
        verify(observer).onChanged(Resource.error(""MSG""))
    }
}
</code></pre>
",https://stackoverflow.com/questions/56182844/unit-testing-coroutineexceptionhandler,"['android', 'unit-testing', 'kotlin', 'coroutine', 'kotlin-coroutines']",1249,True,4,1
Unit testing in SwiftUI,"<p>I am trying to write unit tests for SwiftUI views but finding zero resources on the web for how to go about that. </p>

<p>I have a view like the following</p>

<pre><code>struct Page: View {
@EnvironmentObject var service: Service

var body: some View {
    NavigationView {
        ScrollView(.vertical) {
            VStack {
                Text(""Some text""))
                    .font(.body)
                    .navigationBarTitle(Text(""Title"")))

                Spacer(minLength: 100)
            }
        }
   }
}
}
</code></pre>

<p>I started writing a test like this</p>

<pre><code>func testPage() {
    let page = Page().environmentObject(Service())
    let body = page.body
    XCTAssertNotNil(body, ""Did not find body"")
}
</code></pre>

<p>But then how do I get the views inside the body? How do I test their properties? Any help is appreciated.</p>

<p><strong>Update</strong>:
As a matter of fact even this doesn't work. I am getting the following runtime exception</p>

<pre><code>Thread 1: Fatal error: body() should not be called on  ModifiedContent&lt;Page,_EnvironmentKeyWritingModifier&lt;Optional&lt;Service&gt;&gt;&gt;.
</code></pre>
",https://stackoverflow.com/questions/58238087/unit-testing-in-swiftui,"['swift', 'swiftui', 'xctest']",4803,True,10,2
CdkDragDrop unit testing events,"<p>So, i've been working on unit testing for my Angular app. I'm using Angular Material and i have a component which uses the drag-drop CDK <a href=""https://material.angular.io/cdk/drag-drop/overview"" rel=""noreferrer"">cdk drag-drop API</a>.</p>

<p>the html code looks like this </p>

<pre><code>&lt;mat-card class=""interventionCard""&gt;
  &lt;div  cdkDropListGroup class=""container""&gt;
    &lt;div cdkDropList
         [cdkDropListData]=""interventionsTodo"" (cdkDropListDropped)=""drop($event)"" class=""dragContainer""&gt;
      &lt;div class=""dragInter"" *ngFor=""let i of interventionsTodo"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;a class=""resetInv"" (click)=""reset()""&gt;&lt;div class=""dragInter""&gt;&lt;img src=""../assets/images/simulation-intervention/noIntervention.svg"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;&lt;/a&gt;&lt;!----&gt;
    &lt;/div&gt;

    &lt;div class=""dropContainer""&gt;
      &lt;div cdkDropList [cdkDropListData]=""interventionsDoneNow"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDoneNow"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;/div&gt;
        &lt;div class=""connectorL""&gt;&lt;/div&gt;
      &lt;div cdkDropList [cdkDropListData]=""interventionsDonePlus5"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDonePlus5"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc""&gt;&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=""connectorL""&gt;&lt;/div&gt;
      &lt;div cdkDropList  [cdkDropListData]=""interventionsDonePlus10"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDonePlus10"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=""connectorL""&gt;&lt;/div&gt;
      &lt;div cdkDropList  [cdkDropListData]=""interventionsDonePlus15"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDonePlus15"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=""connectorL""&gt;&lt;/div&gt;
      &lt;div cdkDropList  [cdkDropListData]=""interventionsDonePlus20"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDonePlus20"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=""connectorL""&gt;&lt;/div&gt;
      &lt;div cdkDropList  [cdkDropListData]=""interventionsDonePlus25"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDonePlus25"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=""connectorL""&gt;&lt;/div&gt;
      &lt;div cdkDropList [cdkDropListData]=""interventionsDonePlus30"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDonePlus30"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
</code></pre>

<p>All fine, now i have the cdkDropListDroppet event which calls the function <code>drop()</code></p>

<pre><code>    drop(event: CdkDragDrop&lt;{ imgSrc: string }[], any&gt;) {
     if (event.previousContainer === event.container) {
       moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
     } else {
         if(event.container.data === this.interventionsTodo){
         this.deleteSpecificItemFromTimeline(event.previousContainer.data[0]);
         }else if(event.container.data.length &lt;1){
           copyArrayItem(event.previousContainer.data,
             event.container.data,
             event.previousIndex,
             event.currentIndex);
         }
      }
    }
</code></pre>

<p>this works fine, now im unit testing the angular app (jasmine/karma)
and i am trying to dispatch the CdkDragDrop event so that i can verify the functionality of my <code>drop()</code> function.</p>

<p>So in the angular documentation there is a small chapter on component DOM testing, where its mentioned that you have to get the htmlElement where you want to fire the event which i do like this:<a href=""https://angular.io/guide/testing#component-dom-testing"" rel=""noreferrer"">angular docs</a></p>

<pre><code>    let Dbg = fixture.debugElement;
    let htE = Dbg.nativeElement.querySelector("".dragContainer"");
</code></pre>

<p>now i have the element on which i want to fire the event so full code looks like this</p>

<pre><code>    let Dbg = fixture.debugElement;
      let htE = Dbg.nativeElement.querySelector("".dragContainer"");

      htE.addEventListener('CdkDragDrop', (ev:any) =&gt; {
        component.drop(ev);
      });
      let bla = htE.dispatchEvent(new Event('cdkDropListDropped'));
</code></pre>

<p>So bla returns true, which (if im not wrong) means the event was fired, but nothing seems to happen
<code>fixture.detectchanges()</code> happens automatically..
i tried to debug it to see what is happening but the listenerfunction is never fired and i looked everywhere to find an answer but cant seem to find anything on that kind of eventtesting..</p>
",https://stackoverflow.com/questions/56259451/cdkdragdrop-unit-testing-events,"['angular', 'unit-testing', 'angular-material', 'coded-ui-tests']",9100,True,9,1
unit testing for ngAfterViewInit?,"<p>I am new to writing unit test cases for angular. I have to write a test case for <strong>ngAfterViewInit</strong>. I don't know how to start. I am using angular 7.</p>

<p>My component code:</p>

<pre><code>export class MyAccessComponent implements OnInit, AfterViewInit {

    // Spinner
    pageLoaded: boolean;
    @Input() diameter = 64;
    @Input() strokeWidth = 7;

    // Icons
    faEdit = faEdit;

    dataSource;
    @ViewChild(MatPaginator) paginator: MatPaginator;

    constructor(private router: Router, private userService: UserService) { }

    ngOnInit() {
        this.pageLoaded = false;
        // Data table init
        this.getUsers();
    }

    ngAfterViewInit() {
        setTimeout(() =&gt; {
            this.pageLoaded = true;
        }, 500);
    }
}
</code></pre>
",https://stackoverflow.com/questions/55274781/unit-testing-for-ngafterviewinit,"['angular', 'unit-testing']",18507,True,10,2
Dataflow unit testing,"<p>I'm trying to build a unit test for my pipeline.</p>

<p>This pipeline read from pubsub, perform a transformation and write the result to pubsub again.</p>

<p>To simplify even more the unit test until it works, the unit test will only receive a string as an input and test if the output is the some string.</p>

<p>The code looks like the following:</p>

<pre><code>@RunWith(JUnit4.class)
public class TesterPipeline {   

    // Our static output data, which is the expected data that the final PCollection must match.
    static final String[] COUNTS_ARRAY = new String[] {""this""};

    @Rule public TestPipeline p = TestPipeline.create();

    // Example test that tests the pipeline's transforms.
    @Test
    @Category(ValidatesRunner.class)
    public void testPipeline() throws Exception {

      // Run the pipeline.
      PCollection&lt;String&gt; input= p.apply(""input string"", Create.of(""This is just a message"").withCoder(StringUtf8Coder.of()));
      PAssert.that(input).containsInAnyOrder(COUNTS_ARRAY);
      p.run();
    }
}
</code></pre>

<p>I'm trying to execute the unit test using Eclipse but I got the following error:</p>

<pre><code>java.lang.AssertionError: input string/Read(CreateSource).out: class ""org.hamcrest.Matchers""'s signer information does not match signer information of other classes in the same package
    at org.apache.beam.sdk.testing.PAssert$PAssertionSite.capture(PAssert.java:169)
    at org.apache.beam.sdk.testing.PAssert.that(PAssert.java:411)
    at org.apache.beam.sdk.testing.PAssert.that(PAssert.java:403)
    at com.xxx.pipeline.TesterPipeline.testPipeline(TesterPipeline.java:61)
    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.apache.beam.sdk.testing.TestPipeline$1.evaluate(TestPipeline.java:319)
    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.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)
Caused by: java.lang.SecurityException: class ""org.hamcrest.Matchers""'s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(ClassLoader.java:891)
    at java.lang.ClassLoader.preDefineClass(ClassLoader.java:661)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:754)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at org.apache.beam.sdk.testing.PAssert$AssertContainsInAnyOrder.apply(PAssert.java:1497)
    at org.apache.beam.sdk.testing.PAssert$AssertContainsInAnyOrder.apply(PAssert.java:1476)
    at org.apache.beam.sdk.testing.PAssert$CheckRelationAgainstExpected.apply(PAssert.java:1146)
    at org.apache.beam.sdk.testing.PAssert$CheckRelationAgainstExpected.apply(PAssert.java:1126)
    at org.apache.beam.sdk.testing.PAssert.doChecks(PAssert.java:1425)
    at org.apache.beam.sdk.testing.PAssert$GroupedValuesCheckerDoFn.processElement(PAssert.java:1392)
    at org.apache.beam.sdk.testing.PAssert$GroupedValuesCheckerDoFn$DoFnInvoker.invokeProcessElement(Unknown Source)
    at org.apache.beam.repackaged.direct_java.runners.core.SimpleDoFnRunner.invokeProcessElement(SimpleDoFnRunner.java:218)
    at org.apache.beam.repackaged.direct_java.runners.core.SimpleDoFnRunner.processElement(SimpleDoFnRunner.java:183)
    at org.apache.beam.repackaged.direct_java.runners.core.SimplePushbackSideInputDoFnRunner.processElementInReadyWindows(SimplePushbackSideInputDoFnRunner.java:78)
    at org.apache.beam.runners.direct.ParDoEvaluator.processElement(ParDoEvaluator.java:216)
    at org.apache.beam.runners.direct.DoFnLifecycleManagerRemovingTransformEvaluator.processElement(DoFnLifecycleManagerRemovingTransformEvaluator.java:54)
    at org.apache.beam.runners.direct.DirectTransformExecutor.processElements(DirectTransformExecutor.java:160)
    at org.apache.beam.runners.direct.DirectTransformExecutor.run(DirectTransformExecutor.java:124)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code></pre>

<p>Looking for some information about this error I found this to <a href=""https://stackoverflow.com/questions/9651784/hamcrest-tests-always-fail"">question</a> related. In her, the solution was:<code>The hamcrest.jar needs to go before the Junit library in the build path.</code></p>

<p>I'm not sure If I have something wrong in my configuration, because I thought I had doe what that solution said, but I'm still get the same error.</p>

<p>Like I'm new with Java and also Eclipse maybe I'm executing wrong the unit test, but I did not find more information in the official  <a href=""https://beam.apache.org/documentation/pipelines/test-your-pipeline/"" rel=""nofollow noreferrer"">doc</a> of apache beam and neither in google <a href=""https://cloud.google.com/dataflow/pipelines/testing-your-pipeline"" rel=""nofollow noreferrer"">doc</a></p>

<p>The Junit configuration:</p>

<p><a href=""https://i.stack.imgur.com/PVB6V.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/PVB6V.jpg"" alt=""junit""></a></p>

<p>The build path configuration:</p>

<p><a href=""https://i.stack.imgur.com/uVWGs.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/uVWGs.jpg"" alt=""build path""></a></p>

<p>The pom file:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;

&lt;project xmlns=""http://maven.apache.org/POM/4.0.0""
    xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
    xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

  &lt;groupId&gt;com.xxx.pipeline&lt;/groupId&gt;
  &lt;artifactId&gt;pipeline&lt;/artifactId&gt;
  &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;

  &lt;properties&gt;
    &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
    &lt;maven-compiler-plugin.version&gt;3.7.0&lt;/maven-compiler-plugin.version&gt;
    &lt;exec-maven-plugin.version&gt;1.6.0&lt;/exec-maven-plugin.version&gt;
    &lt;slf4j.version&gt;1.7.25&lt;/slf4j.version&gt;
    &lt;beam.version&gt;2.16.0&lt;/beam.version&gt;
    &lt;apache-commons.version&gt;2.5.0&lt;/apache-commons.version&gt;
    &lt;commons-cli.version&gt;1.4&lt;/commons-cli.version&gt;
  &lt;/properties&gt;

  &lt;repositories&gt;
    &lt;repository&gt;
      &lt;id&gt;ossrh.snapshots&lt;/id&gt;
      &lt;name&gt;Sonatype OSS Repository Hosting&lt;/name&gt;
      &lt;url&gt;https://oss.sonatype.org/content/repositories/snapshots/&lt;/url&gt;
      &lt;releases&gt;
        &lt;enabled&gt;false&lt;/enabled&gt;
      &lt;/releases&gt;
      &lt;snapshots&gt;
        &lt;enabled&gt;true&lt;/enabled&gt;
      &lt;/snapshots&gt;
    &lt;/repository&gt;
  &lt;/repositories&gt;

  &lt;build&gt;
   &lt;plugins&gt;
      &lt;plugin&gt;
        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
        &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
        &lt;version&gt;${maven-compiler-plugin.version}&lt;/version&gt;
        &lt;configuration&gt;
          &lt;source&gt;1.8&lt;/source&gt;
          &lt;target&gt;1.8&lt;/target&gt;
        &lt;/configuration&gt;
      &lt;/plugin&gt;
    &lt;/plugins&gt;

    &lt;pluginManagement&gt;
      &lt;plugins&gt;
        &lt;plugin&gt;
          &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
          &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt;
          &lt;version&gt;${exec-maven-plugin.version}&lt;/version&gt;
          &lt;configuration&gt;
            &lt;cleanupDaemonThreads&gt;false&lt;/cleanupDaemonThreads&gt;
          &lt;/configuration&gt;
        &lt;/plugin&gt;
      &lt;/plugins&gt;
    &lt;/pluginManagement&gt;
  &lt;/build&gt;

  &lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;com.google.cloud.dataflow&lt;/groupId&gt;
      &lt;artifactId&gt;google-cloud-dataflow-java-sdk-all&lt;/artifactId&gt;
      &lt;version&gt;2.5.0&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
      &lt;groupId&gt;org.apache.beam&lt;/groupId&gt;
      &lt;artifactId&gt;beam-runners-direct-java&lt;/artifactId&gt;
      &lt;version&gt;${beam.version}&lt;/version&gt;
      &lt;scope&gt;runtime&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
    &lt;groupId&gt;org.hamcrest&lt;/groupId&gt;
    &lt;artifactId&gt;hamcrest-all&lt;/artifactId&gt;
    &lt;version&gt;1.3&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
      &lt;groupId&gt;org.apache.beam&lt;/groupId&gt;
      &lt;artifactId&gt;beam-sdks-java-core&lt;/artifactId&gt;
      &lt;version&gt;${beam.version}&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
    &lt;groupId&gt;commons-io&lt;/groupId&gt;
    &lt;artifactId&gt;commons-io&lt;/artifactId&gt;
    &lt;version&gt;2.6&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
    &lt;groupId&gt;com.googlecode.json-simple&lt;/groupId&gt;
    &lt;artifactId&gt;json-simple&lt;/artifactId&gt;
    &lt;version&gt;1.1&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
      &lt;groupId&gt;org.apache.beam&lt;/groupId&gt;
      &lt;artifactId&gt;beam-sdks-java-io-google-cloud-platform&lt;/artifactId&gt;
      &lt;version&gt;${beam.version}&lt;/version&gt;
      &lt;exclusions&gt;
        &lt;exclusion&gt;
          &lt;groupId&gt;junit&lt;/groupId&gt;
          &lt;artifactId&gt;junit&lt;/artifactId&gt;
        &lt;/exclusion&gt;
      &lt;/exclusions&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
      &lt;groupId&gt;org.apache.beam&lt;/groupId&gt;
      &lt;artifactId&gt;beam-sdks-java-extensions-google-cloud-platform-core&lt;/artifactId&gt;
      &lt;version&gt;${beam.version}&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.apache.beam&lt;/groupId&gt;
      &lt;artifactId&gt;beam-sdks-java-extensions-protobuf&lt;/artifactId&gt;
      &lt;version&gt;${beam.version}&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.apache.beam&lt;/groupId&gt;
      &lt;artifactId&gt;beam-runners-google-cloud-dataflow-java&lt;/artifactId&gt;
      &lt;version&gt;${beam.version}&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
        &lt;artifactId&gt;commons-dbcp2&lt;/artifactId&gt;
        &lt;version&gt;${apache-commons.version}&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;commons-cli&lt;/groupId&gt;
        &lt;artifactId&gt;commons-cli&lt;/artifactId&gt;
        &lt;version&gt;${commons-cli.version}&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;!-- slf4j API frontend binding with JUL backend --&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
      &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;
      &lt;version&gt;${slf4j.version}&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
      &lt;artifactId&gt;slf4j-jdk14&lt;/artifactId&gt;
      &lt;version&gt;${slf4j.version}&lt;/version&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;
&lt;/project&gt;
</code></pre>
",https://stackoverflow.com/questions/59352277/dataflow-unit-testing,"['java', 'unit-testing', 'google-cloud-dataflow', 'apache-beam']",2484,True,1,2
Unit Testing MatDialog,"<p>Im creating a unit test for my confirmation modal that uses MatDialog. my first test is a basic test that the component should be created. here is my code for the spec file.</p>

<pre><code>import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { PocitConfirmationModalComponent } from './confirmation-modal.component';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { CommonModule } from '@angular/common';
import { PortalModule } from '@angular/cdk/portal';
import { MaterialModule } from 'src/app/core/material/material.module';
import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing';


class MatDialogRefStub {
    close(param: string) {}
}

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


  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        MaterialModule,
        PortalModule
       ],
      declarations: [PocitConfirmationModalComponent],
      providers: [
          { provide: MatDialogRef, useClass: MatDialogRefStub },
          { provide: MAT_DIALOG_DATA, useValue: {} },
      ]
    }).overrideModule(BrowserDynamicTestingModule, {
        set: {
          entryComponents: [ PocitConfirmationModalComponent ],
        }
    })
    .compileComponents();
  }));

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

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

});
</code></pre>

<p>this is the component file that I want to test.</p>

<pre><code>import { Component, OnInit, Inject, ViewEncapsulation } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { ComponentPortal } from '@angular/cdk/portal';

@Component({
  selector: 'pocit-confirmation-modal',
  templateUrl: './confirmation-modal.component.html',
  styleUrls: ['./confirmation-modal.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class PocitConfirmationModalComponent implements OnInit {

  portal: ComponentPortal&lt;any&gt;;

  constructor(
    public dialogRef: MatDialogRef&lt;PocitConfirmationModalComponent&gt;,
    @Inject(MAT_DIALOG_DATA) public data: any,
  ) {
    this.portal = new ComponentPortal(this.data.component);
   }

  ngOnInit() {
  }

  action(type: string) {
    this.dialogRef.close(type);
  }

}
</code></pre>

<p>after all of these I got this error after running the test.</p>

<pre><code>Error: No component factory found for undefined. Did you add it to @NgModule.entryComponents?
</code></pre>

<p>I already added it to entryComponents but still got this error.</p>
",https://stackoverflow.com/questions/54121492/unit-testing-matdialog,"['javascript', 'angular', 'typescript', 'karma-jasmine']",2765,False,1,1
NodeJS unit testing,"<p>Possibly a naive question but I have a class similar to(mine has more data read from database and caching them):</p>

<pre><code>var genericClass = class {

    constructor() {
        this.genericStructure = {};
    }

    async getState(key) {
        //some more core logic
        return this.genericStructure[key];
    }

    async putState(key, genericJson) {
        this.genericStructure[key] = genericJson;
        return true;
    }
}
</code></pre>

<p>its <code>getState</code> and <code>putState</code> are used multiple times in a consumer class, I want to mock all these occurences from a local <code>map</code> object in my test class. Can it be done?</p>

<p>I am using <code>chai, mocha, sinon</code></p>

<pre><code>""devDependencies"": {
        ""chai"": ""^4.1.2"",
        ""chai-as-promised"": ""^7.1.1"",
        ""eslint"": ""^4.19.1"",
        ""mocha"": ""^5.2.0"",
        ""nyc"": ""^12.0.2"",
        ""sinon"": ""^6.0.0"",
        ""sinon-chai"": ""^3.2.0""
    }
</code></pre>
",https://stackoverflow.com/questions/56625011/nodejs-unit-testing,"['node.js', 'unit-testing', 'mocha.js', 'sinon']",95,True,0,1
Unit Testing: Jasmine,"<p><code>isTriangle</code> function checks the sides of the triangle and determines if the triangle is either a scalene, equilateral, or isosceles. </p>

<p>After writing the function, I need to do an unit test via Jasmine with Javascript. </p>

<p>Code:</p>

<pre><code>function isTriangleTranslate(side1, side2, side3) {
    if (side1 === side2 &amp;&amp; side3 === side2 &amp;&amp; side2 === side1) {
        return (""It's an equilateral!"");
    }
    if (side2 === side3 &amp;&amp; side1 != side2 &amp;&amp; side1 != side3 || side1 === side3 &amp;&amp; side2 != side1 &amp;&amp; side2 != side3 || side1 === side2 &amp;&amp; side2 != side3) {
        return (""It's an isosceles!"");
    }
    else {
        return (""It's a scalene!"");
    }
}
</code></pre>

<p>Spec:</p>

<pre><code>describe(""isTriangle"", function(){

  it(""is an equilateral trinagle with three equal sides"", function(){
    expect(isTriangleTranslate()).toEqual(""It's an equilateral!"");

  })

});

describe(""isTriangle"", function(){

  it(""is an isosceles triangle with two equal sides"", function(){
    expect(isTriangleTranslate()).toEqual(""It's an isosceles!"");

  })

});

describe(""isTriangle"", function(){

  it(""is a scalene triangle with no equal sides"", function(){
    expect(isTriangleTranslate()).toEqual(""It's a scalene!"");

  })

});
</code></pre>

<p>Errors are that the scalene &amp; isosceles do not equal ""It's an equilateral"" </p>

<p>I do not want it to do that. I want it to determine if my side1, side2, &amp; side3 are equal then it equals the string ""It's an equilateral!"" </p>

<p>If my side1, side2, &amp; side3 have two sides that are equal the it equals the string ""It's an isosceles!""</p>

<p>Else, the triangle is ""It's a scalene!"" </p>

<p>How will you write this in a unit test for Jasmine?</p>
",https://stackoverflow.com/questions/56841330/unit-testing-jasmine,['javascript'],73,False,-1,1
Laravel Unit Testing,"<p>I am implementing unit testing in laravel.
While running the test cases using the below command.</p>

<pre><code> vendor/bin/phpunit --filter = MethodName
</code></pre>

<p>It is prompting me to install composer,although I have already installed it.
Can anyone help?</p>
",https://stackoverflow.com/questions/55104043/laravel-unit-testing,"['laravel', 'unit-testing', 'lumen']",129,False,0,1
Unit Testing HttpURLconnention,"<p>I am writing Unit Test for Method Which makes Http POST Request using HttpUrlConnection in java.I am using PowerMockito for mocking URL,Proxy.</p>

<pre><code>@Before
   public void setUp()
   {
           impl=new httpClient();

   }
    @Test
    public void httpClientTest()
    {
        try {
            URL obj= PowerMockito.mock(URL.class);
            Proxy proxy = PowerMockito.mock(Proxy.class);
            InetSocketAddress inetAddr=PowerMockito.mock(InetSocketAddress.class);
            HttpURLConnection mockConn = PowerMockito.mock(HttpURLConnection.class);
            PowerMockito.whenNew(InetSocketAddress.class).withArguments(anyString(),anyInt()).thenReturn(inetAddr);
            PowerMockito.whenNew(URL.class).withArguments(any(String.class)).thenReturn(obj);
            PowerMockito.whenNew(Proxy.class).withArguments(Proxy.Type.HTTP,inetAddr).thenReturn(proxy);
            PowerMockito.when(obj.openConnection(proxy)).thenReturn(mockConn);
            JsonObject req=new JsonObject();
             String response=impl.makeRequest(""abc"",req);
             System.out.println(response);
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }



    public void makeRequest(String empid,JsonObject request)
        {
            JsonObject variables=request.getJsonObject(""variables"");
            variables.put(""requested_for"",empid);
            request.put(""variables"",variables);
            StringBuffer response = new StringBuffer();
            JsonObject successResponse;
            try
            {
                String url = ""Some_valid_url"";
                URL obj = new URL(url);
                 String proxyURL=""abc.xyz.com"";
                 int port=80;
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyURL, port));
                HttpURLConnection con = (HttpURLConnection)obj.openConnection(proxy);
                con.setRequestMethod(""POST"");
                con.setRequestProperty(""Content-Type"",""application/json"");
                System.setProperty(""com.sun.net.ssl.checkRevocation"", ""false"");  //SSL certificate validation false
                con.setDoOutput(true);
                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                String requestBody= request.toString();
                wr.writeBytes(requestBody);
                wr.flush();
                wr.close();
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        con.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
            } catch (Exception e) {
                System.out.println(e);
            }


   }
</code></pre>

<p>I am getting this exception while running test.</p>

<pre><code>  java.lang.IllegalArgumentException: type null is not compatible with address null 
    at java.net.Proxy.&lt;init&gt;(Proxy.java:95)
        at sun.net.ApplicationProxy.&lt;init&gt;(ApplicationProxy.java:37)
        at sun.net.ApplicationProxy.create(ApplicationProxy.java:41)
        at java.net.URL.openConnection(URL.java:1018)
</code></pre>

<p>exception is getting caught at
  PowerMockito.when(obj.openConnection(proxy)).thenReturn(mockConn); this point in  test.</p>
",https://stackoverflow.com/questions/57108733/unit-testing-httpurlconnention,"['java', 'junit', 'mockito', 'powermockito']",478,False,0,1
Unit testing principles,"<p>When I write unit tests should I create one or more  test methods for each and every method that I create in the source file? If the method calls 3 other methods , should response of all those methods be mocked?</p>
",https://stackoverflow.com/questions/57999049/unit-testing-principles,"['unit-testing', 'junit', 'python-unittest']",74,True,-1,3
Unit Testing LiveData android.os.Looper not mocked,"<p>I am trying to unit test my ViewModel that posts some stuff back to the activity via <code>LiveData</code> but when I run the method that sets the livedata value I get the error</p>
<blockquote>
<p>java.lang.RuntimeException: Method getMainLooper in android.os.Looper
not mocked.</p>
</blockquote>
<p>I have read several posts and articles that all you have to do is add a <code>Rule</code> for <code>InstantTaskExecutorRule</code> and it should just work but I did that and I still get the error.</p>
<p>This is my unit test</p>
<pre><code>val observer: Observer&lt;String&gt; = mock(Observer::class.java) as Observer&lt;String&gt;

@get:Rule
var rule: TestRule = InstantTaskExecutorRule()

@Test
fun testSearchDataValidationFailureMissingSearchLocation() {
    val viewModel = MoveViewModel()

    val param1 = 0
    val param2 = 1
    val param3 = &quot;1234&quot;
    viewModel.dialogMessageLiveData.observeForever(observer)

    Assert.assertFalse(viewModel.validateSearchData(param1, param2, param3))

    verify(observer).onChanged(&quot;Data not valid&quot;)
}
</code></pre>
<p>This is the method I am trying to test</p>
<pre><code>fun validateSearchData(param1: Int, param2: Int, param3: String): Boolean {
    var valid: Boolean = false

    if (param1 == 0 || param2 == 0 || param3.isBlank()) {
        dialogMessageLiveData.postValue(&quot;Data not valid&quot;)
    } else {
        valid = true
    }

    return valid
}
</code></pre>
<p>I am not sure what else to do to fix this, can anyone suggest another solution?</p>
",https://stackoverflow.com/questions/55616177/unit-testing-livedata-android-os-looper-not-mocked,"['android', 'unit-testing', 'mockito', 'android-architecture-components', 'android-livedata']",7736,True,23,2
Unit Testing a KafkaListenerErrorHandler,"<p>I have a test listener:</p>

<pre><code>@KafkaListener(topics = TEST_TOPIC)
public void consume(
        ConsumerRecord&lt;String, Map&gt; consumerRecord,
        @Payload String message) {
}
</code></pre>

<p>And a test producer:</p>

<pre><code>@Test
public void throwExceptionTest() throws Exception {
    Exception kafkaException = new Exception(""test exception"");
    kafkaTemplate.send(TEST_TOPIC, ""testKey"", kafkaException);
}
</code></pre>

<p>And I am trying to unit test the Kafka Listener Error handler:</p>

<pre><code>@Component
@FunctionalInterface
public interface KafkaListenerErrorHandler {

Logger logger = LoggerFactory.getLogger(KafkaListenerErrorHandler.class);


/**
 * Handle the error.
 * @param message the spring-messaging message.
 * @param exception the exception the listener threw, wrapped in a
 * {@link ListenerExecutionFailedException}.
 * @return the return value is ignored unless the annotated method has a
 * {@code @SendTo} annotation.
 */
Object handleError(Message&lt;?&gt; message, ListenerExecutionFailedException exception);

/**
 * Handle the error.
 * @param message the spring-messaging message.
 * @param exception the exception the listener threw, wrapped in a
 * {@link ListenerExecutionFailedException}.
 * @param consumer the consumer.
 * @return the return value is ignored unless the annotated method has a
 * {@code @SendTo} annotation.
 */
default Object handleError(Message&lt;?&gt; message, ListenerExecutionFailedException exception,
                           Consumer&lt;?, ?&gt; consumer) {
    logger.info(String.format(""KafkaListenerErrorHandler:%s"", exception.getMessage()));
    return handleError(message, exception);
}
</code></pre>

<p>}</p>

<p>Having trouble figuring out how to throw an error on purpose that would trigger that handler.</p>

<p>Any help would be appreciated.</p>
",https://stackoverflow.com/questions/58701661/unit-testing-a-kafkalistenererrorhandler,"['java', 'spring-boot', 'unit-testing', 'apache-kafka', 'spring-kafka']",1013,False,4,0
Unit Testing With Gin-Gonic,"<p>My project is split into three main components: controllers, services, and models. When a route is queried via the URI, the controllers are called, which then call the services to interact with the models, which then interact with the database via gorm.</p>

<p>I am trying to write unit tests for the controllers, but I'm having a hard time understanding how to properly mock the services layer while mocking the gin layer. I can get a mocked gin context, but I'm not able to mock the service layer within my controller method. Below is my code:</p>

<p>resourceController.go</p>

<pre><code>package controllers

import (
    ""MyApi/models""
    ""MyApi/services""
    ""github.com/gin-gonic/gin""
    ""net/http""
)

func GetResourceById(c *gin.Context) {
    id := c.Param(""id"")
    resource, err := services.GetResourceById(id)

    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{""status"": http.StatusBadRequest, ""message"": err})
        return
    } else if resource.ID == 0 {
        c.JSON(http.StatusNotFound, gin.H{""status"": http.StatusNotFound, ""message"": ""Resource with id:""+id+"" does not exist""})
        return
    }

    c.JSON(http.StatusOK, gin.H{
        ""id"": resource.ID,
        ""data1"": resource.Data1,
        ""data2"": resource.Data2,
    })
}

</code></pre>

<p>I want to test that the c.JSON is returning with the proper <code>http</code> status and other data. I need to mock the <code>id</code> variable, <code>err</code> variable, and <code>c.JSON</code> function, but when I try to set the <code>c.JSON</code> function in the test to my new function, I get an error saying <code>Cannot assign to c.JSON</code>.
Below is my attempt at writing a test:</p>

<p>resourceController_test.go</p>

<pre><code>package controllers

import (
    ""github.com/gin-gonic/gin""
    ""github.com/stretchr/testify/assert""
    ""net/http/httptest""
    ""testing""
)

func TestGetResourceById(t *testing.T) {
    var status int
    var body interface{}
    c, _ := gin.CreateTestContext(httptest.NewRecorder())
    c.JSON = func(stat int, object interface{}) {
        status = stat
        body = object
    }
    GetResourceById(c)
    assert.Equal(t, 4, 4)
}

</code></pre>

<p>How do I properly write a unit test to test whether the c.JSON is returning the proper values?</p>
",https://stackoverflow.com/questions/59186562/unit-testing-with-gin-gonic,"['unit-testing', 'go', 'testing', 'go-gin']",19089,True,12,2
Unit testing on STM32,"<p>I am looking for advice on how to do unit testing on my STM32F7 platform. What have people done in the past? What horror stories do you have? What would you do differently? What is problematic with my current plan?</p>

<h2>My Setup</h2>

<ul>
<li>STM32 Nucleo-144 with a custom carrier PCB</li>
<li><code>arm-atollic-eabi-gcc</code> compiler (no C++, for now)</li>
<li>Using Atollic TrueStudio as an IDE</li>
<li>Development done from Ubuntu 16.04</li>
<li>Running FreeRTOS on the board</li>
</ul>

<h2>My Testing Plan</h2>

<p>There are different levels of testing; I am specifically talking about unit testing a library / set of functionality that does NOT depend on external hardware. Things like ""does my ring buffer implementation correctly handle rolling over without memory leaks"" and ""does this bit-shift operation result in the correct endianness in the resulting variable""? So I am focused on those kinds of tests.</p>

<ul>
<li>Convert my project to compile with C++ (and all the associated <code>extern C</code> required)</li>
<li>Refactor my code into a ""library"" portion and an ""application"" portion.</li>
<li>Build <code>googletest</code> (this is what we use for other parts of our system) and link my library into it for testing.</li>
<li>Run the unit tests on the device while running a debug session through Atollic.</li>
</ul>
",https://stackoverflow.com/questions/57415026/unit-testing-on-stm32,"['stm32', 'nucleo', 'stm32f7']",2522,True,4,1
Unit testing lambda script,"<p>I wrote a lambda script to manage the life cycle of Amazon Machine Images using python and boto3. The script is working fine, but when I realized that I had to write unit tests for it, my nightmare began. I am not a develop and I am used to write scripts as SysAdmin.</p>

<p>I have already created unit tests for functions with return state like the following below and I works fine.</p>

<pre><code>def get_interface_wrapper(region, service, interface_type):
    interface_types = ['client', 'resource']
    interface = None

    if (type(region) == str) and (type(service) == str) and (type(interface_type) == str) and (interface_type in interface_types):
        interface = (""boto3."" + interface_type +
                     ""("" + ""service_name=service,"" + ""region_name=region)"")

    return interface

def get_interface(region, service, interface_type):
    return eval(get_interface_wrapper(region, service, interface_type))

#Unit tests
def test_get_interface_client(self):

    service = 'ec2'
    interface_expression = 'boto3.client(service_name=service,region_name=region)'
    client_interface = get_interface_wrapper(
        self.region, service, 'client')
    self.assertEqual(client_interface, interface_expression)


def test_get_interface_resource(self):

    service = 'ec2'
    interface_expression = 'boto3.resource(service_name=service,region_name=region)'
    resource_interface = get_interface_wrapper(
        self.region, service, 'resource')
    self.assertEqual(resource_interface, interface_expression)
</code></pre>

<p>However, for the following functions that have no return statement and rely on AWS endpoint, I am struggling to wrap my head around it. How I can a mock the endpoint or how I can change my code to create a unit test that does not rely on AWS endpoints.</p>

<pre><code>def update_states(actions, ec2_client, logs_client, log_group, log_stream, dryrun_enabled=True):
    for action in actions:

        action.update({'phase': 'planning', 'PlanningTime': datetime.utcnow(
        ).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'})
        put_log_events(logs_client, log_group, log_stream, [action])

        # The tag packer_ami_state_tagging_date is not set
        if (action['is_timestamp_present'] == True):

            if (action['action'] == 'update'):
                # The tag packer_ami_state_tagging_date is set, so update the state and tagging date
                try:

                    ec2_client.Image(action['ImageId']).create_tags(DryRun=dryrun_enabled, Tags=[{'Key': 'packer_ami_state', 'Value': action['new_packer_ami_state']},
                                                                                                 {'Key': 'packer_ami_state_tagging_date', 'Value': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'}, ])

                    operation_result = [
                        {'phase': 'execution', 'imageid': action['ImageId'], 'ExecutionTime':  datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z', 'Result': 'AMI state and tagging date was updated'}, ]

                except Exception as e:

                    operation_result = [
                        {'phase': 'execution', 'imageid': action['ImageId'], 'ExecutionTime': (datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'), 'Result': 'AMI state and tagging date was not updated', 'Error': e.args[0], }]

                finally:
                    put_log_events(logs_client, log_group,
                                   log_stream, operation_result)

            if (action['action'] == 'delete'):
                image = ec2_client.Image(action['ImageId'])
                snapshots = []
                for blockDevMapping in image.block_device_mappings:
                    if 'Ebs' in blockDevMapping:
                        snapshots.append(blockDevMapping['Ebs']['SnapshotId'])

                try:
                    image.deregister(DryRun=dryrun_enabled)
                    operation_result = [
                        {'phase': 'execution', 'imageid': action['ImageId'], 'ExecutionTime':  datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z', 'Result': 'AMI was deregistered'}, ]

                except Exception as e:
                    operation_result = [
                        {'phase': 'execution', 'imageid': action['ImageId'], 'ExecutionTime': (datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'), 'Result': 'AMI was not deregistered', 'Error': e.args[0], }]

                finally:
                    put_log_events(logs_client, log_group,
                                   log_stream, operation_result)

                counter = 1
                for snapshotID in snapshots:
                    snapshot = ec2_client.Snapshot(snapshotID)

                    try:
                        snapshot.delete(DryRun=dryrun_enabled)
                        operation_result = [
                            {'phase': 'execution', 'imageid': action['ImageId'], 'ExecutionTime':  datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z', 'Result': 'SnapShot deleted', 'SnapShotID': snapshotID}, ]

                    except Exception as e:
                        operation_result = [
                            {'phase': 'execution', 'imageid': action['ImageId'], 'ExecutionTime': (datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'), 'Result': 'SnapShot not deleted', 'Error': e.args[0], 'SnapShotID': snapshotID}, ]

                    finally:
                        put_log_events(logs_client, log_group,
                                       log_stream, operation_result)

                    counter += 1

            if (action['action'] == 'none'):
                action.update(
                    {'OperationDate': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z', 'OperationResult': 'No action'})

                operation_result = [
                    {'phase': 'execution', 'imageid': action['ImageId'], 'ExecutionTime':  datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z', 'Result': 'No action'}, ]

                put_log_events(logs_client, log_group,
                               log_stream, operation_result)

        else:
            try:
                ec2_client.Image(action['ImageId']).create_tags(DryRun=dryrun_enabled, Tags=[
                    {'Key': 'packer_ami_state_tagging_date', 'Value': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'}, ])

                operation_result = [
                    {'phase': 'execution', 'imageid': action['ImageId'], 'ExecutionTime':  datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z', 'Result': 'Tag created'}, ]

            except Exception as e:
                operation_result = [
                    {'phase': 'execution', 'imageid': action['ImageId'], 'ExecutionTime': (datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'), 'Result': 'Tag not created', 'Error': e.args[0], }]

            finally:
                put_log_events(logs_client, log_group,
                               log_stream, operation_result)


def put_log_events(client, log_group_name, log_stream_name, log_events):
    log_stream = client.describe_log_streams(
        logGroupName=log_group_name,
        logStreamNamePrefix=log_stream_name
    )

    if (bool(log_stream['logStreams'])) and ('uploadSequenceToken' in log_stream['logStreams'][0]):
        response = {
            'nextSequenceToken': log_stream['logStreams'][0]['uploadSequenceToken']}
    else:
        response = {}

    for log_event in log_events:
        if bool(response):
            response = client.put_log_events(
                logGroupName=log_group_name,
                logStreamName=log_stream_name,
                logEvents=[
                    {
                        'timestamp': int(round(time.time() * 1000)),
                        'message': json.dumps(log_event)
                    },
                ],
                sequenceToken=response['nextSequenceToken']
            )
        else:
            response = client.put_log_events(
                logGroupName=log_group_name,
                logStreamName=log_stream_name,
                logEvents=[
                    {
                        'timestamp': int(round(time.time() * 1000)),
                        'message': json.dumps(log_event)
                    },
                ],
            )
</code></pre>
",https://stackoverflow.com/questions/58652322/unit-testing-lambda-script,"['python', 'amazon-web-services', 'unit-testing', 'boto3']",516,True,3,1
Simulating CancellationToken.IsCancellationRequested when unit testing,"<p>I would like to test a task that is supposed to run continuously until killed. Suppose the following method is being tested:</p>

<pre class=""lang-cs prettyprint-override""><code>public class Worker
{
  public async Task Run(CancellationToken cancellationToken)
  {
    while (!cancellationToken.IsCancellationRequested)
    {
      try
      {
        // do something like claim a resource
      }
      catch (Exception e)
      {
        // catch exceptions and print to the log
      }
      finally
      {
        // release the resource
      }
    }
  }
}
</code></pre>

<p>And a test case </p>

<pre class=""lang-cs prettyprint-override""><code>[TestCase]
public async System.Threading.Tasks.Task Run_ShallAlwaysReleaseResources()
{
  // Act
  await domainStateSerializationWorker.Run(new CancellationToken());  

  // Assert
  // assert that resource release has been called
}
</code></pre>

<p>The problem is that the task never terminates, because cancellation is never requested. Ultimately I would like to create a <code>CancellationToken</code> stub like <code>MockRepository.GenerateStub&lt;CancellationToken&gt;()</code> and tell it on which call to <code>IsCancellationRequested</code> return <code>true</code>, but <code>CancellationToken</code> is not a reference type so it is not possible.</p>

<p>So the question is how to make a test where <code>Run</code> executes for <code>n</code> iterations and then terminates? Is it possible without refactoring <code>Run</code>? </p>
",https://stackoverflow.com/questions/59088678/simulating-cancellationtoken-iscancellationrequested-when-unit-testing,"['c#', 'unit-testing', 'asynchronous', 'rhino-mocks']",14871,True,11,2
Angular unit testing form validation,"<p>I'm learning angular 8 and I'm using Karma for unit testing. I have created a basic registration form which works correctly but I'm facing issues in testing.</p>

<p>Upon testing I'm getting 2 failures </p>

<blockquote>
  <p>RegisterComponent > form should be valid
      Error: Expected validator to return Promise or Observable.</p>
</blockquote>

<p>and</p>

<blockquote>
  <p>RegisterComponent > should call onSubmit method
      Error:  : Expected a spy, but got FormGroup({ validator: Function, asyncValidator: null, _onCollectionChange: Function, pristine: true, touched: false, _onDisabledChange: [  ], controls: Object({ name: FormControl({ validator: Function, asyncValidator: null, _onCollectionChange: Function, pristine: true, touched: false, _onDisabledChange: [ Function ], _onChange: [ Function ], _pendingValue: '', value: '', status: 'INVALID', errors: Object({ required: true }), valueChanges: EventEmitter({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, __isAsync: false }), statusChanges: EventEmitter({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, __isAsync: false }), _parent:  }), email: FormControl({ validator: Function, asyncValidator: Function, _onCollectionChange: Function, pristine: true, touched: false, _onDisabledChange: [ Function ], _onChange: [ Function ], _pendingValue: '', value: '' ....
      Usage: expect().toHaveBeenCalledTimes()</p>
</blockquote>

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

<pre class=""lang-js prettyprint-override""><code>import { ActivatedRoute, Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { AuthenticationService } from '@/_services';
import { MustMatch } from '@/_helpers/validators';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
@Component({ templateUrl: 'register.component.html' })
export class RegisterComponent implements OnInit {
  registerForm: FormGroup;
  submitted = false;
  returnUrl: string;
  error = '';

  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService
  ) {
    if (this.authenticationService.currentUserValue) {
      this.router.navigate(['/']);
    }
  }

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', Validators.required, Validators.email],
      phone: ['', Validators.required],
      password: ['', Validators.required, Validators.minLength(6)],
      confirmPassword: ['', Validators.required],
    }, {
        validator: MustMatch('password', 'confirmPassword')
      });

    this.returnUrl = this.route.snapshot.queryParams.returnUrl || '/';
  }

  get f() {
    return this.registerForm.controls;
  }

  onSubmit() {
    this.submitted = true;
    if (this.registerForm.invalid) {
      return;
    }

    this.submitted = false;
  }
}
</code></pre>

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

<pre class=""lang-js prettyprint-override""><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { RegisterComponent } from './register.component';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { DebugElement } from '@angular/core';

describe('RegisterComponent', () =&gt; {
  let component: RegisterComponent;
  let fixture: ComponentFixture&lt;RegisterComponent&gt;;
  let de: DebugElement;
  let el: HTMLElement;
  const fakeActivatedRoute = {
    snapshot: {
      queryParams: {
        returnUrl: '/'
      }
    }
  };
  const routerSpy = jasmine.createSpyObj('Router', ['navigate']);

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule, HttpClientTestingModule],
      declarations: [RegisterComponent],
      providers: [
        { provide: Router, useValue: routerSpy },
        { provide: ActivatedRoute, useFactory: () =&gt; fakeActivatedRoute }
      ]

    }).compileComponents().then(() =&gt; {
      fixture = TestBed.createComponent(RegisterComponent);
      component = fixture.componentInstance;
      component.ngOnInit();
      fixture.detectChanges();
      de = fixture.debugElement.query(By.css('form'));
      el = de.nativeElement;
    });
  }));

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

  it('form invalid when empty', () =&gt; {
    component.registerForm.controls.name.setValue('');
    component.registerForm.controls.email.setValue('');
    component.registerForm.controls.phone.setValue('');
    component.registerForm.controls.password.setValue('');
    component.registerForm.controls.confirmPassword.setValue('');
    expect(component.registerForm.valid).toBeFalsy();
  });

  it('username field validity', () =&gt; {
    const name = component.registerForm.controls.name;
    expect(name.valid).toBeFalsy();

    name.setValue('');
    expect(name.hasError('required')).toBeTruthy();

  });

  it('email field validity', () =&gt; {
    const email = component.registerForm.controls.email;
    expect(email.valid).toBeFalsy();

    email.setValue('');
    expect(email.hasError('required')).toBeTruthy();
  });

  it('phone field validity', () =&gt; {
    const phone = component.registerForm.controls.phone;
    expect(phone.valid).toBeFalsy();

    phone.setValue('');
    expect(phone.hasError('required')).toBeTruthy();

  });

  it('password field validity', () =&gt; {
    const password = component.registerForm.controls.password;
    expect(password.valid).toBeFalsy();

    password.setValue('');
    expect(password.hasError('required')).toBeTruthy();

  });

  it('confirmPassword field validity', () =&gt; {
    const confirmPassword = component.registerForm.controls.confirmPassword;
    expect(confirmPassword.valid).toBeFalsy();

    confirmPassword.setValue('');
    expect(confirmPassword.hasError('required')).toBeTruthy();

  });

  it('should set submitted to true', () =&gt; {
    component.onSubmit();
    expect(component.submitted).toBeTruthy();
  });

  it('should call onSubmit method', () =&gt; {
    spyOn(component, 'onSubmit');
    el = fixture.debugElement.query(By.css('button')).nativeElement;
    el.click();
    expect(component.registerForm).toHaveBeenCalledTimes(1);
  });

  it('form should be valid', () =&gt; {
    component.registerForm.controls.name.setValue('sasd');
    component.registerForm.controls.email.setValue('sadasd@asd.com');
    component.registerForm.controls.phone.setValue('132456789');
    component.registerForm.controls.password.setValue('qwerty');
    component.registerForm.controls.confirmPassword.setValue('qwerty');
    expect(component.registerForm.valid).toBeTruthy();
  });
});
</code></pre>

<p>I can't seem to understand what is causing this issue. Have gone through several docs and tutorials for this but it doesn't seem to work.</p>
",https://stackoverflow.com/questions/57457293/angular-unit-testing-form-validation,"['angular', 'forms', 'unit-testing', 'validation']",42824,True,11,2
Unit testing express router,"<p>I have a route similar to the below, and I am trying to wrap my head around how to test this using Mocha, Chai, and SinonJS.</p>

<pre><code>router.get(""/favorites"", async function(req, res) {
    try {
        let cachedItem = cache.get(""FAVORITES"");
        if (cachedItem) {
            res.status(global.HttpCode.Ok).send(cachedItem);
        } else {
            var pool = await poolPromiseWebMart;
            let result = await pool.request().execute(""dbo.GetFavorites"");
            cache.put(""FAVORITES"", result.recordset, ONE_MINUTE * NUMBER_OF_MINUTES);
            res.status(global.HttpCode.Ok).send(result.recordset);
        }
    } catch (error) {
        return req.logHelper.log(error, ""dbo.GetFavorites"");
    }
});
</code></pre>

<p>I have just started looking into SinonJS and figuring that I will need to stub out these dependencies but not really sure where to start.  Can a route even be called without the server running?</p>

<p>I have tried calling it using</p>

<pre><code>return request(app)
  .get(""/favorites"")
  .then(function(response) {
     //Testing here
  })
</code></pre>

<p>But I run into a lot of issues with dependencies.  Thanks in advance!</p>
",https://stackoverflow.com/questions/55746901/unit-testing-express-router,"['node.js', 'mocha.js', 'sinon', 'chai']",991,False,2,0
Unit testing SQL scripts,"<p>For below script written in <code>.sql</code> files:</p>

<pre><code>if not exists (select * from sys.tables where name='abc_form')
    CREATE TABLE abc_forms (
        x BIGINT IDENTITY, 
        y VARCHAR(60), 
        PRIMARY KEY (x)
    )
</code></pre>

<hr>

<p>Above script has a bug in table name.</p>

<p>For programming languages like Java/C, compiler help resolve most of the name resolutions</p>

<p>For any SQL script, How should one approach unit testing it? static analysis...</p>
",https://stackoverflow.com/questions/55183385/unit-testing-sql-scripts,"['database', 'unit-testing', 'tsql', 'sonarqube']",426,True,2,2
Unit testing curried functions,"<p>I am trying to figure out what the correct way of thinking about this is. I am trying to play around with some functional programming paradigm in python. I know it is not a functional language, but the concepts can translate.</p>

<p>Lets say I have a set of functions like:</p>

<pre><code>def add(x: int, y: int) -&gt; int:
  return x + y

add_one = partial(add, y=1)
add_two = partial(add, y=2)
add_three = partial(add, y=3)

fut = lambda x: add_three(add_one(add_two(x)))
</code></pre>

<p>The question is, do I unit test the function under test (<code>fut</code>)? And would I unit test <code>add_one</code>, <code>add_two</code> and <code>add_three</code>?</p>

<p>It is an implementation detail in my mind that <code>add_one</code> is a partial of <code>add</code>, but it feels weird to unit test if I have ""complete"" coverage of <code>add</code>. </p>

<p>Lets extend this for a minute and extend it towards a more realistic system.</p>

<pre><code>class Save(Protocol):
  def __call__(self, x: int): ...

def save_to_disk(x: int, file_name:str) -&gt; None:
  """"""
  Implementation of saving something to a disk
  """"""
  ...

save: Save = partial(save_to_disk, file_name=""random_file"")

def add(x: int, y: int) -&gt; int:
  return x + y

add_one = partial(add, y=1)

fut: Save = lambda x: save(add_one(x))
</code></pre>

<p>I now have a function that handles IO and some work generating the data to save. Do I unit test <code>fut</code> here? Do I assume that the currying is just implementation details and leave it for integration tests?</p>

<p>I feel a little lost on this one because in a OO world, I know how I could unit test some of this chaining with mocks but it seems backwards and against some of the functional paradigm and what I am actively trying to avoid by playing around with it.</p>

<p>My gut feeling right now is that the curried functions are integration testing and as long as everything is tested individually showing the components work than the chain I can leave for integration testing I can prove that the system as a whole works.</p>
",https://stackoverflow.com/questions/57262993/unit-testing-curried-functions,"['python', 'unit-testing', 'functional-programming']",695,False,2,2
Unit testing chained promises,"<p>How would I unit test a class method that calls an imported class's method that is a promise? I have the following structure:</p>

<pre><code>import { SomeClass } from 'some-library';

class MyClass extends AnotherClass {
  myMethod() {
    const someClass = new SomeClass();

    return someClass.somePromiseMethod('someParam')
      .then(response =&gt; response.data)
      .then(response =&gt; {
        // Do stuff
      });
  }
}
</code></pre>

<p>I have the following test</p>

<pre><code>describe('myMethod', () =&gt; {
  it('does something', async () =&gt; {
    const inst = new MyClass();
    const stub = sinon.stub(SomeClass, 'somePromiseMethod')
      .resolves(Promise.resolve({
        data: [],
      }));

    await inst.myMethod();

    expect(stub.callCount).to.equal(1);
  });
});
</code></pre>

<p>Which is still pretty bare as I'm not sure how to approach this. Would it be better to break down the code in the <code>then</code>s?</p>

<p><strong>UPDATE</strong></p>

<p>Apparently <code>SomeClass</code> is a singleton and sinon was throwing an error saying <code>somePromiseMethod</code> is a <code>non-existent own property</code>. I changed the stub to call on its <code>prototype</code> instead and now the stub is being called.</p>

<pre><code>class MyClass extends AnotherClass {
  myMethod() {
    const someClassInstance = SomeClass.getInstance();

    return someClassInstance.somePromiseMethod('someParam')
      .then(response =&gt; response.data)
      .then(response =&gt; {
        // Do stuff
      });
  }
}


describe('myMethod', () =&gt; {
  it('does something', async () =&gt; {
    const inst = new MyClass();
    const stub = sinon.stub(SomeClass.prototype, 'somePromiseMethod')
      .resolves(Promise.resolve({
        data: [],
      }));

    await inst.myMethod();

    expect(stub.callCount).to.equal(1);
  });
});
</code></pre>

<p>Now, since then second <code>then</code> would just return <code>data</code>, I could just put <code>//Do stuff</code> in a separate function and test that.</p>
",https://stackoverflow.com/questions/56069568/unit-testing-chained-promises,"['javascript', 'unit-testing', 'promise', 'sinon']",287,True,0,1
unit testing login component,"<p>I want to unit test for login component. I am using reactive forms and Angular 7.</p>

<p>I created backend fake service I am calling that services. I tried below code but I am getting the following error: </p>

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

<p>How to call login method and how to subscribe that value?  </p>

<p>Please anyone help me on that.</p>

<p>signin.component.html</p>

<pre><code>     &lt;form
        class=""form""
        (ngSubmit)=""onSubmit()""
        [formGroup]=""signinForm""
        novalidate&gt;
        &lt;div fxLayout=""row wrap"" fxLayout.xs=""column"" fxLayoutAlign=""center center""&gt;
          &lt;div fxFlex=""100"" fxFlex.gt-md=""25"" fxFlex.gt-sm=""25""&gt;
            &lt;mat-card&gt;
              &lt;mat-card-header&gt;
                &lt;mat-card-title class=""_mat-title""&gt;
                  &lt;h5&gt;Sign In&lt;/h5&gt;
                &lt;/mat-card-title&gt;
              &lt;/mat-card-header&gt;
              &lt;mat-card-content&gt;
                &lt;div
                  fxLayout=""row wrap""
                  fxLayout.xs=""column""
                  fxLayoutAlign=""space-between stretch""&gt;
                  &lt;div fxFlex=""100"" fxFlex.gt-md=""100"" fxFlex.gt-sm=""100""&gt;
                    &lt;mat-form-field&gt;
                      &lt;input
                        matInput
                        placeholder=""Username(Email)""
                        formControlName=""username""
                        value=""{{username}}""
                        /&gt;
                      &lt;mat-error
                        *ngIf=""submitted &amp;&amp;
                        !signinForm.controls['username'].errors?.required &amp;&amp;
                        signinForm.controls['username'].errors?.email &amp;&amp;
                        signinForm.controls['username'].dirty""&gt;
                        Please enter a valid email address
                      &lt;/mat-error&gt;
                      &lt;mat-error
                        *ngIf=""submitted &amp;&amp;
                        signinForm.controls['username'].errors?.required &amp;&amp;
                        signinForm.controls['username']""&gt;
                        Email is required
                      &lt;/mat-error&gt;
                    &lt;/mat-form-field&gt;
                  &lt;/div&gt;

                  &lt;div fxFlex=""100"" fxFlex.gt-md=""100"" fxFlex.gt-sm=""100""&gt;
                    &lt;mat-form-field&gt;
                      &lt;input
                        matInput
                        placeholder=""Password""
                        type=""password""
                        formControlName=""password""
                        value=""{{password}}""
                        /&gt;
                      &lt;mat-error
                        *ngIf=""submitted &amp;&amp;
                        signinForm.controls['password'].errors?.required &amp;&amp;
                        signinForm.controls['password']""&gt;
                        Password is required
                      &lt;/mat-error&gt;
                    &lt;/mat-form-field&gt;
                  &lt;/div&gt;
                  &lt;div fxFlex=""100"" fxFlex.gt-md=""100"" fxFlex.gt-sm=""100""&gt;
                    &lt;div class=""_rem-me""&gt;
                      &lt;mat-checkbox
                        color=""primary""
                        class=""_checkbox""
                        formControlName=""ischeck""&gt;Remember me&lt;/mat-checkbox&gt;
                    &lt;/div&gt;
                    &lt;div class=""_forgot-link""&gt;
                      &lt;a href="""" class=""_link""&gt;Forgot your username or password?&lt;/a&gt;
                    &lt;/div&gt;
                  &lt;/div&gt;
                &lt;/div&gt;
              &lt;/mat-card-content&gt;
              &lt;mat-card-actions&gt;
                &lt;div class=""_button-row""&gt;
                  &lt;button mat-raised-button color=""primary""&gt;
                    Submit
                  &lt;/button&gt;
                &lt;/div&gt;
              &lt;/mat-card-actions&gt;
            &lt;/mat-card&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/form&gt;

signin.component.ts 

import {Component, OnInit, Input }from '@angular/core'; 
import {ErrorStateMatcher }from '@angular/material/core'; 
import {
  FormControl, 
  FormGroup, 
  FormGroupDirective, 
  NgForm, 
  FormBuilder, 
  Validators
}from '@angular/forms'; 
import {SigninService }from '../../../services/signin/signin.service'; 
import {first }from 'rxjs/operators'; 
import {Router, ActivatedRoute }from '@angular/router'; 

/** Error when invalid control is dirty, touched, or submitted. */

@Component( {
  selector:'ap-signin', 
  templateUrl:'./signin.component.html', 
  styleUrls:['./signin.component.scss']
})
export class SigninComponent implements OnInit {
  // spinner
  pageLoaded:boolean; 
  @Input()diameter = 64; 
  @Input()strokeWidth = 7; 

  signinForm:FormGroup; 
  username:string; 
  password:string; 
  returnUrl:string; 
  submitted = false; 
  accessRequestForm = false; 

  //ischeck = true; 
  // matcher = new MyErrorStateMatcher();

  constructor(
    private signinService:SigninService, 
    private route:ActivatedRoute, 
    private router:Router, 
    private fb:FormBuilder
  ) {
    this.pageLoaded = false; 
    // redirect to dashboard if already signed in
    if (this.signinService.currentUserValue) {
      this.router.navigate(['/']); 
    }
  }

  ngOnInit() {
    setTimeout(() =&gt;  {
      this.pageLoaded = true; 
    }, 500); 
    this.username = localStorage.getItem('username'); 
    this.password = localStorage.getItem('password'); 
    // Form validation
    this.formValidation(); 
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; 
  }

  // Form validation
  formValidation():void {
    this.signinForm = this.fb.group( {
      username:[null, [Validators.compose([Validators.required, Validators.email])]], 
      password:[null, [Validators.compose([Validators.required])]],
      ischeck: [false, Validators.required]
    }); 
  }

  get f() {
    return this.signinForm.controls; 
  }

  onSubmit() {
    this.submitted = true; 
    //alert(this.f.ischeck.value);
    if (this.signinForm.invalid) {
      return; 
    }
    this.pageLoaded = true; 
    this.signinService
      .signin(this.f.username.value, this.f.password.value)
      .pipe(first())
      .subscribe(
        data =&gt;  {
          if (this.f.ischeck.value) {
          localStorage.setItem('username', this.f.username.value); 
          localStorage.setItem('password', this.f.password.value); 
          this.router.navigate([this.returnUrl]); 
          }else {
            localStorage.clear(); 
            this.router.navigate([this.returnUrl]); 
            }
        }, 
        err =&gt;  {
          this.pageLoaded = false; 
        }); 
  }

}

signin.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { SigninComponent } from './signin.component';
import { RouterTestingModule } from '@angular/router/testing';
import { CoreModule } from '../../core.module';
import { FeaturesModule } from '../../../features/features.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 
import { HttpClientModule } from '@angular/common/http';
import { SigninService, User } from '../../../services/signin/signin.service'
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';


fdescribe('SigninComponent', () =&gt; {
  let signinComponent: SigninComponent;
  let signinService: SigninService;
  let fixture: ComponentFixture&lt;SigninComponent&gt;;
  let de: DebugElement;
  let el: HTMLElement;


  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        CoreModule,
        FeaturesModule,
        BrowserAnimationsModule,
        HttpClientModule,
        FormsModule,
        ReactiveFormsModule
      ],
      declarations: [ ],
      providers: [SigninService],

    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    const fixture = TestBed.createComponent(SigninComponent);
    signinComponent = fixture.componentInstance;
    //el = de.nativeElement;
    fixture.detectChanges();
  });

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


  it('should call auth signin method', () =&gt; {
    let loginElement: DebugElement;
    const debugElement = fixture.debugElement;
    let signinService = debugElement.injector.get(SigninService);
    let loginSpy = spyOn(signinService, 'signin').and.callThrough();
    loginElement = fixture.debugElement.query(By.css('form'));
    signinComponent.signinForm.controls['username'].setValue('test@hp.com');
    signinComponent.signinForm.controls['password'].setValue('12345');
    loginElement.triggerEventHandler('ngSubmit', null);
    expect(loginSpy).toHaveBeenCalledTimes(1);



  });

});
</code></pre>
",https://stackoverflow.com/questions/55177118/unit-testing-login-component,"['angular', 'unit-testing', 'angular7']",1250,False,0,1
Directive unit testing fails,"<p>I am using <code>jest.js</code> for testing with my angular app. here is the directive I use in html:</p>

<pre><code>&lt;textarea errorHighlighter formControlName=""Url"" name=""Url"" cols=""50"" rows=""5""
                                placeholder=""Enter Page URL"" (ngModelChange)=""pageUrlChanges($event)""&gt;&lt;/textarea&gt;
</code></pre>

<p>here is my directive.ts file:</p>

<pre><code>import { Directive, ElementRef, SimpleChanges, HostListener, Renderer2 } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[errorHighlighter]'
})
export class ErrorHighlighterDirective {

  constructor(private el: ElementRef, private control: NgControl, private renderer: Renderer2) { }

  @HostListener('input') oninput() {
    if (this.el.nativeElement &amp;&amp; this.control) {
      if (this.control.control.status === 'INVALID') {
        this.renderer.addClass(this.el.nativeElement, 'has-err');
      } else {
        this.renderer.removeClass(this.el.nativeElement, 'has-err');
      }
    }
  }

}
</code></pre>

<p>this is written to show the error border around the input field. I am trying to test the same like this:</p>

<pre><code>import { ErrorHighlighterDirective } from './error-highlighter.directive';
import { Directive, ElementRef, SimpleChanges, HostListener, Renderer2, Component, DebugElement } from '@angular/core';
import { NgControl, FormGroup, FormsModule, FormControl, ReactiveFormsModule } from '@angular/forms';
import { TestBed, ComponentFixture } from '@angular/core/testing';

@Component({
    template: `&lt;input errorHighlighter formControlName=""Url"" type=""text""&gt;`
})
class TestHighlighterComponent { }



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

    let component: TestHighlighterComponent;
    let fixture: ComponentFixture&lt;TestHighlighterComponent&gt;;
    let inputEl: DebugElement;

    const fg: FormGroup = new FormGroup({
        'Url': new FormControl('')
    });

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [TestHighlighterComponent, ErrorHighlighterDirective],
            imports: [FormsModule, ReactiveFormsModule],
            providers: [
                { provide: NgControl, useValue: fg }
            ]
        });
        fixture = TestBed.createComponent(TestHighlighterComponent);
        component = fixture.componentInstance;
        inputEl = fixture.debugElement.query(By.css('input'));
    });


    it('should create an instance', () =&gt; {
        const directive = new ErrorHighlighterDirective(inputEl, fg, Renderer2);
        expect(directive).toBeTruthy();
    });

});
</code></pre>

<p>But the test not succeeds. getting error like below:</p>

<pre><code>● Test suite failed to run

    TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    src/app/directives/error-highlighter.directive.spec.ts:33:46 - error TS2304: Cannot find name 'By'.

    33         inputEl = fixture.debugElement.query(By.css('input'));
                                                    ~~
    src/app/directives/error-highlighter.directive.spec.ts:38:66 - error TS2345: Argument of type 'FormGroup' is not assignable to parameter of type 'NgControl'.
      Type 'FormGroup' is missing the following properties from type 'NgControl': name, valueAccessor, viewToModelUpdate, control, path

    38         const directive = new ErrorHighlighterDirective(inputEl, fg, Renderer2);
</code></pre>

<p>Any one help me to understand and fix these issue? I am not much familiar with angular test either jest.js.</p>
",https://stackoverflow.com/questions/58437237/directive-unit-testing-fails,"['jestjs', 'angular-directive', 'angular8', 'angular-test', 'angular-jest']",812,True,0,1
NPE while unit testing,"<p>I'm trying to write unit test for my method called <code>getBestSellers()</code>.</p>

<p>Here it is:</p>

<pre><code>package bookstore.scraper.book.scrapingtypeservice;

import bookstore.scraper.enums.Bookstore;
import bookstore.scraper.book.Book;
import bookstore.scraper.fetcher.empik.EmpikFetchingBookService;
import bookstore.scraper.fetcher.merlin.MerlinFetchingBookService;
import bookstore.scraper.urlproperties.EmpikUrlProperties;
import bookstore.scraper.urlproperties.MerlinUrlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.EnumMap;
import java.util.List;
import java.util.Map;

import static bookstore.scraper.utilities.JSoupConnector.connect;

@Service
public class BestSellersService {

    private final EmpikUrlProperties empikUrlProperties;
    private final MerlinUrlProperties merlinUrlProperties;
    private final EmpikFetchingBookService empikBookService;
    private final MerlinFetchingBookService merlinBookService;

    @Autowired
    public BestSellersService(EmpikFetchingBookService empikBookService, MerlinFetchingBookService merlinBookService, EmpikUrlProperties empikUrlProperties, MerlinUrlProperties merlinUrlProperties) {
        this.empikBookService = empikBookService;
        this.merlinBookService = merlinBookService;
        this.empikUrlProperties = empikUrlProperties;
        this.merlinUrlProperties = merlinUrlProperties;
    }

    public Map&lt;Bookstore, List&lt;Book&gt;&gt; getBestSellers() {
        Map&lt;Bookstore, List&lt;Book&gt;&gt; bookstoreWithBestSellers = new EnumMap&lt;&gt;(Bookstore.class);

        bookstoreWithBestSellers.put(Bookstore.EMPIK, empikBookService
                .get5BestSellersEmpik(connect(empikUrlProperties.getEmpik().getBestSellers())));
        bookstoreWithBestSellers.put(Bookstore.MERLIN, merlinBookService
                .get5BestSellersMerlin(connect(merlinUrlProperties.getMerlin().getBestSellers())));

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

<p>So, first I prepared test which looks like this: </p>

<pre><code>package bookstore.scraper.book.scrapingtypeservice;

import bookstore.scraper.book.Book;
import bookstore.scraper.dataprovider.EmpikBookProvider;
import bookstore.scraper.dataprovider.MerlinBookProvider;
import bookstore.scraper.enums.Bookstore;
import bookstore.scraper.fetcher.empik.EmpikFetchingBookService;
import bookstore.scraper.fetcher.merlin.MerlinFetchingBookService;
import bookstore.scraper.urlproperties.EmpikUrlProperties;
import bookstore.scraper.urlproperties.MerlinUrlProperties;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.List;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class BestSellersServiceTest {

    @Mock
    private EmpikFetchingBookService empikBookService;
    @Mock
    private MerlinFetchingBookService merlinBookService;
    @Mock
    private EmpikUrlProperties empikUrlProperties;
    @Mock
    private MerlinUrlProperties merlinUrlProperties;

    @InjectMocks
    private BestSellersService bestSellersService;

    @Test
    public void getBestSellers() {
        List&lt;Book&gt; merlinBestsellers = EmpikBookProvider.prepare5Bestsellers();
        List&lt;Book&gt; empikBestsellers = MerlinBookProvider.prepare5Bestsellers();

        when(empikBookService.get5BestSellersEmpik(any())).thenReturn(empikBestsellers);
        when(merlinBookService.get5BestSellersMerlin(any())).thenReturn(merlinBestsellers);
        //when(empikUrlProperties.getEmpik().getBestSellers()).thenReturn(anyString());
        //when(merlinUrlProperties.getMerlin().getBestSellers()).thenReturn(anyString());

        Map&lt;Bookstore, List&lt;Book&gt;&gt; actualMap = bestSellersService.getBestSellers();
        Map&lt;Bookstore, List&lt;Book&gt;&gt; expectedMap = null;

        assertEquals(expectedMap, actualMap);
        assertThat(actualMap).hasSize(expectedMap.size());
    }
}
</code></pre>

<p>Without setting behaviour for properties classes as I thought it is unnecessary, because I put <code>any()</code> when calling <code>empikBookService.get5BestSellersEmpik</code> (same for <code>merlinBookService</code>) but it threw NPE when calling </p>

<pre><code>bookstoreWithBestSellers.put(Bookstore.EMPIK, empikBookService
                .get5BestSellersEmpik(connect(empikUrlProperties.getEmpik().getBestSellers())));
</code></pre>

<p>I've debugged it and I have seen that </p>

<pre><code>empikUrlProperties.getEmpik().getBestSellers()))
</code></pre>

<p>was given me NPE.
So I set behaviour like this:</p>

<pre><code>when(empikUrlProperties.getEmpik().getBestSellers()).thenReturn(anyString());
when(merlinUrlProperties.getMerlin().getBestSellers()).thenReturn(anyString());
</code></pre>

<p>and now it is giving me here NPE with stactrace:</p>

<pre><code>ava.lang.NullPointerException
    at bookstore.scraper.book.scrapingtypeservice.BestSellersServiceTest.getBestSellers(BestSellersServiceTest.java:48)
    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)
.
.
.
</code></pre>

<p><code>connect</code> method used in tested method:</p>

<pre><code>@UtilityClass
public class JSoupConnector {

    public static Document connect(String url) {
        try {
            return Jsoup.connect(url).get();
        } catch (IOException e) {
            throw new IllegalArgumentException(""Cannot connect to"" + url);
        }
    }
}
</code></pre>

<p>Properties class (same for merlin)</p>

<pre><code>package bookstore.scraper.urlproperties;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Getter
@Setter
@Component
@ConfigurationProperties(""external.library.url"")
public class EmpikUrlProperties {

    private Empik empik = new Empik();

    @Getter
    @Setter
    public static class Empik {

        private String mostPreciseBook;
        private String bestSellers;
        private String concreteBook;
        private String romances;
        private String biographies;
        private String crime;
        private String guides;
        private String fantasy;
    }
}
</code></pre>

<p>What am I making wrong? Why it didnt work in the first place when I put <code>any()</code></p>
",https://stackoverflow.com/questions/57336935/npe-while-unit-testing,"['java', 'unit-testing', 'mockito']",759,True,0,2
Unit testing retries websocket,"<p>I would like to unit test the below function to see if there is n retries of the websocket connection</p>

<pre><code>ws = webSocket(url)

notification(action: string) {
    return this.ws.asObservable().pipe(
      retryWhen(errors =&gt;
        errors.pipe(concatMap((_, iteration) =&gt;
          timer(Math.pow(2, iteration) * 1000)),
          tap(e =&gt; console.log('test', e)),
          take(10))
      ),
      tap(e =&gt; console.log('st', e)),
      filter((e: any) =&gt; e.action === action));
  }
</code></pre>

<p>I am bit stucked on how to mock the websocket</p>

<pre><code>it('should make call 10 times', fakeAsync(() =&gt; {
    const service = TestBed.get(NotificationService);
    let wsSpy = new Subject()
    service.ws = wsSpy;
    service.filterNotification('test').subscribe(data =&gt; {
      expect(data).toBe('data')
    })
    wsSpy.error({ action: 'test' })
    tick(time)
    wsSpy.error({ action: 'test' })
    // sending error the first time cancels the subscription
    // Is there any other way to send the error many times
    wsSpy.next({ action: 'test' })
  }));
</code></pre>
",https://stackoverflow.com/questions/59088111/unit-testing-retries-websocket,"['angular', 'unit-testing', 'jasmine']",68,False,-1,1
c# - Unit testing HTTPWebRequest,"<p>I have a code to make HTTP web request and get the response.How to unit test invoke method and I found some links related to unit test HTTP web request and response but they are confusing for me.</p>

<p>I am looking to test response with out running any server.</p>

<p><strong>Unit test code:</strong></p>

<pre><code>        [TestMethod]
        public void TestMethod()
        {
            string request = ""request content"";
            WebServiceClass webServiceClass = new WebServiceClass();
            string actual_response;
            webServiceClass.InvokeService               
       (request,""POST"",""application/json"",""/invoke"",out actual_response);
            string expected_response=""response content"";
            Assert.AreEqual(actual_response, expected_response);

        }
</code></pre>

<p><strong>Actual code:</strong></p>

<pre><code>class WebServiceClass {

 private HttpWebRequest BuildHttpRequest(String requestMethod, String contentType,String uriExtension, int dataBytes)
        {
            String composeUrl = webServiceURL + ""/"" + uriExtension;
            Uri srvUri = new Uri(composeUrl);
            HttpWebRequest httprequest = (HttpWebRequest)HttpWebRequest.Create(srvUri);
            httprequest.Method = requestMethod;
            httprequest.ContentType = contentType;
            httprequest.KeepAlive = false;
            httprequest.Timeout = webSrvTimeOut;
            httprequest.ContentLength = dataBytes;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            httprequest.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =&gt; true;
            return httprequest;
        }


        public void InvokeService(String request, String requestMethod, String contentType,String uriExtension, out String response)
        {
            Encoding encoding = new UTF8Encoding();
            String serviceResponse = String.Empty;
            byte[] dataBytes = encoding.GetBytes(request);
            try
            {
                int dataLength = dataBytes.Length;
                HttpWebRequest httprequest = BuildHttpRequest(requestMethod, contentType, uriExtension, dataLength);
                using (StreamWriter writes = new StreamWriter(httprequest.GetRequestStream()))
                {
                    writes.Write(request);
                }
                using (HttpWebResponse httpresponse = (HttpWebResponse)httprequest.GetResponse())
                {
                    String httpstatuscode = httpresponse.StatusCode.ToString();
                    using (StreamReader reader = new StreamReader(httpresponse.GetResponseStream(), Encoding.UTF8))
                    {
                        serviceResponse = reader.ReadToEnd().ToString();

                    }
                }


            }
}
</code></pre>
",https://stackoverflow.com/questions/54187209/c-unit-testing-httpwebrequest,"['c#', '.net', 'unit-testing', 'httpwebrequest', 'moq']",1645,False,0,1
unit testing factory method,"<p>I want to unit test angular factory method which is performing some API call.</p>

<pre><code>fileUploadFcty.getImage(imageParams)
           .then(function (image) {
                  console.log(image)
               }
           });
</code></pre>

<p>when I unit tests this it is not showing anything inside the console. I have tried to mock it and returning the response data.</p>
",https://stackoverflow.com/questions/56847057/unit-testing-factory-method,"['javascript', 'angularjs', 'jasmine', 'karma-runner']",81,False,0,0
AssertionError in unit testing,"<p>while I was writing tests I got that error</p>

<blockquote>
<pre><code> assert response.status_code == status.HTTP_201_CREATED
</code></pre>
  
  <p>E       AssertionError: assert 415 == 201
  E         -415
  E         +201</p>
</blockquote>

<p><strong>models.py</strong></p>

<pre><code>class Product(TimeStamp):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
color = models.ManyToManyField(ColorOfProduct)
available = models.BooleanField(default=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', null=True, blank=True)
slug = models.SlugField(max_length=100, unique=True, blank=True)

def __str__(self):
    return f'{self.category} - {self.name}'
</code></pre>

<p><strong>tests.py</strong> looks like this</p>

<pre><code>class ProductTest(APITestCase):
def post_product(self, category, name, brand_name, color, available):
    url = reverse(ProductView.name)
    print(url)
    data = {
        'category': category,
        'name': name,
        'brand_name': brand_name,
        'color': color,
        'available': available,
    }

    response = self.client.post(url, data, format='json')
    return response

def test_post_and_get_product(self):
    new_category_name = 'Hewlet Packard'
    new_product_name = 'HP Zenbook'
    new_brand_name = 'HP'
    new_color = 'black'
    new_available = True
    response = self.post_product(
        new_category_name,
        new_product_name,
        new_brand_name,
        new_color,
        new_available,
    )
    assert response.status_code == status.HTTP_201_CREATED
    assert Product.objects.count() == 1
    assert Product.objects.get().name == new_product_name
</code></pre>

<p>I am indicating media type but when I check it throws error ""Unsupported media type""</p>

<p>how can I solve this issue?</p>
",https://stackoverflow.com/questions/57251798/assertionerror-in-unit-testing,"['python-3.x', 'django-models', 'django-rest-framework']",68,True,0,1
unit testing with ArgumentValidator.VerifyNotNullOrEmpty,"<p>I am doing unit testing. And I have the following method:</p>

<pre><code>  public PortfolioFileGetListDto(string documentsCaseNumber)
        {
            ArgumentValidator.VerifyNotNullOrEmpty(documentsCaseNumber, nameof(documentsCaseNumber));

            CaseNumber = documentsCaseNumber;
        }
</code></pre>

<p>and I try to unit test this method like so:</p>

<pre><code> [TestMethod]
        public void PortfolioFileGetListDto_Constructor_ShouldValidateParameters()
        {
            // Portfolio           
            Action act = () =&gt; new PortfolioFileGetListDto(null);
            act.Should().Throw&lt;ArgumentNullException&gt;().WithMessage(""Value cannot be null.\n\rParameter name: portfolio"");
        }
</code></pre>

<p>But if I debug the unit test, I get the following exception:</p>

<pre><code>System.ArgumentNullException: 'Value cannot be null.
Parameter name: documentsCaseNumber'
</code></pre>

<p>So how to pass this unit test?</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/54779513/unit-testing-with-argumentvalidator-verifynotnullorempty,"['c#', 'unit-testing']",118,True,0,2
"Angular, Subjects Unit Testing","<p>We have recently implemented a message service largely based on <a href=""http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject"" rel=""nofollow noreferrer"">this solution</a> in Angular 7, but we are stucked on the unit testing implementation.</p>

<p>We have this service:</p>

<pre><code>@Injectable()
export class MessageService {
  private subject = new Subject&lt;any&gt;();
  sendMessage(message: MessageInput) {
    this.subject.next(message);
  }
  clearMessage() {
    this.subject.next();
  }
  getMessage(): Observable&lt;any&gt; {
    return this.subject.asObservable();
  }
}
</code></pre>

<p>And we have this implemetation, listening for a message sent by another component:</p>

<pre><code>ngOnInit() {
this.subscription = this.messageService.getMessage().subscribe(
  (message: MessageInput) =&gt; {
    if (message) {
      .....
    }
  }, () =&gt; {
      .....
  }
)};
</code></pre>

<p>We want to unit test our implementation, but we are not able to mock the sending and receiving of the message. We are trying this:</p>

<pre><code>beforeEach(() =&gt; {
  TestBed.configureTestingModule({
    schemas: [NO_ERRORS_SCHEMA],
    declarations: [...],
    providers: [
      ...
      MessageService
    ],
    imports: [...]
  });
  fixture = TestBed.createComponent(...);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('makes ngOnInit expected calls', () =&gt; {
  const messageService: MessageService = fixture.debugElement.injector.get(
    MessageService
  );
  component.ngOnInit();
  expect(component.subscription).toBeDefined();
  const message: MessageInput = {text: TypeMessage...., data: '...'};
  const nextSpy = spyOn(messageService.getMessage(), 'subscribe');
  messageService.sendMessage(message);
  expect(nextSpy).toHaveBeenCalled();
});
</code></pre>

<p>We are a but lost there, could any one please help us? Thanks!</p>
",https://stackoverflow.com/questions/54782733/angular-subjects-unit-testing,"['angular', 'unit-testing', 'jasmine', 'rxjs', 'observable']",6004,True,0,2
Unit Testing Failed - AccordionComponent,"<p>I was importing <code>AccordionModule</code> inside module. But with ""<code>ng test</code>"", I'm getting below error in console-</p>

<pre><code>Error: StaticInjectorError[AccordionComponent]: 
  StaticInjectorError[AccordionComponent]: 
    NullInjectorError: No provider for AccordionComponent!
</code></pre>

<p>I already tried to import it inside <code>spec.ts</code> file and inside <code>component.ts</code> file, but still this error is coming.</p>

<p>Spec file:</p>

<pre><code>beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
        imports: [AccordionModule.forRoot()],
        declarations: [CBenefitComponent], providers: [DataService]
    }).compileComponents();
}));
beforeEach(() =&gt; {
    fixture = TestBed.createComponent(CBenefitComponent);
    component = fixture.componentInstance; fixture.detectChanges();
});

fit('should create', () =&gt; {
    expect(component).toBeTruthy();
});
</code></pre>

<p>And the CAFDetailModule : </p>

<pre><code>import { NgModule } from '@angular/core'; 
import { CommonModule } from '@angular/common'; 
import { FormsModule, ReactiveFormsModule} from '@angular/forms'; 
import { AccordionModule } from 'ngx-bootstrap/accordion'; 
@NgModule({ 
    imports: [ ReactiveFormsModule, CommonModule, AccordionModule.forRoot() 
    ], 
exports: [AccordionModule], 
}) 
export class CAFDetailModule { 
    constructor(){ 
        console.log('detail module loaded'); } 
}
</code></pre>
",https://stackoverflow.com/questions/55378606/unit-testing-failed-accordioncomponent,"['angular', 'unit-testing']",278,False,0,0
unit testing web api,"<p>We currently have a Web API (.Net core 2.1), it has a service injected which it calls.  the service is based on an interface, the service methods do the business logic and CRUD work.</p>

<p>We are using Entity Framework to talk to the db, using UnitOfWork pattern which the Services are using in their methods.  How do we test these calls, without hitting the db?  I see the Moq framework, but i'm not sure how does it avoid the db calls?  In order to create my controller i need to pass my service, whose constructor takes the unitofwork, done via .net dependency injection.</p>

<p>I'm not sure how to simulate the data portion.  Will Moq automatically do that, or do I need to setup fake data and then Moq will use that for my db calls?  for example if I want to check if a GET request returns data.  or a post returns Ok.</p>
",https://stackoverflow.com/questions/56175275/unit-testing-web-api,"['.net', 'unit-testing', 'asp.net-web-api', 'moq']",474,True,-1,1
Spring Boot Unit Testing,"<p>I'm currently developing a Rest service in Spring Boot and am attempting to develop unit tests.  My Rest controller takes the request and utilizes an Sftp Connector defined within another package to directly interface with our servers.  I've defined my test cases to mock the behavior of the Sftp Connector rather than have it execute with the mock data being fed into the Rest endpoints.  I've been getting a ton of error logs during testing showing that exceptions are being raised from the Sftp connector.  Which makes sense if the mock data sent to the endpoints is still being fed into the connector class.  I'm guessing that I'm not mocking the connector properly.  I've been unsuccessful so far in locating a method to mock the connector.  Is this possible?  Or can I only mock the classes defined within the same package as the test class?</p>

<p>Controller:</p>

<pre><code>package RestAPI;

import JSch.SFTP.SftpConnector;
import JSch.SFTP.fileInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;


@RestController
@Api( value = ""Test Rest Controller"", description = ""Basic test for SFTP 
connector with very basic operations."")
public class SftpRestController {

    private Properties getProperties(){ //used to get connection values from 
 external file
    InputStream input = null;
    Properties prop = new Properties(); //new property
    try{
        if(System.getProperty(""os.name"").contains(""Windows"")){
            input = new FileInputStream(""C:\\tmp\\application.properties""); //get resources stream
        }
        else{
            input = new FileInputStream(""application.properties"");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line;
        while((line = reader.readLine()) != null){
            String[] split = line.split(""="");
            prop.put(split[0], split[1]);
        }

    }catch(IOException IO){
        IO.printStackTrace();
    }finally{
        if(input != null )
            try{
                input.close(); //close the stream
            }catch(IOException IO2){
                IO2.printStackTrace();
            }
    }
    System.out.println(prop.getProperty(""sftp.port""));
    return prop;
}

@ApiOperation(value = ""Check that service is up and running."", response = String.class)
@RequestMapping(""/"")
public @ResponseBody String index(){ return ""Rest Test Service is up and running"";}


@ApiOperation(value = ""Upload a file"", response = String.class)
@PostMapping(value=""/Upload"") //uploads files so long as the files are defined in one structure in the form body
public @ResponseBody String multipartUpload(@RequestBody MultipartFile[] files, @RequestParam(""dest"") String dest){
    String fileMessage = """"; //need something to send back to the caller
    SftpConnector connector = new SftpConnector(this.getProperties()); //plugs properties into the constructor and opens a connection
    for( int i = 0; i &lt; files.length; i++ ){ //for each file uploaded
        connector.uploadFile(files[i], dest); //call the upload method with the file reference and where it's going
        fileMessage = fileMessage + files[i].getOriginalFilename() + "" has been uploaded to remote directory \n"";
    }
    connector.closeSFTPConnection(); //manually close the connection
    return fileMessage;
}

@ApiOperation(value = ""Downloads a file over SFTP and writes it to local file system specified"", response = String.class)
@GetMapping(value=""/Download"")
public @ResponseBody String downloadFile(@RequestParam(""fileName"") String fName, @RequestParam(""dest"") String dest){
    SftpConnector connector = new SftpConnector(this.getProperties()); //new connector
    connector.downloadFile(fName, dest); //pull the specified file down
    connector.closeSFTPConnection(); //close the connection
    return fName + "" has been downloaded to the specified local directory"";
}

@ApiOperation(value = ""Moves all files on a remote server from one directory to another based on file type specified"", response = String.class)
@PutMapping(value=""/moveFiles"")
public @ResponseBody String moveFiles(@RequestParam(""dir"") String origin, @RequestParam(""fileType"") String type,@RequestParam(""dest"") String dest){
    SftpConnector connector = new SftpConnector(this.getProperties());
    connector.moveFiles(origin, type, dest); //moves a group of files based file type from one directory to another
    connector.closeSFTPConnection();
    return ""All files have been moved."";
}

@ApiOperation(value = ""Moves a single specific file"", response = String.class)
@GetMapping(value=""/moveFile"")
public @ResponseBody String moveFile(@RequestParam(""dir"") String origFile, @RequestParam(""dest"") String dest){
    SftpConnector connector = new SftpConnector(this.getProperties());
    connector.moveFile(origFile, dest); //moves a single file.  file name must be specified.
    connector.closeSFTPConnection();
    return FilenameUtils.getName(origFile) + "" has been moved to "" + dest;
}

@ApiOperation(value = ""Gets a specified file stream and returns it as a string"", response = String.class)
@GetMapping(value=""/readFile"")
public @ResponseBody String readFile(@RequestParam(""path"") String path){
    String fileContents;
    try{
        SftpConnector connector = new SftpConnector(this.getProperties());
        InputStream fis = connector.readFile(path); //gets an open file stream
        fileContents = IOUtils.toString(fis,""UTF-8""); //takes a file stream, reads into variable in specified encoding
        fis.close(); //closes the stream
        connector.closeSFTPConnection();
    }catch(IOException IO){
        fileContents = IO.toString();
    }
    return fileContents;
}

@ApiOperation(value=""Returns a list of file names as a string"", response = String.class)
@GetMapping(value=""/listFiles"")
public @ResponseBody String fileNames(@RequestParam(""dir"") String origin, @RequestParam(""fileType"") String type){
    String base = """";
    try{
        SftpConnector connector = new SftpConnector(this.getProperties());
        Collection&lt;fileInfo&gt; files = connector.listFiles(origin, type); //gets a list of files with name, type, and an input stream
        Iterator&lt;fileInfo&gt; iterator = files.iterator(); //iterator to roll over collection
        while(iterator.hasNext()){ //while not empty
            fileInfo thisFile = iterator.next(); //get the next fileInfo
            base = base + thisFile.getName() + '\n' ; //write the name to the base string
            thisFile.getFileStream().close(); //close the file stream
        }
        connector.closeSFTPConnection();
    }catch(Exception ex){
        ex.printStackTrace();
    }
    return base;
}

@ApiOperation(value = ""Moves a file by the connectors readFile and writeFile methods rather than SFTP rename"", response = String.class)
@GetMapping(value=""/test"")
public @ResponseBody String StreamTest(@RequestParam(""file"") String file, @RequestParam(""dest"") String dest){
    SftpConnector connector = new SftpConnector(this.getProperties());
    connector.writeFile(dest, FilenameUtils.getName(file), connector.readFile(file));
    connector.closeSFTPConnection();
    return file + "" has been successfully read, and written to destination"";
}
}
</code></pre>

<p>Sftp Connector:</p>

<pre><code>package JSch.SFTP;

import com.jcraft.jsch.*;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.*;

@Component
public class SftpConnector {
private String sftpHost;
private String sftpUser;
private int sftpPort;
private String sftpPass;
private Session session = null;
private ChannelSftp channelSftp = null;

public String getSftpHost() {
    return sftpHost;
}

public void setSftpHost(String sftpHost) {
    this.sftpHost = sftpHost;
}

public String getSftpUser() {
    return sftpUser;
}

public void setSftpUser(String sftpUser) {
    this.sftpUser = sftpUser;
}

public int getSftpPort() {
    return sftpPort;
}

public void setSftpPort(int sftpPort) {
    this.sftpPort = sftpPort;
}

public String getSftpPass() {
    return sftpPass;
}

public void setSftpPass(String sftpPass) {
    this.sftpPass = sftpPass;
}

public void setConnectionVars(String host, String user, String password, int port){
    this.setSftpHost(host);
    this.setSftpPort(port);
    this.setSftpUser(user);
    this.setSftpPass(password);
}

public SftpConnector(Properties prop){
    this.setConnectionVars(prop.getProperty(""sftp.host""), prop.getProperty(""sftp.user""), prop.getProperty(""sftp.pass""), Integer.parseInt(prop.getProperty(""sftp.port""))); //set the connection variables
    this.openSFTPConnection(); //open the sftp connection
}

public Session getSession() {
    return session;
}

public void setSession(Session session) {
    this.session = session;
}

public ChannelSftp getChannelSftp() {
    return channelSftp;
}

public void setChannelSftp(ChannelSftp channelSftp) {
    this.channelSftp = channelSftp;
}

public void openSFTPConnection(){
    try{
        JSch jsch = new JSch(); //create the new JSch var
        Session baseSession = jsch.getSession(this.getSftpUser(), this.getSftpHost(),this.getSftpPort()); //establish the ssh session info
        baseSession.setPassword(this.getSftpPass()); //auth over password
        baseSession.setConfig(""StrictHostKeyChecking"",""no""); // don't require hosting key check will need to change after testing
        baseSession.setConfig(""PreferredAuthentications"",""password""); //used to omit kerberos authentication
        this.setSession(baseSession); //set the session to private variable
        this.getSession().connect(); //open the session
        ChannelSftp tempChannel = (ChannelSftp) this.getSession().openChannel(""sftp""); //create an SFTP channel
        this.setChannelSftp(tempChannel); //set the channel to the private variable
        this.getChannelSftp().connect(); //open the SFTP connection
    }catch(JSchException e){
        e.printStackTrace();
    }
}

public void closeSFTPConnection(){
    try{
        if(this.getChannelSftp().isConnected()){ //if the channel is open so must be the session close both
            this.getChannelSftp().disconnect();
            this.getSession().disconnect();
        }else{ //if the channel is closed check to see if the session is still open
            if(this.getSession().isConnected()){
                this.getSession().disconnect();
            }
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

public Collection&lt;fileInfo&gt; listFiles(String dir, String filter){
    Collection&lt;fileInfo&gt; files = new ArrayList&lt;fileInfo&gt;();
    try{
        if(this.getChannelSftp() == null || !this.getChannelSftp().isConnected())     //make sure that the JSch sessions been opened.
            this.openSFTPConnection();
        this.getChannelSftp().cd(dir); //set the working directory
        Vector&lt;ChannelSftp.LsEntry&gt; fileList = this.getChannelSftp().ls(filter); //Get a listing of the files in the directory depending on a filter
        Iterator&lt;ChannelSftp.LsEntry&gt; iterator = fileList.iterator(); //iterate over the collection
        while(iterator.hasNext()) {
            ChannelSftp.LsEntry entry = iterator.next();
            fileInfo thisFile = new fileInfo(entry.getFilename(), entry.getAttrs().getAtimeString(), FilenameUtils.getExtension(entry.getFilename()), this.getChannelSftp().get(entry.getFilename())); //get a buffered input stream for each file.
            files.add(thisFile);
        }
    }catch(SftpException e){
        e.printStackTrace();
    }
    return files;
}

public InputStream readFile(String filePath){ //built to read get a file stream from a given file path
    InputStream inputStream = null;
    try{
        if(this.getChannelSftp() == null || !this.getChannelSftp().isConnected()) //if the channel isn't open, open it.
            this.openSFTPConnection(); //open connection
        inputStream = this.getChannelSftp().get(filePath); //get the stream

    }catch(SftpException ex){
        ex.printStackTrace();
    }
    return inputStream;
}

public String uploadFile(MultipartFile file, String dest){
    try{
        System.out.println(this.getSession().getConfig(""FileUploadBaseSizeLimit""));
        if(this.getChannelSftp() == null || !this.getChannelSftp().isConnected()) //if not connected open the connection
            this.openSFTPConnection();
        this.getChannelSftp().cd(dest); //set working dir
        this.getChannelSftp().put(file.getInputStream(), dest + '/' + file.getOriginalFilename()); //get the input stream from the multipart file and put it in the destination
    }catch(IOException IO){
        IO.printStackTrace();
    }catch(SftpException sftp){
        sftp.printStackTrace();
    }
    return file.getOriginalFilename() + "" has been uploaded"";
}

public String downloadFile(String orig, String dest){
    try{
        if(this.getChannelSftp() == null || !this.getChannelSftp().isConnected()) //if not connected
            this.openSFTPConnection();
        File download = new File(dest + '/' + FilenameUtils.getName(orig)); //create a new local file
        OutputStream outputStream = new FileOutputStream(download);  //generate an output stream to the file
        byte[] buffer = new byte[10000000]; //10MB buffer instance
        BufferedInputStream bufferedInputStream = new BufferedInputStream(this.getChannelSftp().get(orig)); //create a buffered input stream off the input stream from the ssh get
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); // and a buffered output stream off the output stream we created
        int readCount; //integer link to the buffer
        while((readCount = bufferedInputStream.read(buffer)) &gt; 0){ //read the buffered input stream into the buffer.  while it's not empty...
            bufferedOutputStream.write(buffer, 0, readCount); //write the buffer to the output stream
        }
        bufferedInputStream.close(); //close the streams
        bufferedOutputStream.close();
        outputStream.close();

    }catch(IOException IO){
        IO.printStackTrace();
    }catch(SftpException sftp){
        sftp.printStackTrace();
    }
    return ""File "" + FilenameUtils.getName(orig)  + "" has been downloaded.""; //return that we've successfully uploaded the file
}

public void writeFile(String dir, String fileName, InputStream fileIS) { //writes a file given the destination directory, fileName, and an input stream
    try{
        if(this.getChannelSftp() == null || !this.getChannelSftp().isConnected() ) //if the connection isn't already open, open it
            this.openSFTPConnection();
        this.getChannelSftp().cd(dir); //set the working dir for better shorthand
        this.getChannelSftp().put(fileIS, fileName); //put the file.
        fileIS.close(); //close the file stream

    }catch(SftpException e){
        e.printStackTrace();
    }catch(IOException IO){
        IO.printStackTrace();
    }

}

public void moveFile(String path, String dest){
    try{
        if(this.getChannelSftp() == null || !this.getChannelSftp().isConnected()){ //open connection if not done already
            this.openSFTPConnection();
        }
        this.getChannelSftp().rename(path, dest + '/' + FilenameUtils.getName(path)); //ssh command to move the file.
    }catch(SftpException e){
        e.printStackTrace();
    }
}

public String moveFiles(String dir, String filter, String dest){
    try{
        if(this.getChannelSftp() == null || !this.getChannelSftp().isConnected()){ //open if not done already
            this.openSFTPConnection();
        }
        Collection&lt;fileInfo&gt; files = this.listFiles(dir, filter); //invoke the listFiles method and convert to an array
        Iterator&lt;fileInfo&gt; iterator = files.iterator(); //iterator
        while( iterator.hasNext()){ //while there is another value in the collection
            fileInfo thisFile = iterator.next(); // have to store the fileInfo somewhere.  can't just keep calling next.
            this.getChannelSftp().rename(dir + '/' + thisFile.getName(), dest + '/' + thisFile.getName());
        }
        this.closeSFTPConnection(); //close the connection
    }catch(Exception ex){
        ex.printStackTrace();
    }
    return ""all files moved"";
}
}
</code></pre>

<p>Test Class:</p>

<pre><code>package RestAPI;

import JSch.SFTP.SftpConnector;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
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.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.io.FileInputStream;
import java.io.InputStream;


@RunWith(SpringRunner.class)
@WebMvcTest(value = SftpRestController.class, secure = false)
public class SftpRestUnitTest {

@Autowired
private MockMvc mockMvc;

@MockBean
SftpConnector connector ;

@Test
public void testFileUpload() throws Exception{
    MockMultipartFile testFile1 = new MockMultipartFile(""data"", ""WSUID1.csv"", ""application/csv"", ""some xml"".getBytes());
    Mockito.when(
            connector.uploadFile(Mockito.any(),Mockito.anyString())
    ).thenReturn(""WSUID1.csv has been uploaded"");
    MvcResult result = mockMvc.perform(MockMvcRequestBuilders.multipart(""/Upload"").file(testFile1).param(""dest"", ""/tmp/test"")).andReturn();
    System.out.println(result.getResponse().getContentAsString());
    assert result.getResponse().getContentAsString().equals(""WSUID1.csv has been uploaded to remote directory \n"");
}
@Test
public void testDownload() throws Exception{
    String expected = ""TestFile.csv has been downloaded to the specified local directory"";
    Mockito.when(
            connector.downloadFile(Mockito.anyString(), Mockito.anyString())
    ).thenReturn(""File TestFile.csv has been downloaded."");
    RequestBuilder request = MockMvcRequestBuilders.get(""/Download"").param(""fileName"",""/tmp/TestFile.csv"").param(""dest"", ""/tmp"");
    MvcResult result = mockMvc.perform(request).andReturn();
    System.out.println(result.getResponse().getContentAsString());
    assert result.getResponse().getContentAsString().equals(expected);
}
@Test
public void testMoveFiles() throws Exception{
    Mockito.when(
            connector.moveFiles(Mockito.anyString(),Mockito.anyString(),Mockito.anyString())
    ).thenReturn(""all files moved"");
    RequestBuilder request = MockMvcRequestBuilders.put(""/moveFiles"").param(""dir"",""/IB_Test"").param(""fileType"", ""*.csv"").param(""dest"", ""/InternatlPgms/INTO/Archive/Receipt"");
    MvcResult result = mockMvc.perform(request).andReturn();
    System.out.println(result.getResponse().getContentAsString());
    assert result.getResponse().getStatus() == 200;
}
@Test
public void testReadFile() throws Exception{
    String expected = ""greetings from java test"";
    InputStream mockStream = Mockito.mock(FileInputStream.class);
    Mockito.when(
            connector.readFile(Mockito.anyString())
    ).thenReturn(mockStream);
    RequestBuilder request = MockMvcRequestBuilders.get(""/readFile"").param(""path"", ""IB_Test"");
    MvcResult result = mockMvc.perform(request).andReturn();
    System.out.println(result.getResponse().getContentAsString());
    assert result.equals(expected);
}
}
</code></pre>

<p>Error Logs:</p>

<pre><code>The specified file is a directory.
at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2873)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:1337)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:1290)
at JSch.SFTP.SftpConnector.readFile(SftpConnector.java:133)
at RestAPI.SftpRestController.readFile(SftpRestController.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
</code></pre>

<p>Any help is greatly appreciated.</p>
",https://stackoverflow.com/questions/54138964/spring-boot-unit-testing,"['java', 'spring', 'unit-testing', 'spring-boot']",1360,False,0,1
Dart/Flutter Web unit testing errors: Error: Not found: &#39;dart:html&#39;,"<p>I'm working on a Flutter web app and I'm having trouble running a test.</p>

<pre><code>Flutter 1.7.8+hotfix.4 • channel stable • git@github.com:flutter/flutter.git
Framework • revision 20e59316b8 (9 weeks ago) • 2019-07-18 20:04:33 -0700
Engine • revision fee001c93f
Tools • Dart 2.4.0
</code></pre>

<p>This is the pubspec.yaml:</p>

<pre><code>name: web_flutter
description: An app built using Flutter for web

environment:
  # You must be using Flutter &gt;=1.5.0 or Dart &gt;=2.3.0
  sdk: '&gt;=2.3.0-dev.0.1 &lt;3.0.0'

dependencies:
  flutter_web: any
  flutter_web_ui: any
  provider: any
  rxdart: ^0.22.0
  http: ^0.12.0+2
  json_annotation: ^2.4.0
  intl: 0.15.8


dev_dependencies:
  build_runner: ^1.4.0
  build_web_compilers: ^2.0.0
  pedantic: ^1.0.0
  json_serializable: ^3.0.0
  test: any

flutter:
  uses-material-design: true

dependency_overrides:
  flutter_web:
    git:
      url: https://github.com/flutter/flutter_web
      path: packages/flutter_web
  flutter_web_ui:
    git:
      url: https://github.com/flutter/flutter_web
      path: packages/flutter_web_ui
  provider:
    git:
      url: https://github.com/kevmoo/provider
      ref: flutter_web

</code></pre>

<p>I wrote a couple of tests that are passing when I run <code>pub run test</code> in either the IDE's terminal  (VS Code) or in terminal app.</p>

<p>The test I'm having trouble with requires some package imports from the project. With this test in place I get errors and the other two tests don't run. I haven't found anything that points to a solution.</p>

<p>This is the error message:</p>

<pre><code>pub run test                                                                                         MyMac@MyMac
00:06 +0 -1: loading test/service_test.dart [E]                                                                                                                          
  Failed to load ""test/service_test.dart"":
  Unable to spawn isolate: file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/ui.dart:12:8: Error: Not found: 'dart:html'
  import 'dart:html' as html;
         ^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine.dart:11:8: Error: Not found: 'dart:html'
  import 'dart:html' as html;
         ^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web/lib/src/services/asset_bundle.dart:7:8: Error: Not found: 'dart:html'
  import 'dart:html' show HttpRequest;
         ^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine.dart:12:8: Error: Not found: 'dart:js'
  import 'dart:js' as js;
         ^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine.dart:13:8: Error: Not found: 'dart:js_util'
  import 'dart:js_util' as js_util;
         ^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/ui/compositing.dart:20:9: Error: Type 'html.Element' not found.
    final html.Element webOnlyRootElement;
          ^^^^^^^^^^^^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine.dart:177:37: Error: Type 'html.NodeTreeSanitizer' not found.
  class _NullTreeSanitizer implements html.NodeTreeSanitizer {
                                      ^^^^^^^^^^^^^^^^^^^^^^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine.dart:179:21: Error: Type 'html.Node' not found.
    void sanitizeTree(html.Node node) {}
                      ^^^^^^^^^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine/bitmap_canvas.dart:26:9: Error: Type 'html.Element' not found.
    final html.Element rootElement = html.Element.tag('flt-canvas');
          ^^^^^^^^^^^^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine/bitmap_canvas.dart:28:3: Error: Type 'html.CanvasElement' not found.
    html.CanvasElement _canvas;
    ^^^^^^^^^^^^^^^^^^
00:06 +0 -1: Some tests failed.
</code></pre>

<p>If I comment out this new test, the errors persist. If I comment out the test and the related imports the remaining two tests run and pass.</p>

<p>This is the test file (I left the offending code commented out so it's easier for you to see - I hope).</p>

<pre><code>import 'package:test/test.dart';
import 'package:http/http.dart';
import 'package:http/testing.dart';
import 'dart:convert';
import 'package:web_flutter/services/service.dart';
// These are the package imports that cause errors:
import 'package:web_flutter/model/model.dart';
import 'package:web_flutter/data/tenant_view_model.dart';

void main(){

  test(""getSubmission returns ResponseData{}"", () async {
    // Arrange: setup the test
    final _service = Service();

    _service.httpClient = MockClient((request) async {
      final responseData = {
        ""id"": ""some_id"",
        ""state"": ""processed"",
        ""test"": true,
        ""editable"": false,
        ""expires_at"": ""2019-09-19T03:40:22Z"",
        ""processed_at"": ""2019-09-12T03:40:22Z"",
        ""batch_id"": """",
        ""download_url"": ""downloadURl.com"",
        ""permanent_download_url"": ""permanentdownloadURL.com""
      };
      return Response(json.encode(responseData),200);
    });

    // Act
    final response = await _service.getSubmission(""submissionID"");

    // Assert
    expect(response.download_url, ""downloadURL.com"");
  });
  test(""generateForm returns SubmissionResponse{}"", () async {
    // Arrange: setup the test
    final _service = Service();

    _service.httpClient = MockClient((request) async {
      final submissionResponse = {
        ""status"": ""success"",
        ""submission"": {
          ""id"": ""some_id"",
          ""state"": ""pending"",
          ""test"": false,
          ""editable"": false,
          ""expired"": false,
          ""expires_at"": null,
          ""metadata"": {
            ""foo"": 123,
            ""bar"": ""baz""
          },
          ""processed_at"": null,
          ""batch_id"": null,
          ""data_requests"": [],
          ""download_url"": null,
          ""permanent_download_url"": null
        }
      };
      return Response(json.encode(submissionResponse),200);
    });

    // Act
    final response = await _service.generateForm(42, ""templateID"");

    // Assert
    expect(response.submission.id, ""some_id"");
  });

  test('Tenant View Model generateForm returns tenantVM.submission.submission.id', () async {
    // Arrange
    final _service = Service();
    Tenant tenant;
    tenant.id = 42;

    _service.httpClient = MockClient((request) async {
      final submissionResponse = {
        ""status"": ""success"",
        ""submission"": {
          ""id"": ""some_id"",
          ""state"": ""pending"",
          ""test"": false,
          ""editable"": false,
          ""expired"": false,
          ""expires_at"": null,
          ""metadata"": {
            ""foo"": 123,
            ""bar"": ""baz""
          },
          ""processed_at"": null,
          ""batch_id"": null,
          ""data_requests"": [],
          ""download_url"": null,
          ""permanent_download_url"": null
        }
      };
      return Response(json.encode(submissionResponse),200);
    });
    TenantViewModel tenantVM = TenantViewModel(tenant, _service);

    // Act
    await tenantVM.generateForm(""templateID"");

    // Assert
    expect(tenantVM.submission.submission.id, ""some_id"");
  });
}

</code></pre>

<p>This is the class that has the method I'm trying to test (<code>generateForm()</code>).</p>

<pre><code>import 'package:flutter_web/cupertino.dart';
import 'package:web_flutter/model/model.dart';
import 'package:web_flutter/services/service.dart';

class TenantViewModel with ChangeNotifier {
  Tenant _tenant;
  Property _property;
  Service _service;
  SubmissionResponse _submission;
  ResponseData _responseData;

  TenantViewModel(this._tenant, this._service);

  bool get isNew =&gt; _tenant.id == null;

  set tenant(Tenant tenant) {
    if (_tenant != tenant) {
      _tenant = tenant;
      notifyListeners();
    }
  }

  Tenant get tenant =&gt; _tenant;

  set property(Property property) {
    _tenant.propertyId = property.id;
    notifyListeners();
  }

  Property get property =&gt; _property;

  set submission(SubmissionResponse submission) {
    if (_submission != submission) {
      _submission = submission;
      notifyListeners();
    }
  }

  SubmissionResponse get submission =&gt; _submission;

  set responseData(ResponseData responseData) {
    if (_responseData != responseData) {
      _responseData = responseData;
      notifyListeners();
    }
  }

  ResponseData get responseData =&gt; _responseData;

  Future generateForm(String templateID) async {
    SubmissionResponse submission;

    submission = await _service.generateForm(_tenant.id, templateID);
    this.submission = submission;

    notifyListeners();
  }

  Future getSubmission(String submissionID) async {
    ResponseData responseData;

    responseData = await _service.getSubmission(submissionID);
    this.responseData = responseData;

    notifyListeners();
  }

  Future save() async {
    Tenant updatedTenant;
    if (tenant.isNew) {
      updatedTenant = await _service.createTenant(_tenant);
      this.tenant = updatedTenant;
    } else {
      updatedTenant = await _service.updateTenant(tenant);
      this.tenant = updatedTenant;
    }
    notifyListeners();
  }

  Future refresh() async {
    if (isNew) {
      return;
    }
    var updatedTenant = await _service.getTenant(_tenant.id);
    if (_tenant.propertyId != null) {
      _property = await _service.getProperty(_tenant.propertyId);
    }
    _tenant = updatedTenant;
    notifyListeners();
  }
}
</code></pre>

<p>I have tried:
<code>import 'package:flutter_test/flutter_test.dart';</code> in the test file and adding this to the pubspec.yaml:</p>

<pre><code>  flutter_test:
    sdk: flutter
</code></pre>

<p>These cause their own varieties of errors, because I'm using Flutter Web, not Flutter. Can anyone see where I'm going wrong?</p>

<p>I am aware that the test I'm working on is probably wrong as it is, but I can't even get to the point of having it run and fail.</p>
",https://stackoverflow.com/questions/57982493/dart-flutter-web-unit-testing-errors-error-not-found-darthtml,"['flutter', 'unit-testing', 'dart', 'flutter-web', 'flutter-test']",81926,True,45,10
jdbcTemplate Mockito unit testing,"<p>I'm trying to perform unit testing and write a test for <code>jdbctemplate.query</code>. I need the code coverage for the below method.</p>
<h3>Code:</h3>
<pre><code>   ` public List&lt;User&gt; UserInfo(final Long runId){
    jdbcTemplate.setFetchSize(10);
    List&lt;User&gt; userList = jdbcTemplate.query(con -&gt; con.prepareStatement(GET_USER_INFO)
            , (rs, rowNum) -&gt; {
                String userName = rs.getString(&quot;username&quot;);
                String shoppingItems = rs.getString(&quot;shopingItems&quot;);
                Long shoppingid = rs.getLong(&quot;shoppingid&quot;);
                User user= new User();
                user.setCmts(userName);
                user.setNodeid(shoppingItems);
                user.setNodename(shoppingid);
                user.setRunId(runId);
                return user;
            });
    return userList;

}`
</code></pre>
<p>I have written the test as below, but running the test &quot;coverage as junit&quot; doesn't show me any code coverage for method which is inside the <code>(rs, rowNum) -&gt; {</code></p>
<h3>Test:</h3>
<pre><code>`@InjectMocks
private OracleRepository oracleRepository;

@Mock
private JdbcTemplate jdbcTemplate;

@Mock
private ResultSet rs;

@Mock
private Connection connection;

@Mock
private PreparedStatement stmt;

@Mock
private RowMapper rowMapper;

@Test
public void UserInfoTest() throws SQLException {
    String username= &quot;joe&quot;;
    String shoppingItems= &quot;3&quot;;
    long shoppingId = 1123456778;
    long runId = 2;
    List&lt;User&gt; listUser = new ArrayList&lt;User&gt;();
    Mockito.when(rs.getString(&quot;cmts&quot;)).thenReturn(cmts);
    Mockito.when(rs.getString(&quot;node&quot;)).thenReturn(node);
    Mockito.when(rs.getLong(&quot;nodeid&quot;)).thenReturn(nodeid);
     User user= new User();
     user.setUserName(username);
     user.setShoppingItems(shoppingItems);
     user.setShoppingId(shoppingId);
     user.setRunId(runId);
     listUser.add(user);
    Mockito.when(connection.prepareStatement(Mockito.any(String.class))).thenReturn(stmt);
    Mockito.when(rowMapper.mapRow(Mockito.any(ResultSet.class), Mockito.any(Integer.class))).thenReturn(user);
    Mockito.when(jdbcTemplate.query(Mockito.anyString(), Mockito.any(RowMapper.class))).thenReturn(listUser);
    List&lt;User&gt; list = oracleRepository.UserInfo(runId);
}`
</code></pre>
<p>How do I solve this problem?</p>
",https://stackoverflow.com/questions/55787901/jdbctemplate-mockito-unit-testing,"['java', 'unit-testing', 'mockito']",1104,False,-1,1
Unit Testing a Timer?,"<p>I want to test that a signal is getting fired every 6 seconds. My code looks like this:</p>

<pre><code>class DataStore {

    var clinics: Int { return clinicsSignal.lastDataFired ?? 0 }    
    let clinicsSignal = Signal&lt;Int&gt;(retainLastData: true)
    var timer: Timer?

    init() {
    }

    func load() {

        self.clinicsSignal.fire(0)

        DispatchQueue.main.async { [weak self] in
            self!.timer?.invalidate()
            self!.timer = Timer.scheduledTimer(withTimeInterval: 6.0, repeats: true) { [weak self] _ in
                self?.clinicsSignal.fire(9)
            }
        }
    }
}
</code></pre>

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

<pre><code>func testRefresh() {

    var dataStore: DataStore = DataStore()

    dataStore.clinicsSignal.subscribeOnce(with: self) {
        print(""clinics signal = \($0)"")
        dataStore.clinicsSignal.fire(0)
    }

    dataStore.load()

    sleep(30)

    print(""clinics3 = \(dataStore.clinics)"")

}
</code></pre>

<p>When I sleep for 30 seconds, the timer code doesn't get ran again until after the 30 seconds, therefore it's not getting ran once every 6 seconds like it's supposed to. Any idea on how to test that code in a timer is gettin hit at specific times? Thanks.</p>
",https://stackoverflow.com/questions/55870601/unit-testing-a-timer,"['swift', 'asynchronous', 'time', 'timer']",1111,True,0,1
unit testing custom directive,"<p><strong>I'm using material angular and I have a form with mat-checkbox.</strong></p>

<p>Above the checkbox there are terms of use and user must scroll the terms of use to bottom for enable the mat-checkbox which is disabled by default.</p>

<p>The problem is that using [disabled] directive send a message (it's not good to use directive must use in ts blablabla).</p>

<p>My solution is to create dedicated directive:</p>

<pre><code>export class MyDisabledDirective {
 @Input() set myDisabled(condition: boolean) {
    const input = this.ngControl.control;
    condition ? input.disable() : input.enable();
  }

  constructor( private ngControl: NgControl ) {
  }
}
</code></pre>

<p>Ok very simple, it works.</p>

<p>Now I need to do unit test for this directive but it's like impossible, anything I try doesn't work.</p>

<p>Right now the specs look like:</p>

<pre><code>@Component({
  selector: fake-component',
  template: `
    &lt;button [myDisabled]=""condition""&gt;Testing&lt;/button&gt;
  `,
})
class FakeComponent {
  condition = true;
}

describe('DisabledDirective', () =&gt; {
  let component: FakeComponent;
  let fixture: ComponentFixture&lt;FakeComponent&gt;;
  let button: DebugElement;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [FakeComponent, MyDisabledDirective],
      providers: [NgControl],
    });
    fixture = TestBed.createComponent(FakeComponent);
    component = fixture.componentInstance;
    button = fixture.debugElement.query(By.css('button'));
  });

  it('should disable if the condition is true', () =&gt; {
    component.condition = true;
    expect(button.nativeElement.disabled).toBeTruthy();
  });

  it('should enable if the condition is false', () =&gt; {
    component.condition = true;
    expect(button.nativeElement.disabled).toBeFalsy();
  });
});
</code></pre>

<p>It doesn't work and <em>button.nativeElement.disabled</em> is false every time.
And I wonder if the way I'm trying to make the tests is good.</p>

<p><strong>Hope You can help me, Regards</strong></p>

<p>console.log:
<a href=""https://i.stack.imgur.com/eUC0E.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/eUC0E.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/55346218/unit-testing-custom-directive,"['angular', 'unit-testing', 'karma-jasmine']",686,False,0,0
Unit Testing AppContext Switches,"<p><strong>Change Log</strong></p>

<ul>
<li>Renamed question: <strike>AppContext Switch Failing In Unit Test (CryptographicException: Invalid Algorithm Specified)</strike></li>
<li>Added section at bottom explaining the issue in further detail after doing more investigating</li>
<li>Added section at the bottom explaining a workaround I have implemented</li>
</ul>

<p>I have a piece of code that I am writing unit tests for that signs some xml.</p>

<p>I noticed when developing the code that .NET 4.7.1+ will throw <code>CryptographicException: Invalid algorithm specified</code>. To get around this issue I used the following <code>AppContext</code> switches (sources: <a href=""https://www.wiktorzychla.com/2018/07/net-471-and-higher-no-longer-supports.html"" rel=""nofollow noreferrer"">wiktor zychla</a>, <a href=""https://stackoverflow.com/a/56682656/8828057"">why am i getting invalid algorithm specified...</a>).</p>

<p>I've put the following code in any app that calls my xml signing code:</p>

<pre><code>AppContext.SetSwitch(""Switch.System.Security.Cryptography.Xml.UseInsecureHashAlgorithms"", true);
AppContext.SetSwitch(""Switch.System.Security.Cryptography.Pkcs.UseInsecureHashAlgorithms"", true);
</code></pre>

<p>When running in the wild, this code is functioning correctly, and my xml is being signed as expected.</p>

<p>I've written some unit tests for this code, it's my first real attempt at writing unit tests and I'm experiencing some weird edge cases.</p>

<pre><code>try
{
    // Compute the signature.
    signedXml.ComputeSignature();
}
catch (CryptographicException cex)
{
    //Contains instead of == since this message contains newline characters...
    if (cex.Message.Contains(""Invalid algorithm specified""))
    {
        string code = Environment.NewLine + ""AppContext.SetSwitch(\""Switch.System.Security.Cryptography.Xml.UseInsecureHashAlgorithms\"", true);"" +
                        Environment.NewLine + ""AppContext.SetSwitch(\""Switch.System.Security.Cryptography.Pkcs.UseInsecureHashAlgorithms\"", true); "";

        throw new Exception($""Cryptographic exception was thrown, ensure that the following switches are set in the executing assembly: {code}"", cex);
    }
    else
    {
        throw cex;
    }
}
</code></pre>

<p>So if the exception is thrown, I display a nice message saying please add the following code before calling this method.</p>

<p>My test class looks something like this:</p>

<pre><code>[TestFixture]    
public class XMLSigningTests
{
    protected IXMLSigner _xmlSigner;
    protected byte[] _publicKey;
    protected string _password;

    [SetUp]
    public void Init()
    {
        _xmlSigner = new XMLSigner();
        _password = ""test"";
        _publicKey = GenerateTestCert(_password);
    }

    [TearDown]
    public void CleanUp()
    {
        _xmlSigner = null;
        _publicKey = null;
        _password = null;
    }

    [Test]
    public void SignXML_AppContextSwitchNotSet_Fail()
    {
        XMLDocument xmlDoc = GenerateXML();

        Assert.Throws&lt;Exception&gt;(() =&gt; { _xmlSigner.SignXML(xmlDoc, _publicKey, _password); });
    }

    [Test]
    public void SignXML_AppContextSwitchSet_Success()
    {
        AppContext.SetSwitch(""Switch.System.Security.Cryptography.Xml.UseInsecureHashAlgorithms"", true);
        AppContext.SetSwitch(""Switch.System.Security.Cryptography.Pkcs.UseInsecureHashAlgorithms"", true);

        XMLDocument xmlDoc = GenerateXML();

        var signedXml = _xmlSigner.SignXML(xmlDoc, _publicKey, _password); 

        Assert.IsFalse(signedXML == null);
        //More validation here
    }

    private XMLDocument GenerateXML()
    {
        return new XMLDocument(""Some fancy xml here..."");
    }

    private byte[] GenerateTestCert(string password)
    {
        //Use Pluralsight.Crypto to generate a self signed cert &amp; export as .pfx
        return cert.Export(X509ContentType.Pfx, password);
    }
}
</code></pre>

<p>When I run <code>SignXML_AppContextSwitchSet_Success</code> which I'd expect to pass on its own, the test passes everytime (just me repeatedly running it). If I clean my solution and run all tests, the test always fails.</p>

<p>My xml generation class has no shared objects, it could infact be static.</p>

<p>The test fails because the cryptographic exception gets thrown (triggering my code and throwing the exception telling the dev (me) to add the app context switch).</p>

<p>Is there a way to verify that the config switches are being respected?</p>

<p>When running the code from my console tester app and in the wpf app I've built it into, the exception is never thrown. It is only thrown when I run all of the unit tests back to back. I would like these tests to run on an azure pipeline so it is important that it can run simultaneously as well as individually.</p>

<p>My thoughts on this exception are that maybe when I'm running all the tests together, the <code>AppContext</code> switches are not being honoured. I've tried to add checks before signing the xml:</p>

<pre><code>AppContext.TryGetSwitch(""Switch.System.Security.Cryptography.Xml.UseInsecureHashAlgorithms"", out bool xmlSwitch);
AppContext.TryGetSwitch(""Switch.System.Security.Cryptography.Pkcs.UseInsecureHashAlgorithms"", out bool pkcsSwitch);

if (!xmlSwitch || !pkcsSwitch)
{
    throw new NotImplementedException(""THESE VALUES SHOULD BE SET WTF"");
}
</code></pre>

<p>Now you'd expect this code to fail my fail test (where the switches aren't set) and it does, you can see my crude <code>NotImplementedException</code> message in the test explorer. However the test i'm expecting to succeed throws a <code>CryptographicException</code> again...</p>

<pre><code>System.Exception : Cryptographic exception was thrown, ensure that the following switches are set in the executing assembly: 
    AppContext.SetSwitch(""Switch.System.Security.Cryptography.Xml.UseInsecureHashAlgorithms"", true);
    AppContext.SetSwitch(""Switch.System.Security.Cryptography.Pkcs.UseInsecureHashAlgorithms"", true); 
      ----&gt; System.Security.Cryptography.CryptographicException : Invalid algorithm specified.
</code></pre>

<p>As I said earlier, I'm very new to testing and I'm not sure if my approach to test design is wrong, if I'm just testing something that's spaghetti code under the hood so maybe I'm just doomed trying to test it or theres something I'm missing to allow correct testing of this case.</p>

<p>I'm currently using <code>NUnit 3.12.0 + NUnit3TestAdapter 3.15.1</code> to write tests, although I was intially using <code>MSTest 1.3.2</code> and experienced the same behaviour using both frameworks.</p>

<hr/>

<h3>Update</h3>

<p>I've discovered that the execution order of the following tests determines the success:</p>

<ul>
<li>SignXML_AppContextSwitchNotSet_Fail</li>
<li>SignXML_AppContextSwitchSet_Success</li>
</ul>

<p>I discovered this by reading posts such as (<a href=""https://stackoverflow.com/questions/42263941/unit-test-fails-when-running-all-but-passes-when-running-individually"">Unit test fails when running all, but passes when running individually</a>) on tests failing when not running individually.</p>

<p>It got me thinking about the values being set, I want the following cases:</p>

<pre><code>//Test I expect to fail
AppContext.SetSwitch(""the switch.."", false);

//Test I expect to pass
AppContext.SetSwitch(""the switch.."", true);
</code></pre>

<p>Eventhough I have already tested for these values being set correctly, are the underlying switches being updated? How can I cleanup these underlying objects?</p>

<hr/>

<h3>Workaround / 'Nasty' Fix</h3>

<p>I found the following issue on <a href=""https://github.com/nunit/nunit/issues/2280"" rel=""nofollow noreferrer"">NUnit's GitHub (appdomain per test (isolation per test), for dealing with static classes)</a>. In this thread they discuss the option of a new <code>AppDomain</code> per test, this is exactly what I need in my case.</p>

<p>A ways down the thread <a href=""https://github.com/jnm2"" rel=""nofollow noreferrer"">jnm2</a> posts a util class to run code in a seperate <code>AppDomain</code> (<a href=""https://github.com/nunit/nunit/issues/2280#issuecomment-335474469"" rel=""nofollow noreferrer"">code</a>) (I won't post it here since this post's already massive). I took this util class and adapted my tests to work with it (you can't use any class variables or methods, meaning I had to copy my helper methods code).</p>

<p>Once I had implemented the util and adapted my tests to fit its criteria, the tests started passing both when I ran them individually &amp; all at once.</p>

<p>Mission accomplished!</p>
",https://stackoverflow.com/questions/59267036/unit-testing-appcontext-switches,"['.net', 'unit-testing', 'nunit', 'signedxml', 'cryptographicexception']",623,False,0,1
Unit testing UrlHelper extensions,"<p>I have written several extension methods for the UrlHelper in my ASP.NET Core project. Now I would like to write unit tests for them. However, many of my extension methods leverage the UrlHelper's methods (for example, Action), so I need to pass a working UrlHelper to the <code>this</code> argument (or a working UrlHelper to call the methods on). </p>

<p>How can I instantiate a working UrlHelper? I tried this:</p>

<pre><code>        Mock&lt;HttpContext&gt; mockHTTPContext = new Mock&lt;HttpContext&gt;();
        Microsoft.AspNetCore.Mvc.ActionContext actionContext = new Microsoft.AspNetCore.Mvc.ActionContext(
            new DefaultHttpContext(), 
            new RouteData(), 
            new ActionDescriptor());
        UrlHelper urlHelper = new UrlHelper(actionContext);

        Guid theGUID = Guid.NewGuid();

        Assert.AreEqual(""/Admin/Users/Edit/"" + theGUID.ToString(), UrlHelperExtensions.UserEditPage(urlHelper, theGUID));
</code></pre>

<p>It crashes (<code>Test method Test.Commons.Admin.UrlHelperTests.URLGeneration threw exception: 
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index</code>) with this call stack:</p>

<pre><code>   at System.Collections.Generic.List`1.get_Item(Int32 index)
   at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.GetVirtualPathData(String routeName, RouteValueDictionary values)
   at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.Action(UrlActionContext actionContext)
   at Microsoft.AspNetCore.Mvc.UrlHelperExtensions.Action(IUrlHelper helper, String action, String controller, Object values)
   at &lt;MY PROEJCT&gt;.UrlHelperExtensions.UserEditPage(IUrlHelper helper, Guid i_userGUID) 
   at &lt;MY TEST&gt;.URLGeneration()
</code></pre>

<p>An example of the extension methods is the following:</p>

<pre><code>    public static string UserEditPage(this IUrlHelper helper, Guid i_userGUID)
    {
        return helper.Action(
            nameof(UsersController.EditUser), 
            ""Users"", 
            new { id = i_userGUID });
    }
</code></pre>
",https://stackoverflow.com/questions/55922148/unit-testing-urlhelper-extensions,"['c#', 'asp.net-core', 'mstest']",1462,True,0,1
Unit testing MessageListener class,"<p>How do you unit test a class that implements the spring-kafka MessageListener interface? I have a listener class that I am manually listening to topics with a onMessage function. This function is very simple and just receives the messages. </p>

<p>My setup is with Spring 5.8, Spring-Kafka 2.2.7, Spring-Kafka-Test, JUnit, and <strong>WITHOUT</strong> spring boot. </p>

<p>I have been trying a bunch of different examples from the Spring reference docs and other posts but none seem to show a simple way to test the Listener class that implements MessageListener. </p>

<p>I am not sure if I need to set up an EmbeddedKafkaBroker or EmbeddedKafkaRule or is there a different way to test. When I tried using EmbeddedKafkaRule I get an error that says NoClassDefFound. </p>

<p>However I don't understand how this test case would hit my onMessage function.</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext
public class listenerTest {

    private String topic = ""someTopic"";

    @ClassRule
    public static EmbeddedKafkaRule embeddedKafka = new EmbeddedKafkaRule(1, true, topic);

    private CountDownLatch countDownLatch;

    @Before
    public void setUpTests (){
        Map&lt;String, Object&gt; sProps = KafkaTestUtils.senderProps(embeddedKafka.getEmbeddedKafka().getBrokersAsString());

        ProducerFactory producer = new DefaultKafkaProducerFactory&lt;String, String&gt; (sProps);

        kafkaTemplate = new KafkaTemplate&lt;&gt;(producer);

        kafkaTemplate.setDefaultTopic(topic);

        countDownLatch = new CountDownLatch (1);

    }

    @Test
    public void testReceiver(){
         kafkaTemplate.sendDefault(""message"");
         assertEquals(latch.getCount(), 0);
    }
</code></pre>

<p>Class I want to Unit Test</p>

<pre><code>public class listener implements BatchAcknowledgingMessageListener&lt;String, String&gt;{

    private CallbackInterface callback;

    public listener(CallbackInterface callback){
        this.callbackI = callback;
    }

    @Override
    public void onMessage(List&lt;ConsumerRecord&lt;String, String&gt;&gt; records, Acknowledgment ack){
         this.callbackI.handleMessage();
         ack.acknowledge();
    }
}
</code></pre>

<p>This throws a weird error that says this... NoClassDefFound</p>
",https://stackoverflow.com/questions/57192362/unit-testing-messagelistener-class,"['java', 'junit', 'mockito', 'spring-kafka', 'spring-kafka-test']",3759,True,0,1
Unit-Testing in Android,"<p>I've written a lot of code for an app, but I didn't use a Model-View-Presenter approach. I need to do unit tests for the app. I've been going around looking for tutorials and many people either have their methods static or they use MVP. Should I change all my code to MVP or there's a simpler way to get unit tests working without making my methods and variables static?</p>

<p>I'm planning to use Mockito and JUnit4. I'm developing on AndroidX.</p>
",https://stackoverflow.com/questions/55986393/unit-testing-in-android,"['android', 'unit-testing', 'mvp']",49,True,0,2
ember unit testing models,"<p>I am trying to write unit tests for my ember application. Currently the test that model exist works but I want to test computed properties within model which are based on some other properties generated by mirage or returned from API calls. My concern is how shall I initialize or populate data for the model under unit testing?</p>

<p>Sample unit test code for my model: ""user"" is:</p>

<pre><code>import { moduleForModel, test } from 'ember-qunit';

moduleForModel('user', 'Unit | Model | User', {
    needs: ['model:account']
});
</code></pre>

<p>Now I want to write a test where I can use:</p>

<pre><code>let model = this.subject();
</code></pre>

<p>And then I shall be able to access the properties injected by mirage. But how can I do that here? I did not find anything on documentation. Please help</p>
",https://stackoverflow.com/questions/54409443/ember-unit-testing-models,"['unit-testing', 'ember.js']",198,True,0,1
Python - Unit Testing Patch,"<p>I'm having some issues getting <code>@patch</code> to work with my unit tests, after patching an import the mock doesn't seem to be picked up and the 'regular' class is used instead</p>

<p>The class and method I'm trying to test are shown below (simplified for sake of the question) </p>

<pre><code>from sila2lib.sila_server import SiLA2Server
# ... snip ...

class DeviceService:

def __init__(self, central_message_queue: asyncio.Queue, config: Config):

    self.central_message_queue: asyncio.Queue = central_message_queue
    self.logger = logging.getLogger('GWLogger')

    # ...... snip ......

async def start_device_server(self, tag_config: dict) -&gt; asyncio.Queue:

    # Message queue used for passing messages to running device features (instrument readings)
    name = tag_config[""Name""]
    uuid = tag_config[""UUID""]
    cfg = tag_config[""FeatureConfig""]

    # SiLA Server Setup [This is what I want to mock]
    self.device_server = SiLA2Server(name=name,
                                     description=""Provides Device specific functions"",
                                     server_uuid=uuid,
                                     port=self.device_server_port,
                                     ip=self.device_server_address,
                                     simulation_mode=False,
                                     key_file=None,
                                     cert_file=None)

    # ........ snip .......
</code></pre>

<p>And an example test - all I want to do is swap out the <code>SilaServer</code> with a <code>MagicMock</code> so I can verify a method has been called with the correct params</p>

<pre><code>import asynctest, asyncio
from tests.util.MockConfig import build_mock_config
from unittest.mock import patch, MagicMock
from services.device.DeviceService import DeviceService

class DeviceServiceTests(asynctest.TestCase):

@patch(""services.device.DeviceService.SiLA2Server"")
async def test_device_info_load(self, mock_sila_server_class):

    mock_sila_server_instance = MagicMock()
    mock_sila_server_class.return_value = mock_sila_server_instance
    message_queue = asyncio.Queue()
    device_service = DeviceService(message_queue, build_mock_config())
    device_service.logger = MagicMock()

    await device_service.start_device_server(empty_tag_config)

    # Test feature has been set
    mock_sila_server_instance.add_feature.assert_called_with(data_path='',
                                                             feature_id='DeviceInfo',
                                                             servicer=None)

    # Check that server was started
    mock_sila_server_instance.run.assert_called_with(block=False)
</code></pre>

<p>And project structure </p>

<p><a href=""https://i.stack.imgur.com/rbXrZ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/rbXrZ.png"" alt=""Project Structure""></a></p>

<p>The test runs and fails as the mock isn't being used and I get an assertion exception as you'd expect, adding a breakpoint and examining the <code>device_service</code> is using the actual class</p>

<p><a href=""https://i.stack.imgur.com/2VuRY.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2VuRY.png"" alt=""Var inspect""></a></p>

<p>I feel it's something really obvious but I just can't see it, I have other similar tests that work fine with <code>@patch</code> decorators but there doesn't seem to be any difference in how its applied in those tests and this one</p>

<p>Any help is really appreciated</p>
",https://stackoverflow.com/questions/59490742/python-unit-testing-patch,"['python', 'testing', 'mocking']",145,True,0,1
JUnit - Unit Testing Dearchivers,"<p>I'd like to test the 2 methods below but I have no idea where to start. Possible scenarios I can think of:
1) Test that decompressing the input produces output that is bigger than the input.(not valid for .tar?)
2) Test edge cases such as zero length and very long input.
3) Test very large size input.</p>

<p>Could you hint for test cases or provide 1 code example?</p>

<pre><code>    /**
     * uncompresses .tar file
     * @param in
     * @param out
     * @throws IOException
     */
    public static void decompressTar(String in, File out) throws IOException {
        try (TarArchiveInputStream tin = new TarArchiveInputStream(new FileInputStream(in))){
            TarArchiveEntry entry;
            while ((entry = tin.getNextTarEntry()) != null) {
                if (entry.isDirectory()) {
                    continue;
                }
                File curfile = new File(out, entry.getName());
                File parent = curfile.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }
                IOUtils.copy(tin, new FileOutputStream(curfile));
            }
        }
    }

    /**
     * uncompresses .7z file
     * @param in
     * @param destination
     * @throws IOException
     */
    public static void decompressSevenz(String in, File destination) throws IOException {
        //@SuppressWarnings(""resource"")
        SevenZFile sevenZFile = new SevenZFile(new File(in));
        SevenZArchiveEntry entry;
        while ((entry = sevenZFile.getNextEntry()) != null){
            if (entry.isDirectory()){
                continue;
            }
            File curfile = new File(destination, entry.getName());
            File parent = curfile.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(curfile);
            byte[] content = new byte[(int) entry.getSize()];
            sevenZFile.read(content, 0, content.length);
            out.write(content);
            out.close();
        }
        sevenZFile.close();
    }
</code></pre>

<p>Here is current emptyness:</p>

<pre><code>package jfe;

import static org.junit.Assert.*;

import org.junit.Test;

/**
 * @author test
 */
public class JThreadTarTest {

    private String dir_input =""unit_test/jfe/files/input""; //input file directory
    private String dir_exp_out = ""unit_test/jfe/files/expectedOutput/""; //actual output directory
    private String dir_act_out = ""unit_test/jfe/files/actualOutput/""; //actual output directory

    @Test
    public void testdecompressTar() {
        fail(""Not yet implemented"");
    }

    @Test
    public void testdecompressSevenz() {
        fail(""Not yet implemented"");
    }
    //check if file size is too big
    //check null pointers
    //check etc.
    //assertNotNull
}
</code></pre>
",https://stackoverflow.com/questions/59324369/junit-unit-testing-dearchivers,"['java', 'unit-testing', 'junit']",38,False,0,0
Unit Testing with Pester,"<blockquote>
  <p>I understand the Theories but need a little help in practice when it comes to testing. </p>
</blockquote>

<p>So I'm still in the process of learning testing in general and after some research I can see that the code coverage is generated by how much each line of code is tested. I'm also learning c# sharp side by side and improving my scripting skills as much as possible in the process. I also understand that you usually want to mock out any dependencies when it comes to unit testing a method that relies on another method or class. In this case it's a function or cmdlet since it's powershell.(Learning these side by side shows how much more I can do in c#)</p>

<p>All I'm asking for is a little help identifying things that need to be mocked and how many tests should I write? I know that sounds subjective but I'm trying to get a general idea and best practice for myself. I keep hearing from my co-workers that TDD is the way to go and it does speed up the development/scripting process significantly by catching bugs early that you're going to run in to anyway but don't have to test manually. I'm trying to learn to do  tests first but need a little bit of guidance. I apologize if I seem like a scrub. I just need validation that I'm learning correctly.</p>

<p><strong>To make my questions clearer:</strong> </p>

<blockquote>
  <p>Am I identifying what I need to mock correctly?</p>
  
  <p>What am I missing or could identify better?</p>
  
  <p>Am I identifying what I need to test correctly?</p>
</blockquote>

<p><strong>What I'm looking for in an answer:</strong></p>

<blockquote>
  <p>Here's what you're Missing/Screwed up/Could identify better</p>
</blockquote>

<p><strong>The Code I'm Testing</strong></p>

<p><strong>Function 1</strong></p>

<pre><code>function New-ServiceSnapshot {
[CmdletBinding()]
param (
    # path to export to 
    [Parameter(Mandatory=$true)]
    [string]$ServiceExportPath
)
    $results = get-service
    $results | Export-Csv -Path $ServiceExportPath -NoTypeInformation 
}
</code></pre>

<p>On function 1 at first glance I look at it and can see 2 dependencies. I would want to mock out get-service and use dummy data to do this. I did it by an import-csv from real dummy data in to the real object that would be tested. In order to test the export I have no clue. I would maybe mock out the return for the input ExportPath parameter? Just return the string path that was input? Would that suffice? </p>

<p><strong>Function 2</strong></p>

<pre><code>function Inspect-ServiceSnapshot {
[CmdletBinding()]
param (
    #Snapshot
    [Parameter(Mandatory=$false)]
    [ValidateScript({Test-Path $_ -PathType Leaf})]
    [string]$SnapshotPath,

    # timer
    [Parameter(Mandatory=$false)]
    [int]$TimeToWait = 0,

    # If variable
    [Parameter(Mandatory=$false)]
    [object[]]
    $SnapshotVariable,

    # compare variable
    [Parameter(Mandatory=$false)]
    [object[]]
    $CompareVariable
)
if($TimeToWait) { Start-Sleep -Seconds $TimeToWait }
if($SnapshotVariable){$snap = $SnapshotVariable}
if($SnapShotPath){$snap = Import-Csv -Path $SnapshotPath}
if($CompareVariable){$Compare = $CompareVariable}else{$Compare = (Get-Service)}
if($null -eq $CompareVariable -and $null -ne $SnapshotVariable){Write-Error -Message ""If you have a SnapshotVariable, Compare variable is required"" -ErrorAction Stop}
if($null -eq $SnapshotVariable -and $null -ne $CompareVariable){Write-Error -Message ""If you have a CompareVariable, SnapshotVariable is required"" -ErrorAction Stop}

$list = @()
foreach($entry in $Compare) {
# make sure we are dealing with the SAME service
    $previousStatus = $snap | Where-Object { $_.Name -eq $entry.Name} | Select-Object -Property Status -first 1 -ExpandProperty Status
    $info = New-Object -TypeName psobject -Property @{
        Name = $entry.Name
        CurrentStatus = $entry.status
        DisplayName = $entry.displayname
        StartType = $entry.StartType
        PreviousStatus = if ($null -ne $previousStatus) { $previousStatus } else { 'Didnt Exist before, New Service' }
        isDifferent = if($previousStatus -ne $entry.status) {$true} elseif($null -eq $previousStatus) {$null} else { $false}
    }
    $list += $info
}
$list | Where-Object { $_.isDifferent -eq $true -and $_.StartType -ne ""Automatic""}
}
</code></pre>

<p>On this I think I would want to test all 4 of the inputs. I also would have to mock the dependencies and some of the inputs since they require real objects for dummy data. Other than that. No Clue.</p>
",https://stackoverflow.com/questions/54237840/unit-testing-with-pester,"['powershell', 'unit-testing', 'testing']",199,False,0,0
Unit testing the dependency injection,"<p>I am using <code>Autofac</code> for IoC</p>

<p>Here is my container initiator class, which the  responsibility is to register the dependencies.</p>

<pre><code> public class ContainerInit
 {
      public static IContainer BuildContainer()
      {
            var conFac = new ContainerFactory();
            var builder = new ContainerBuilder();
            builder.Register(conFac).As&lt;IContainerFactory&gt;().SingleInstance();
            builder.Register(c=&gt; new MainClass(conFac)).As&lt;IMainClass&gt;().SingleInstance();
            builder.Register(c=&gt; new Database(conFac)).As&lt;IDatabase&gt;().SingleInstance();
             var logger = LoggUtil.CreateLogger();
            builder.Register(logger).As&lt;ILogger&gt;().SingleInstance();

            var container = builder.Build();
            ContainerFactory.SetContainer(container);
            return container;
      }
 }
</code></pre>

<p>Problem with this approach is, I need to pass <code>IContainerFactory</code> to the constructor of every class I use in my application as follow</p>

<pre><code>  public class MainClass: IMainClass
  {       
      private readonly ILogger _logger;
      private readonly IDatabase _db;
      public MainClass(IContainerFactory containerFactory)
      {
              _logger = containerFactory.GetInstance&lt;ILogger&gt;();  
              _db =  containerFactory.GetInstance&lt;IDatabase&gt;(); //example       
      }
      public AddDetails(Data data)
      {
        //do some business operations 
        _db.Add(data);
        _logger.Information(""added"");
      }
  }
</code></pre>

<p>So it is difficult to unit test these classes.</p>

<p>How can come up with a good solution?</p>
",https://stackoverflow.com/questions/56521382/unit-testing-the-dependency-injection,"['c#', 'unit-testing', 'dependency-injection', 'inversion-of-control']",24843,True,7,3
Unit testing WinForms forms,"<p>In unit testing .net winforms, we're coming across the need to manipulate and verify the state of various form controls, as well as to fire events on those controls. The problem is that the controls are private by default on the form, and the test method can't get at them.</p>

<p>So far, we've resorted to using magic strings to get the controls via reflection. This works, but it's brittle. Tests will break if the control name changes.</p>

<p>Changing all the controls to internal works, but it's a bit of a pain in that we have to remember to do it for each and every control we might want to access in a test.</p>

<p>I thought maybe I might use expression trees to get around the ""privateness"" of the control, but nothing obvious comes to mind as to how to go about building such code.</p>

<p>There's also the problem of raising events. So far, we're magic strings to hold event names, then using reflection to locate the <em>OnXXX</em> method and invoking it, but again, we'd like to do away with that.</p>

<p>Is there a way to use expression trees (or any other semantics or mechanisms) to access private controls, in order to manipulate or verify their state and fire their events?</p>
",https://stackoverflow.com/questions/58612047/unit-testing-winforms-forms,"['c#', 'unit-testing', 'events', 'reflection', 'expression-trees']",73,False,0,0
NestJS - Mongoose @InjectConnection unit testing,"<p>I have a service that uses the <code>@InjectConnection</code> decorator in it's constructor.</p>

<p>I am unable to instantiate a testingModule for this service. The following error is thrown: <code>Nest can't resolve dependencies of the AttachmentsService (?, winston). Please make sure that the argument at index [0] is available in the TestModule context.</code></p>

<p>Service constructor:</p>

<pre><code>  constructor(@InjectConnection() private readonly mongooseConnection: Mongoose,
              @Inject(Modules.Logger) private readonly logger: Logger) {
    this.attachmentGridFsRepository = gridfs({
      collection: 'attachments',
      model: Schemas.Attachment,
      mongooseConnection: this.mongooseConnection,
    });

    this.attachmentRepository = this.attachmentGridFsRepository.model;
  }
</code></pre>

<p>Test module constructor:</p>

<pre><code>const module: TestingModule = await Test.createTestingModule({
  imports: [
    WinstonModule.forRoot({
      transports: [
        new transports.Console({
          level: 'info',
          handleExceptions: false,
          format: format.combine(format.json()),
        }),
      ],
    }),
  ],
  providers: [AttachmentsService, {
    provide: getConnectionToken(''),
    useValue: {},
  }],
}).compile();

service = module.get&lt;AttachmentsService&gt;(AttachmentsService);
</code></pre>

<p>I realize that I will have to mock the connection object to be callable by GridFS, but right now I am unable to actually get the test module to build.</p>
",https://stackoverflow.com/questions/54829935/nestjs-mongoose-injectconnection-unit-testing,"['node.js', 'typescript', 'mongoose', 'gridfs', 'nestjs']",6589,True,7,1
Mediatr: Unit Testing behaviors/validation,"<p>I have a command/handler that saves an entity to the db, but in my code, it goes through validation first (validation pipeline) using fluentvalidation.</p>

<p>I was able to create a success test to test the handler, but now I would like to make sure the command goes through validation first.</p>

<p>How would I go about doing so? should I be calling the validation independently like i do with my handler? if so how do i do that</p>

<p>here is my code</p>

<pre><code>    [Test]
    public  async Task CreateCoinCommand_Success()
    {
        var context = new Mock&lt;EventsContext&gt;();
        var ownersMock = CreateDbSetMock(new List&lt;Owner&gt;());

        context.Setup(x =&gt; x.Owners).Returns(ownersMock.Object);

        var handler = new CreateCoinCommandHandler(context.Object, mapper.Object );


        var cmd = new CreateCoinCommand(1, ""sym"", ""name"", null, null, null, 1, ""description"",
            null, ""https://google.com"", null, null, null, new []{1,2});

        var cltToken = new System.Threading.CancellationToken();
        var result = await handler.Handle(cmd, cltToken);

        Assert.IsInstanceOf&lt;Unit&gt;(result);
    }
</code></pre>

<p>My validator is called <code>CreateCoinCommandValidator</code></p>
",https://stackoverflow.com/questions/54024459/mediatr-unit-testing-behaviors-validation,"['c#', '.net-core', 'fluentvalidation', 'mediatr']",5685,True,6,1
C# async Task - Unit testing,"<p>I am new to C# unit testing and have to test if the method is working properly.</p>

<p>Here is what I have so far:</p>

<pre><code>  public async Task&lt;IHttpActionResult&gt; Post(API_FIRM_LINK aPI_FIRM_LINK)
    {
        db.API_FIRM_LINK.Add(aPI_FIRM_LINK);
        await db.SaveChangesAsync();

        return Created(aPI_FIRM_LINK);
    }
</code></pre>

<p>test method: Not really sure if I am on the right path
If someone could provide an example based on my test </p>

<pre><code>     public async Task PostTest()

    {
        ////Arrange
        API_FIRM_LINKController controller = new API_FIRM_LINKController();

        API_FIRM_LINK aPI_FIRM_LINK = null;

        IHttpActionResult expectedResult = await controller.Post(aPI_FIRM_LINK);
        //act

        IHttpActionResult result = await controller.Post(API_FIRM_LINK, aPI_FIRM_LINK);


        ////Assert
        IComparer&lt;IHttpActionResult&gt; comparer = new IHttpActionResultComparer();
       // Assert.IsTrue(comparer.Equals(expectedResult, result));

        Assert.IsNotNull(result);
        Console.Write(result);
</code></pre>
",https://stackoverflow.com/questions/55107238/c-async-task-unit-testing,"['c#', 'unit-testing', 'async-await']",13981,True,4,2
Angular unit testing - ignore stylesheets,"<p>I'm trying to speed up the unit tests for a fairly large <em>non-cli</em> Angular application and had a thought: what if I skipped the style sheets? The slowest step in running the tests (by a wide margin) is Webpack compiling the thousands of scss style sheets contained in the app.</p>

<p>I've changed the webpack settings to load empty modules for these files:</p>

<pre><code> { test: /\.css$/, use: 'null-loader' },
 { test: /\.scss$/, use: 'null-loader' },
</code></pre>

<p>But of course the Angular testbed's metadata-resolver now complains about the modules being empty..</p>

<pre><code> Error: Expected 'styles' to be an array of strings.
      at assertArrayOfStrings (webpack:///node_modules/@angular/compiler/esm5/compiler.js:2522 &lt;- config/spec-bundle.js:109446:19)
      at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (webpack:///node_modules/@angular/compiler/esm5/compiler.js:14965 &lt;- config/spec-bundle.js:121889:13)
</code></pre>

<p>I think what I need to do here is to either load every style sheet as an empty string, or set the Testbed up in such a way that it ignores references to .scss files in the component metadata.</p>

<p>Is there a way to accomplish one of these solutions, or is there perhaps a smarter way of going about this?</p>
",https://stackoverflow.com/questions/54805196/angular-unit-testing-ignore-stylesheets,"['css', 'angular', 'webpack', 'karma-runner', 'testbed']",1520,True,4,1
Flutter/Dart wait for a few seconds in unit testing,"<p>I am writing a timer app. In unit testing how do I wait for few seconds to test if my timer is working properly?</p>

<pre><code>// I want something like this.
test(""Testing timer"", () {
    int startTime = timer.seconds;
    timer.start();

    // do something to wait for 2 seconds

    expect(timer.seconds, startTime - 2);

});
</code></pre>
",https://stackoverflow.com/questions/54088397/flutter-dart-wait-for-a-few-seconds-in-unit-testing,"['unit-testing', 'dart', 'flutter', 'wait']",36654,True,41,2
Unit testing an inner function?,"<p>I have a function that has inner functions, for my unit test, I only want to test the functionality of the inner function, but when I export the function and call the inner function, <em>npm</em> tests returns an error.</p>

<p>In my <code>main.js</code>:</p>

<pre><code>mainFunction = () =&gt; {
  functionToBeTested = () =&gt; {
    // some code
  }
}

module.exports = {mainFunction: mainFunction}
</code></pre>

<p>In my <code>test.js</code></p>

<pre><code>const chai    = require(""chai"");
const assert  = require(""chai"").assert;
const mainFunction = require(""./main"");

describe (""test"", () =&gt; {
 it(""returns results"", () =&gt; {
  let result = mainfunction.functionToBeTested(args);
  //equal code
  });
})
</code></pre>

<p>But when I run <em>npm</em> test, it says: </p>

<blockquote>
  <p>mainfunction.functionToBeTested is not a function.</p>
</blockquote>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/57040638/unit-testing-an-inner-function,"['javascript', 'testing', 'mocha.js', 'chai', 'helper']",1445,True,4,3
Unit testing MongoDB.Driver dotnet core,"<p>We are using a Command/Query pattern where the implementation has detailed knowledge about how MongoDB works and we want to write a test for that. Mocking MongoDb <code>IMongoCollection&lt;CarDocument&gt;</code> while also making sure the correct <code>Find</code> filter is sent is quite challenging. We are using .NET core 2.1 and MongoDB.Driver v2.7.2</p>

<pre><code>using MongoDB.Driver;

namespace Example
{


    public class SomeMongoThing : ISomeMongoThing
    {
        public IMongoCollection&lt;CarDocument&gt; GetCars()
        {
            var client = new MongoClient(""ConnectionString"");
            var database = client.GetDatabase(""DatabaseName"");
            return database.GetCollection&lt;CarDocument&gt;(""CollectionName"");
        }
    }

    public interface ISomeMongoThing
    {
        IMongoCollection&lt;CarDocument&gt; GetCars();
    }

    public class GetCarQuery
    {
        private readonly ISomeMongoThing someMongoThing;

        public GetCarQuery(ISomeMongoThing someMongoThing)
        {
            this.someMongoThing = someMongoThing;
        }

        public CarDocument Query(string aKey)
        {
            var schedules = someMongoThing.GetCars();

            var match = schedules.Find(x =&gt; x.AKey == aKey);
            return match.Any() ? match.First() : this.GetDefaultCar(schedules);
        }

        private CarDocument GetDefaultCar(IMongoCollection&lt;CarDocument&gt; schedules)
        {
            return schedules.Find(x =&gt; x.AKey == ""Default"").First();
        }
    }
}
</code></pre>

<p>We have a test here but we are unable to write a test which checks that the correct <code>aKey</code>-filter has been used, meaning if we use the filter <code>x =&gt; x.AKey == ""hello""</code> in the implementation the test should fail. Even if the code has <code>.Find(x =&gt; true)</code> the tests pass.</p>

<pre><code>using System.Collections.Generic;
using System.Threading;
using MongoDB.Driver;
using Moq;
using NUnit.Framework;

namespace Example
{
    public class GetCarQueryTest
    {
        [Test]
        public void ShouldGetByApiKey()
        {
            var mockCarDocument = new CarDocument();
            var aKey = ""a-key"";

            var result = Mock.Of&lt;IAsyncCursor&lt;CarDocument&gt;&gt;(x =&gt;
                x.MoveNext(It.IsAny&lt;CancellationToken&gt;()) == true
                &amp;&amp; x.Current == new List&lt;CarDocument&gt;() { mockCarDocument });
            var cars = Mock.Of&lt;IMongoCollection&lt;CarDocument&gt;&gt;(x =&gt; x.FindSync(
                It.IsAny&lt;FilterDefinition&lt;CarDocument&gt;&gt;(),
                It.IsAny&lt;FindOptions&lt;CarDocument, CarDocument&gt;&gt;(),
                It.IsAny&lt;CancellationToken&gt;()) == result);

            var someMongoThing = Mock.Of&lt;ISomeMongoThing&gt;(x =&gt; x.GetCars()() == cars);
            var getCarQuery = new GetCarQuery(someMongoThing);

            var car = getCarQuery.Query(aKey);

            car.Should().Be(mockCarDocument);
        }
    }
}
</code></pre>

<p>How would you test the provided code?
If making the abstraction between <code>SomeMongoThing</code> and <code>GetCarQuery</code> helps things we are open to suggestions. The idea is that the Query has knowledge about MongoDb to be able to leverage the power of the MongoDb client, and that the user of the query does not have to care.</p>
",https://stackoverflow.com/questions/54888272/unit-testing-mongodb-driver-dotnet-core,"['.net', 'mongodb', '.net-core', 'tdd', 'moq']",3635,True,3,1
NativeScript Unit Testing keep disconnecting,"<p>Why <strong>tns test</strong> closes blank NativeScript app?</p>

<p>I have initialized a jasmine test from example in Unit Testing NativeScript Docs.</p>

<p>After I run </p>

<p><code>tns test android</code></p>

<p>First App launches and shows correct test pass screen, but after 4-5 seconds just closes and gives following error in shell.</p>

<blockquote>
  <p>DisconnectedClient disconnected from CONNECTED state (transport error)</p>
</blockquote>

<p><em>All dependencies match the latest package versions :)</em></p>

<p><strong>Things I have already tried</strong>:</p>

<ol>
<li>connecting over wi-fi and USB.</li>
<li>two different android mobiles but they closed app after showing successful test screen </li>
</ol>
",https://stackoverflow.com/questions/58428571/nativescript-unit-testing-keep-disconnecting,"['unit-testing', 'nativescript', 'karma-jasmine']",182,False,3,0
Unit testing ordered SQL queries,"<p>I am writing unit tests on queries where the results must be returned in a specific sorted order. We are using the Java H2 in memory database.</p>

<p>I want to make sure that the ""order by"" statements are being executed correctly. I'm not trying test H2, I accept it's correct, I'm trying to test that I have issued correct the SQL statement to return the correctly sorted results.</p>

<p>I'm thinking something like a way to tell H2 to randomise the results each time before sorting or perhaps some kind of SQL insertion that inserts rows in a random order to the tables each time. Hopefully this tests the ordering is correct. I know it's no guarantee because the database determines it's own internal order but thought I'd throw it in as an idea I was thinking about.</p>
",https://stackoverflow.com/questions/58463376/unit-testing-ordered-sql-queries,"['java', 'unit-testing', 'junit', 'h2']",380,True,3,2
Unit testing services in Angular,"<p>I am new to unit testing in Angular. Is there any way other than this to write unit tests for this particular function? Thank you!</p>

<p>list-user.component.ts</p>

<pre><code>constructor(private auth: AuthenticationService, private router: Router, private dialog: MatDialog) { }

fetchOfficeInfoByManager() {
          this.auth.getUserbyLM().subscribe((data: User[]) =&gt; {
          this.usersource = new MatTableDataSource(data);
}

ngOnInit() {`
this.fetchOfficeInfoByManager();
}
</code></pre>

<p>list-user.component.spec.ts</p>

<pre><code>import { ListUserComponent } from './list-user.component';
import { AuthenticationService } from '../../shared/services/authentication.service';
import { Observable } from 'rxjs';
import { from } from 'rxjs'


describe ('ListUserComponent', () =&gt; {
    let component: ListUserComponent;
    let service: AuthenticationService;

    beforeEach(() =&gt; {
        service = new AuthenticationService(null, null);
        component = new ListUserComponent(service, null, null);
    });

    it('should get employees according to line manager', () =&gt; {
        let data = [];
        spyOn(service, 'getUserbyLM').and.callFake(() =&gt; {
            return from([ data ]);
        });

        component.fetchOfficeInfoByManager();
        expect(component.data).toBeTruthy();
    });
});
</code></pre>
",https://stackoverflow.com/questions/54500080/unit-testing-services-in-angular,"['angular', 'unit-testing']",117,True,2,1
Signalr hub with Unit Testing,"<p>I am using nUnit Test and Signalr with .net framework 4.5 and I get error like :</p>

<blockquote>
  <p><em>System.Net.Http.HttpRequestException : An error occurred while sending the request.
        ----> System.Net.WebException : Unable to connect to the remote server
        ----> System.Net.Sockets.SocketException : No connection could be made because the target machine actively refused it 127.0.0.1:6790</em></p>
</blockquote>

<p>Actually I need to test when <strong>hub.GetCallControlData();</strong> being called then it should be invoked <strong>SetServer</strong>  method </p>

<p>code :</p>

<pre><code>[HubName(""SignalRHub"")]
public class SignalRHub1 : Hub
{
    public override Task OnConnected()
    {

        return base.OnConnected();
    }
    public override Task OnDisconnected(bool stopCalled)
    {
        return base.OnDisconnected(stopCalled);
    }
    public void GetCallControlData()
    {
        Clients.Caller.SetServer(""Server"");
    }
}
</code></pre>

<p>Test</p>

<pre><code>[TestFixture]
public class SignalrHubTest1
{
    public interface IClientContract
    {

        void SetServer(string s);
    }

    [Test]
    public async Task MockSingalrHub()
    {
        var url = ""http://localhost:6790"";
        var connectionId = Guid.NewGuid().ToString();
        var mockRequest = new Mock&lt;IRequest&gt;();
        var mockClients = new Mock&lt;IHubCallerConnectionContext&lt;dynamic&gt;&gt;();
        var mockProxy = new Mock&lt;IHubProxy&gt;();
        var _connection = new HubConnection(url);
        var clientContract = new Mock&lt;IClientContract&gt;();

        var mockHeaders = new Mock&lt;INameValueCollection&gt;();
        mockHeaders.Setup(h =&gt; h[""host""]).Returns(url); 

        mockRequest.Setup(r =&gt; r.Headers).Returns(mockHeaders.Object);
        clientContract.Setup(_ =&gt; _.SetServer(It.IsAny&lt;string&gt;()));


        mockClients.Setup(m =&gt; m.Caller).Returns(clientContract.Object);

        var hub = new SignalRHub1()
        {

            Clients = mockClients.Object,
            Context = new HubCallerContext(mockRequest.Object, connectionId)
        };


        var _hub = _connection.CreateHubProxy(""SignalRHub"");
        mockProxy.Setup(x =&gt; x.Subscribe(It.IsAny&lt;string&gt;())).Returns(new Subscription());
        _hub.On&lt;string&gt;(""SetServer"", x =&gt; SetServer(x));

       await hub.OnConnected();
        hub.GetCallControlData();
        clientContract.VerifyAll();
        await _connection.Start();
    }
    internal void SetServer(string s)
    {
      //  throw new NotImplementedException();
    }

}
</code></pre>
",https://stackoverflow.com/questions/59160015/signalr-hub-with-unit-testing,"['c#', 'unit-testing', 'signalr', 'nunit', 'signalr.client']",2299,True,2,1
Unit Testing angular HttpInterceptor retry,"<p>this is the first project where I'm trying to have unit test working for angular, so I'm just figuring out how this exactly works. the project is in angular 7 and I have an HttpInteceptorService to retry 2 extra times if an HTTP request fails:</p>

<pre><code>@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
    constructor() { }

    intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse&lt;any&gt; | HttpUserEvent&lt;any&gt;&gt; {
        return next.handle(request).pipe(retry(2));
    }
}
</code></pre>

<p>my tests for this interceptor so far:</p>

<pre><code>describe('HttpInterceptorService', () =&gt; {
    beforeEach(() =&gt; TestBed.configureTestingModule({
        imports: [
            HttpClientTestingModule
        ],
        providers: [
            HttpInterceptorService,
            {
                provide: HTTP_INTERCEPTORS,
                useClass: HttpInterceptorService,
                multi: true
            }
        ]
    }));

    it('should be created', () =&gt; {
        const service: HttpInterceptorService = TestBed.get(HttpInterceptorService);
        expect(service).toBeTruthy();
    });

    it('should get http 404', () =&gt; {
        const http: HttpClient = TestBed.get(HttpClient);

        http.get('/fake-route').subscribe((response: any) =&gt; {
            expect(response).toBeTruthy();
            expect(response.status).toEqual('404');
        });
    });
});
</code></pre>

<p>so I'm testing if i get a 404 successfully but I have no idea how to test if the interceptor is repeating the 2 extra times.</p>

<p><strong>Edit</strong></p>

<p>Actualy I was wrong, not even my <code>'should get http 404'</code> test is working correctly, it's just always giving a false positive.</p>

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

<p>I believe I'm getting closer, the 404 is now working properly and I've added a test for the ""retrying"" but it's still not working as expected I think the interceptor is probably not even being called...</p>

<pre><code>it('should repeat failed request 2 more times', () =&gt; {
    const emsg = 'deliberate 404 error';

    jasmine.clock().install();
    spyOn(httpClient, 'get').and.callThrough();

    expect(httpClient.get).not.toHaveBeenCalled();

    httpClient.get(fakeUrl).subscribe(
    (response) =&gt; {
      fail('should have failed with the 404 error');
    },
    (error) =&gt; {
      expect(error.status).toEqual(404, 'status');
      expect(error.error).toEqual(emsg, 'message');
    });

    jasmine.clock().tick(3000);

    expect(httpClient.get).toHaveBeenCalledTimes(3);

    jasmine.clock().uninstall();
});
</code></pre>

<p>and this test fails with ""Expected spy get to have been called 3 times. It was called 1 times""</p>
",https://stackoverflow.com/questions/54074665/unit-testing-angular-httpinterceptor-retry,"['angular', 'unit-testing']",1013,True,2,1
Sinon unit testing MySQL connection,"<p>I am trying to unit test my AWS Node Lambda. I am using MySQL. I have a utility file to get a MySQL connection pool, which is a dependency in my handler. I am trying to unit test my handler via Mocha and Sinon. I want to stub or mock the database pool and connection (without actually creating a db connection or hitting the database), but I am not having any luck. Does anyone know how to achieve this? I created the following 2 files as a test harness:</p>

<p><strong>dbConn.js</strong></p>

<pre><code>const mysql = require('mysql2/promise');

async function getPool(options = {}) {
  return await mysql.createPool(optionsClone);
}

module.exports = {
  getPool
};
</code></pre>

<p><strong>getEmployees.js</strong></p>

<pre><code>const database = require('./dbConn');

exports.handler = async function(event, context, callback) {
  // Connect to a database via connection pool
  let pool = await database.getPool(dbOptions);
  let conn = await pool.getConnection();

  const dbResult = await conn.query('select * from employees');

  conn.release();

  return dbResult;
};
</code></pre>
",https://stackoverflow.com/questions/59346368/sinon-unit-testing-mysql-connection,"['javascript', 'mysql', 'unit-testing', 'aws-lambda', 'sinon']",2951,True,2,1
Unit Testing Nestjs Mongoose services,"<p>I've been trying to figure out how to unit test services NestJS.
So I wrote a spec file which tests these NestJS services which use mongoose using jest.</p>

<p>The spec file is as follows:</p>

<pre class=""lang-js prettyprint-override""><code>import { Test, TestingModule } from '@nestjs/testing';
import { EventsService } from './events.service';
import { getModelToken } from '@nestjs/mongoose';
import { CreateEventDto } from './dto/create-event.dto';

const event = {
  _id: '53d53d2s',
  name: 'Event Name',
  description: 'Description of the event.',
  min_team_size: 0,
  max_team_size: 4,
  event_price: 300,
};

describe('EventsService', () =&gt; {
  let service: EventsService;
  const eventModel = {
    save: jest.fn().mockResolvedValue(event),
    find: jest.fn().mockResolvedValue([event]),
    findOne: jest.fn().mockResolvedValue(event),
    findOneAndUpdate: jest.fn().mockResolvedValue(event),
    deleteOne: jest.fn().mockResolvedValue(true),
  };
  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        EventsService,
        {
          provide: getModelToken('Event'),
          useValue: eventModel,
        },
      ],
    }).compile();

    service = module.get&lt;EventsService&gt;(EventsService);
  });

  it('should return all the events', () =&gt; {
    expect(service.findAll()).resolves.toEqual([event]).catch( err =&gt; {
      console.log(err);
    });
  });
  it('should create a new event and save it', () =&gt; {
    expect(service.create({
      name: event.name,
      description: event.description,
      event_price: event.event_price,
      max_team_size: event.max_team_size,
      min_team_size: event.min_team_size
    } as CreateEventDto )).resolves.toEqual(event).catch(err =&gt; {
      console.log(err);
    });
  });
  it('should return one event', () =&gt; {
    expect(service.findOne('53d53d2s')).resolves.toEqual(event).catch(err =&gt; {
      console.log(err);
    });
  });
  it('should find and update one model', () =&gt; {
    expect(service.findOneAndUpdate('53d53d2s', {} as any)).resolves.toEqual(event).catch( err =&gt; {
      console.log(err);
    });
  });
  it('should delete one model', () =&gt; {
    expect(service.deleteOne('53d53d2s')).resolves.toBeTruthy().catch( err =&gt; {
      console.log(err);
    });
  });
});
</code></pre>

<p>This is the service file:</p>

<pre class=""lang-js prettyprint-override""><code>import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { CreateEventDto } from './dto/create-event.dto';
import { EventInterface } from './interfaces/event.interface';
import { InjectModel } from '@nestjs/mongoose';

@Injectable()
export class EventsService {
  constructor(@InjectModel('Event') private readonly eventModel: Model&lt;EventInterface&gt;) {}

  async create(createEventDto: CreateEventDto): Promise&lt;EventInterface&gt; {
    const createdEvent = new this.eventModel(createEventDto);
    return createdEvent.save();
  }

  async findAll(): Promise&lt;EventInterface[]&gt; {
    return this.eventModel.find();
  }

  async findOne(id): Promise&lt;EventInterface&gt; {
    return this.eventModel.findOne({ _id: id });
  }

  async findOneAndUpdate(id, createEventDTO: CreateEventDto): Promise&lt;EventInterface&gt; {
    return this.eventModel.findOneAndUpdate({ _id: id }, createEventDTO);
  }
  async deleteOne(id): Promise&lt;any&gt; {
    return this.eventModel.deleteOne({ _id: id});
  }
}
</code></pre>

<p>Here all tests past successfully except the <code>create()</code>. It shows the following error:
<code>{ Error: expect(received).resolves.toEqual()</code></p>

<pre class=""lang-sh prettyprint-override""><code>Received promise rejected instead of resolved
Rejected to value: [TypeError: this.eventModel is not a constructor]
    at expect (/home/rakesh/SJPUC/Equinox-2019/equinox-api/node_modules/expect/build/index.js:138:15)
    at Object.it (/home/rakesh/SJPUC/Equinox-2019/equinox-api/src/events/events.service.spec.ts:44:5)
    at Object.asyncJestTest (/home/rakesh/SJPUC/Equinox-2019/equinox-api/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:102:37)
    at resolve (/home/rakesh/SJPUC/Equinox-2019/equinox-api/node_modules/jest-jasmine2/build/queueRunner.js:43:12)
    at new Promise (&lt;anonymous&gt;)
    at mapper (/home/rakesh/SJPUC/Equinox-2019/equinox-api/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
    at promise.then (/home/rakesh/SJPUC/Equinox-2019/equinox-api/node_modules/jest-jasmine2/build/queueRunner.js:73:41)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  matcherResult: undefined,
</code></pre>

<p>Also, I would like to know a better way to unit test these services.</p>
",https://stackoverflow.com/questions/57007200/unit-testing-nestjs-mongoose-services,"['unit-testing', 'mongoose', 'nestjs']",6370,True,2,1
Unit testing lit-element mixins,"<p>What are the ways to unit test a lit-element mixin? I have a simple mixin that just modifies the <code>firstUpdated</code> lifecycle event of a lit-element:</p>

<pre><code>const mixin = sup =&gt; class extends sup {
  firstUpdated() {
    super.firstUpdated();
    // do something else.
  }
}
</code></pre>

<p>So basically, the usage is:</p>

<pre><code>class MyElement extends mixin(LitElement) {
  ...
}
</code></pre>

<p>I'm not really sure how to handle the unit tests for this.</p>

<p><strong>UPDATE</strong></p>

<p>I could probably create a test element that extends the mixin, i.e. <code>MyElement</code>, and then test the element's firstUpdated function. Is that the only way to test this or are there better ways to do this?</p>
",https://stackoverflow.com/questions/55157861/unit-testing-lit-element-mixins,"['unit-testing', 'lit-element']",597,True,2,1
Mocking system_clock in unit testing,"<p>I have unit testcase suite to simulate various timings in day. Is it possible to change system time at the beginning of each testcase using chrono::system_clock?</p>
",https://stackoverflow.com/questions/54740711/mocking-system-clock-in-unit-testing,"['c++', 'c++11', 'c++-chrono']",621,False,2,0
Unit testing Kotlin&#39;s ConflatedBroadcastChannel behavior,"<p>In the new project that I'm currently working on I have no RxJava dependency at all, because until now I didn't need that - coroutines solve threading problem pretty gracefully.</p>

<p>At this point I stumbled upon on a requirement to have a <a href=""https://kotlinlang.org/docs/reference/coroutines/channels.html"" rel=""nofollow noreferrer""><code>BehaviorSubject</code></a>-alike behavior, where one can subscribe to a stream of data and receive the latest value upon subscription. As I've learned, <a href=""https://kotlinlang.org/docs/reference/coroutines/channels.html"" rel=""nofollow noreferrer""><code>Channel</code></a>s provide very similar behavior in Kotlin, so I decided to give them a try.</p>

<p>From <a href=""https://proandroiddev.com/part-3-transmitting-streams-of-value-with-channels-70cf8dccf2b"" rel=""nofollow noreferrer"">this</a> article I've learned, that <a href=""https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-conflated-broadcast-channel/"" rel=""nofollow noreferrer""><code>ConflatedBroadcastChannel</code></a> is the type of channel that mimics <code>BehaviorSubject</code>, so I declared following:</p>

<pre><code>class ChannelSender {

    val channel = ConflatedBroadcastChannel&lt;String&gt;()

    fun sendToChannel(someString: String) {
         GlobalScope.launch(Dispatchers.Main) { channel.send(someString) }
    }
}
</code></pre>

<p>For listening to the channel I do this:</p>

<pre>
<code>
    class ChannelListener(val channelSender: ChannelSender) {
        fun listenToChannel() {
            channelSender.channel.consumeEach { someString ->
                if (someString == ""A"") foo.perform() 
                else bar.perform()
            }
        }
    }
</code>
</pre>

<p>This works as expected, but at this point I'm having difficulties understanding how to unit test <code>ChannelListener</code>.</p>

<p>I've tried to find something related <a href=""https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-core/jvm/test/guide"" rel=""nofollow noreferrer"">here</a>, but none of <code>example-channel-**.kt</code> classes were helpful.</p>

<p>Any help, suggestion or correction related to my incorrect assumptions is appreciated. Thanks.</p>
",https://stackoverflow.com/questions/56848248/unit-testing-kotlins-conflatedbroadcastchannel-behavior,"['kotlin', 'listener', 'channel', 'kotlin-coroutines', 'behaviorsubject']",1586,True,2,1
Cloud Firestore Unit Testing Java,"<p>I am creating a REST API in Spring Boot and I am stuck with unit testing my service, which makes calls to my firestore database. I am trying to mock my Firestore database so I don't add unnecessary data to my firestore database as part of my tests. However, when I try to stub responses on the mocked Firestore object, I am getting a Null Pointer Exception. I am using JUnit 5 and mocking the Firestore class by</p>

<pre><code>@Mock
private Firestore db;

@InjectMocks
private ProductsService productsService;
</code></pre>

<p>In my test, I am stubbing a response from a method of the Firestore object by</p>

<pre><code>// Getting a null pointer exception here
when(db.collection(""products"").add(productToCreate).get()).thenReturn(any(DocumentReference.class));
</code></pre>
",https://stackoverflow.com/questions/58713663/cloud-firestore-unit-testing-java,"['java', 'spring-boot', 'google-cloud-firestore', 'mockito', 'junit5']",2142,True,2,2
Mock unit testing for RxJava,"<p>I'm writing unit tests base on Google's samples: <a href=""https://github.com/googlesamples/android-architecture/blob/todo-mvp-kotlin/todoapp/app/src/test/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailPresenterTest.kt#L102"" rel=""nofollow noreferrer"">TaskDetailPresenterTest.kt#L102</a></p>

<p>They use <code>ArgumentCaptor&lt;TasksDataSource.GetTaskCallback&gt;</code> to trigger callback with fake data <code>COMPLETED_TASK</code></p>

<pre><code>@Test 
fun getCompletedTaskFromRepositoryAndLoadIntoView() {
    presenter = TaskDetailPresenter(COMPLETED_TASK.id, tasksRepository, taskDetailView)
    presenter.start()

    // Then task is loaded from model, callback is captured
    verify(tasksRepository).getTask(
                eq(COMPLETED_TASK.id), capture(taskCallbackCaptor))

    // When task is finally loaded
    taskCallbackCaptor.value.onTaskLoaded(COMPLETED_TASK) // Trigger callback
}
</code></pre>

<p>Everything work fine because they use <code>TasksDataSource.GetTaskCallback</code> to return data. See: <a href=""https://github.com/googlesamples/android-architecture/blob/todo-mvp-kotlin/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailPresenter.kt#L36"" rel=""nofollow noreferrer"">TaskDetailPresenter.kt#L36</a>:</p>

<pre><code>fun getTask(taskId: String, callback: GetTaskCallback)
</code></pre>

<p>Then use as</p>

<pre><code>tasksRepository.getTask(taskId, object : TasksDataSource.GetTaskCallback {
    override fun onTaskLoaded(task: Task) {
        showTask(task)
    }
}
</code></pre>

<hr>

<p>But when I try to use <strong>RxJava Single&lt;> instead of normal callback</strong>, like:</p>

<pre><code>fun getTask(taskId: String): Single&lt;Task&gt;
</code></pre>

<p>Then use as</p>

<pre><code>tasksRepository.getTask(taskId)
    .subscribe(object : SingleObserver&lt;Task&gt; {
        override fun onSuccess(task: Task) {
            showTask(task)
        }

        override fun onError(e: Throwable) {
        }
    })
}
</code></pre>

<p>Then I <strong>cannot</strong> use <code>ArgumentCaptor&lt;&gt;</code> to trigger return fake data. It always throw <code>NullPointerException</code> when I execute my test, because  <code>tasksRepository.getTask(taskId)</code> is <strong>always</strong> return <code>null</code>.</p>

<p>So how can I achieve the same unit test like Google did, but in RxJava?</p>

<hr>

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

<pre><code>@Mock private lateinit var tasksRepository: TasksRepository

@Captor private lateinit var taskCaptor: ArgumentCaptor&lt;SingleObserver&lt;Task&gt;&gt;

private lateinit var presenter: TaskDetailPresenter

@Before fun setup() {
    MockitoAnnotations.initMocks(this)
}

@Test 
fun getCompletedTaskFromRepositoryAndLoadIntoView() {
    presenter = TaskDetailPresenter(COMPLETED_TASK.id, tasksRepository, taskDetailView)
    presenter.start()

    // Then task is loaded from model, callback is captured
    verify(tasksRepository).getTask(
                eq(COMPLETED_TASK.id)).subscribe(taskCaptor.capture())

    // When task is finally loaded
    taskCaptor.value.onSuccess(COMPLETED_TASK) // Trigger callback
}
</code></pre>

<p>Note that all other parts (declare, setup, mocking,..) is the same as Google.</p>
",https://stackoverflow.com/questions/56409465/mock-unit-testing-for-rxjava,"['android', 'unit-testing', 'mockito', 'rx-java', 'android-testing']",259,False,2,2
Unit testing redux-saga select,"<p>I have a simple saga of this form:</p>

<pre><code>const getAccountDetails = function * () {
   const { url } = yield select(state =&gt; state.appConfig)
   const accountDetails = yield call(apiFetchAccountDetails, url)
}
</code></pre>

<p>I'm trying to write a unit test:</p>

<pre><code>describe('getAccountDetails', () =&gt; {
    const iterator = getAccountDetails()
    it(""should yield an Effect 'select(state=&gt; state.appConfig)'"", () =&gt; {
       const effect = iterator.next().value
       const expected = select(state =&gt; state.appConfig)
       expect(effect).to.deep.eql(expected)
    })
</code></pre>

<p>This test fails. Although <code>effect</code> and <code>expected</code> are very similar, they are not identical.</p>

<p>At least one of the differences is buried in <code>payload.selector.scopes</code>, where the yielded effect and expected are as follows:</p>

<p><a href=""https://i.stack.imgur.com/gghmx.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gghmx.png"" alt=""screen shot""></a></p>

<p>As the scopes of these two will always be different, how can these tests ever be made to work?</p>

<p>eta: this pattern is adapted from <a href=""https://github.com/redux-saga/redux-saga/blob/master/examples/shopping-cart/test/sagas.js"" rel=""nofollow noreferrer"">the example</a> linked to from the redux-saga docs</p>
",https://stackoverflow.com/questions/56632514/unit-testing-redux-saga-select,"['mocha.js', 'generator', 'chai', 'redux-saga']",3843,True,2,1
"Unit Testing Controllers use Jest, NodeJS","<p>I want to check a case that certain routes are calling the correct controller use <strong>Jest</strong> specific <em>(mock or spy)</em>.</p>

<p>It is case specific for unit testing. Somebody can help me how to check it use jest. I don't need verify kind of 
expect (status code or res object) i need to check if <strong>controller</strong> have been called.
Thanks!</p>

<p>For instance:</p>

<pre><code>// todoController.js
function todoController (req, res) {
    res.send('Hello i am todo controller')
} 

// index.spec.js
const express = require('express');
const request = require('request-promise');
const todoController = require('./todoController');
jest.mock('./todoController');

const app = express();

app.get('/todo', todoController)

test('If certain routes are calling the correct controller , controller should to have been called times one.', async() =&gt; {
    await request({url: 'http://127.0.0.1/todo'})
    expect(todoController).toHaveBeenCalledTimes(1);
})
</code></pre>
",https://stackoverflow.com/questions/55463886/unit-testing-controllers-use-jest-nodejs,"['javascript', 'node.js', 'unit-testing', 'express', 'jestjs']",18970,True,9,1
React Js - unit testing - sanitizeEmail,"<p>Running a unit test using ReactJS jest and enzyme.I am not really sure how to test the following  correctly:</p>

<pre class=""lang-js prettyprint-override""><code>sanitizeEmail = email =&gt; {
  let result = email;
  if (result.indexOf('@') !== -1 &amp;&amp; result.substring(0, result.indexOf('@')).length &gt; 3) {
    const end = result.indexOf('@');
    let temp = '';
    for (const i in result.substring(4, end)) {
      temp = temp + '*';
    }
    result = result.substring(0, 3) + temp + result.substring(end, result.length);
  }
  return result;
};
</code></pre>

<p>I want to make sure this function gets called, the test is passing at the moment but it's not affecting its coverage
Here is my test at the moment</p>

<pre class=""lang-js prettyprint-override""><code>it('Test sanitizeEmail function', () =&gt; {
  wrapper.setProps({});
  wrapper.find('CLASSNAME').setState({
    permissionsLoaded: true,
    localPermissions: { [globals.UI_NOTIFICATION]: true }
  });
  wrapper.update();
  expect(
    wrapper
      .find('CLASSNAME')
      .instance()
      .sanitizeEmail('test')
  ).toEqual('test');
  expect(wrapper.find('CLASSNAME').state('permissionsLoaded')).toBeTruthy();
});
</code></pre>
",https://stackoverflow.com/questions/57061012/react-js-unit-testing-sanitizeemail,"['jestjs', 'enzyme']",11,False,1,0
Unit Testing Python; Imports breaking,"<p>I have a python app that I’m attempting to unit test.  The code is sat in a src directory the tests in a test directory. </p>

<p>The problem comes when trying to test the class containing my main method. This class sits in the src directory and has references to  classes in other modules that all sit in the src directory. In order to execute my app I have the references in this format <code>from &lt;module&gt; import &lt;class&gt;</code></p>

<p>When I come to test this main class I write a test class and place it in the test directory. Running the test I find I have problems with the imports in the main class. To resolve I have to change the imports to be from <code>from src.&lt;module&gt; import &lt;class&gt;</code> Having done this my tests now pass but the app itself fails.</p>

<p>How can I resolve the issue so that my imports are valid for both my unit tests and normal execution?</p>
",https://stackoverflow.com/questions/54328924/unit-testing-python-imports-breaking,"['python', 'unit-testing', 'python-import']",584,False,2,1
Android Alert Dialog unit testing,"<blockquote>
  <p>AlertFragment</p>
</blockquote>

<pre><code>public class AlertFragment extends DialogFragment {

    private static final String TAG = ""DeliveryRequestErrMsg"";

    private String mMsg;
    private String mTitle;
    private AlertDismissListener mAlertDismissListener;
    private FragmentManager mFragmentManager;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        return new AlertDialog
                .Builder(getActivity())
                .setTitle(mTitle)
                .setMessage(mMsg)
                .setNegativeButton(R.string.cart_btn_dismiss, null)
                .create();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        mAlertDismissListener.onDismiss(this);
    }

    public AlertFragment title(String title) {
        this.mTitle = title;
        return this;
    }

    public AlertFragment msg(String mMsg) {
        this.mMsg = mMsg;
        return this;
    }

    public AlertFragment fragmentMgr(FragmentManager fragmentManager) {
        mFragmentManager = fragmentManager;
        return this;
    }

    public AlertFragment onDismiss(AlertDismissListener alertDismissListener) {
        this.mAlertDismissListener = alertDismissListener;
        return this;
    }

    public void show() {
        try {
            super.show(mFragmentManager, getClass().getName());
        } catch (Exception e) {
            Log.e(TAG, ""show: "", e);
        }
    }

    interface AlertDismissListener {
        void onDismiss(AlertFragment fragment);
    }

    public String getMsg() {
        return mMsg;
    }

    public String getTitle() {
        return mTitle;
    }
}
</code></pre>

<blockquote>
  <p>AlertManagerImpl</p>
</blockquote>

<pre><code>public class AlertManagerImpl implements AlertManager {

        private List&lt;AlertFragment&gt; mListOfMessageShown = new ArrayList&lt;&gt;();

        @Override
        public boolean isMessageDisplayed(@Nonnull String message) {
            boolean isAlreadyShown = false;
            for (AlertFragment deliveryRequestErrMsgFragment : mListOfMessageShown) {
                if (message.equals(deliveryRequestErrMsgFragment.getMsg())) {
                    isAlreadyShown = true;
                    break;
                }
            }
            return isAlreadyShown;
        }

        @Override
        public void showAlertMessage(@Nullable String title, String msg, FragmentActivity activity) {
            AlertFragment deliveryRequestErrMsgFragment = new AlertFragment()
                    .title(title)
                    .msg(msg)
                    .onDismiss(fragment -&gt; mListOfMessageShown.remove(fragment))
                    .fragmentMgr(activity.getSupportFragmentManager());
            deliveryRequestErrMsgFragment.show();
            mListOfMessageShown.add(deliveryRequestErrMsgFragment);
        }

        @Override
        public void showAlertMessageWithoutDuplicates(@Nullable String title, String msg, FragmentActivity activity) {
            if (!isMessageDisplayed(msg)) {
                showAlertMessage(title, msg, activity);
            }
        }
    }
</code></pre>

<blockquote>
  <p>AlertManager</p>
</blockquote>

<pre><code>    public interface AlertManager {

    /**
     * This method allow user to show multiple same alert messages
     *
     * @param title Title that need to show
     * @param msg Message that need to show
     * @param activity
     */
    void showAlertMessage(@Nullable String title, String msg, FragmentActivity activity);

    /**
     * This method does not allow user to show multiple same alert messages
     *
     * @param title Title that need to show
     * @param msg Message that need to show
     * @param activity
     */
    void showAlertMessageWithoutDuplicates(@Nullable String title, String msg, FragmentActivity activity);

    /**
     * Verify if there is already a similar message currently displayed to the user. Returns true if a similar message is already showing, else returns false
     *
     * @param message The message that we want to compare with the currently displayed alert messages
     * @return
     */
    boolean isMessageDisplayed(@Nonnull String message);

}
</code></pre>

<blockquote>
  <p>AlertManagerImplTest</p>
</blockquote>

<pre><code>    @Config(constants = BuildConfig.class, sdk = TestConfig.SDK)
@RunWith(RobolectricTestRunner.class)
public class AlertManagerImplTest {
    @Inject
    AlertManager alertManager;
    @Inject
    Context mContext;
    MainActivity mainActivity;

    @Module(
            includes = TestAppModule.class,
            injects = AlertManagerImplTest.class,
            overrides = true
    )
    static class TestModule {
    }

    @Before
    public void setUp() {
        mContext = RuntimeEnvironment.application;
        FirebaseApp.initializeApp(mContext);
        Services.initialize(new AlertManagerImplTest.TestModule()).inject(this);
        mainActivity = Robolectric.buildActivity(MainActivity.class).create().get();
    }

    @Test
    public void checkMessageDisplayed_WhenSameMessage_ShouldReturnTrue() throws Exception {
        alertManager.showAlertMessage(""Title1"", ""Message1"", mainActivity);
        Assert.assertTrue(alertManager.isMessageDisplayed(""Message1""));
    }

    @Test
    public void checkMessageDisplayed_WhenDifferentMessage_ShouldReturnFalse() throws Exception {
        alertManager.showAlertMessage(""Title1"", ""Message1"", mainActivity);
        Assert.assertFalse(alertManager.isMessageDisplayed(""Message2""));
    }
}
</code></pre>

<blockquote>
  <p>Here I have created AlertManager to use in my project. So implementation is working properly. But now I'm facing a challenge that I need to write some Unit testing for this implementation. Especially I need to test the following scenarios </p>
</blockquote>

<ul>
<li>show one alert -> Verify if it is showing</li>
<li>try to show one alert with a ""dead"" activity -> Verify that no crash occurs</li>
<li>show 10 alerts -> Verify that all 10 are shown (to verify that we can trust the method in most of the cases)</li>
</ul>

<blockquote>
  <p>I created a test class to just test one function of AlertManagerImpl
  class. I need to actually verify alert is showing. I read some post
  and someone suggested that Robolectric is good for this but I not good
  at Unit testing if you can suggest any other solution also welcome. If someone help with this to me much appreciated.</p>
</blockquote>
",https://stackoverflow.com/questions/59171478/android-alert-dialog-unit-testing,"['android', 'unit-testing', 'robolectric']",1850,False,1,1
Scala Unit testing for ProcessAllWindowFunction,"<p>After Reading the official flink testing documentation (<a href=""https://ci.apache.org/projects/flink/flink-docs-release-1.9/dev/stream/testing.html"" rel=""nofollow noreferrer"">https://ci.apache.org/projects/flink/flink-docs-release-1.9/dev/stream/testing.html</a>)
I was able to develop tests for a ProcessFunction, using a Test Harness, something like this: </p>

<pre><code>pendingPartitionBuilder = new PendingPartitionBuilder("":::some_name"", """")

testHarness =
  new OneInputStreamOperatorTestHarness[StaticAdequacyTilePublishedData, PendingPartition](
    new ProcessOperator[StaticAdequacyTilePublishedData, PendingPartition](pendingPartitionBuilder)
  )

testHarness.open()
</code></pre>

<p>now, I’m trying to do the same for a ProcessAllWindowFunction, that looks like this: </p>

<pre><code>class MapVersionValidationDistributor(batchSize: Int) extends
  ProcessAllWindowFunction[MapVersionValidation, Seq[StaticAdequacyTilePublishedData],TimeWindow] {

lazy val state: ValueState[Long] = getRuntimeContext .getState(new ValueStateDescriptor[Long](""latestMapVersion"", classOf[Long]))
(...)
</code></pre>

<p>First I realized I can’t use TestHarness for  ProcessAllWindowFunction, because it doesn’t have a processElement method. In this case, what unit test strategy should I follow?</p>

<p>EDIT: At the moment my test code looks like this: </p>

<pre><code>val collector = mock[Collector[Seq[StaticAdequacyTilePublishedData]]]
    val mvv = new MapVersionValidationDistributor(1)
    val input3 = Iterable(new MapVersionValidation(""123"",Seq(TileValidation(1,true,Seq(1,3,4)))))

    val ctx = mock[mvv.Context]
    val streamContext =  mock[RuntimeContext]
    mvv.setRuntimeContext(streamContext)

    mvv.open(mock[Configuration])
    mvv.process(ctx,input3,collector)

</code></pre>

<p>and I'm getting this error: </p>

<pre><code> Unexpected call: &lt;mock-3&gt; RuntimeContext.getState[T](ValueStateDescriptor{name=latestMapVersion, defaultValue=null, serializer=null}) Expected: inAnyOrder { }
</code></pre>
",https://stackoverflow.com/questions/58648453/scala-unit-testing-for-processallwindowfunction,"['scala', 'apache-flink', 'flink-streaming']",610,False,1,1
unit testing async express middleware,"<p>I have the following async middleware which uses multiple try-catches to check for the response of some http calls. I wish to unit test this middleware but am encountering difficulties mocking the ""next"" callback. When i wrap it like so: </p>

<pre><code>it('should test for auth', () =&gt; {
    logon(req, res, function() {
        expect(res.locals).toBe(true)
    })
})
</code></pre>

<p>it does not seem to be actually running the function and running the <code>expect</code> after. Any ideas on how I can mock the <code>request</code>, <code>response</code> and <code>next</code> objects so I can test for the final values (res.locals)? Thanks.</p>

<pre><code>async function logon(req, res, next) {

if (!req.query.isAuth)
    req.locals.auth = false;
    next()
}

try {
    const getData = await http.get(/logon);
    if (getData.status == 200) {
        res.locals.auth = true;
    } else {
        res.locals.auth = false;
        try {
            const secondCall = http.get(/logon2);
            if (secondCall.data.bob) {
                return res.redirect(/home);
            }
        } catch(e) {console.error(3)}
    }
} catch(e) {console.error(e)}
next();
}
</code></pre>
",https://stackoverflow.com/questions/54392291/unit-testing-async-express-middleware,"['javascript', 'node.js', 'express', 'asynchronous', 'testing']",809,False,1,1
Unit Testing Umbraco 8 Composers,"<p>I'm fairly new to unit testing so go easy on me! I'm attempting to use a fairly simple Umbraco 8 project as a bit of a test bed. I'm currently stuck on trying to test a composer which registers a dependency and having a tough time figuring out how to test it.</p>

<p>The code will probably speak volumes so without further ado, here's the composer I'd like to test. As you can see, it simply registers a service coded against an interface:</p>

<pre><code>using Papermoon.Umbraco.Utils.Services;
using Papermoon.Umbraco.Utils.Services.Interfaces;
using Umbraco.Core;
using Umbraco.Core.Composing;

namespace Papermoon.Umbraco.Aldus.Core.Composers
{
    [RuntimeLevel(MinLevel = RuntimeLevel.Run)]
    public class ServicesComposer : IUserComposer
    {
        public void Compose(Composition composition)
        {
            composition.Register&lt;IPapermoonContentTypeContainerService, PapermoonContentTypeContainerService&gt;();
        }
    }
}
</code></pre>

<p>After a lot of playing around, I found some code in the Umbraco source which means I can get a test passing based on the idea of registering a type. However, that is in no way in context of the <code>ServicesComposer</code> class. Hence, that wouldn't count against my code coverage and actually testing the class, rather than the ability to register something. Here's the code anyway:</p>

<pre><code>using System;
using Moq;
using NUnit.Framework;
using Papermoon.Umbraco.Aldus.Core.Composers;
using Papermoon.Umbraco.Utils.Services;
using Papermoon.Umbraco.Utils.Services.Interfaces;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.Composing.CompositionExtensions;
using Umbraco.Core.Logging;

namespace Papermoon.Umbraco.Aldus.Core.Tests.Composers
{
    [TestFixture]
    public class ServicesComposerTests
    {
        private ServicesComposer _servicesComposer;

        [SetUp]
        public void SetUp()
        {
            _servicesComposer = new ServicesComposer();
        }

        [Test]
        public void Compose_WhenCalled_RegistersContentTypeContainerService()
        {
            Func&lt;IFactory, IFactory&gt; factoryFactory = null;

            var mockedRegister = Mock.Of&lt;IRegister&gt;();
            var mockedFactory = Mock.Of&lt;IFactory&gt;();

            // the mocked register creates the mocked factory
            Mock.Get(mockedRegister)
                .Setup(x =&gt; x.CreateFactory())
                .Returns(mockedFactory);

            // the mocked register can register a factory factory
            Mock.Get(mockedRegister)
                .Setup(x =&gt; x.Register(It.IsAny&lt;Func&lt;IFactory, IFactory&gt;&gt;(), Lifetime.Singleton))
                .Callback&lt;Func&lt;IFactory, IFactory&gt;, Lifetime&gt;((ff, lt) =&gt; factoryFactory = ff);

            // the mocked factory can invoke the factory factory
            Mock.Get(mockedFactory)
                .Setup(x =&gt; x.GetInstance(typeof(IPapermoonContentTypeContainerService)))
                .Returns(() =&gt; new Mock&lt;IPapermoonContentTypeContainerService&gt;().Object);

            var logger = new ProfilingLogger(Mock.Of&lt;ILogger&gt;(), Mock.Of&lt;IProfiler&gt;());
            var typeLoader = new TypeLoader(Mock.Of&lt;IAppPolicyCache&gt;(), """", logger);
            var composition = new Composition(mockedRegister, typeLoader, logger, Mock.Of&lt;IRuntimeState&gt;());

            var factory = composition.CreateFactory();

            var resolved = factory.GetInstance&lt;IPapermoonContentTypeContainerService&gt;();

            Assert.IsNotNull(resolved);
        }
    }
}
</code></pre>

<p>And the below code shows where I am at the moment, and is probably close to what the test should look like (if a little messy currently). I'm potentially way off the mark here so any help would go down a storm!</p>

<pre><code>using System;
using Moq;
using NUnit.Framework;
using Papermoon.Umbraco.Aldus.Core.Composers;
using Papermoon.Umbraco.Utils.Services;
using Papermoon.Umbraco.Utils.Services.Interfaces;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.Composing.CompositionExtensions;
using Umbraco.Core.Logging;

namespace Papermoon.Umbraco.Aldus.Core.Tests.Composers
{
    [TestFixture]
    public class ServicesComposerTests
    {
        private ServicesComposer _servicesComposer;

        [SetUp]
        public void SetUp()
        {
            _servicesComposer = new ServicesComposer();

            Current.Factory = new Mock&lt;IFactory&gt;().Object;
        }

        [Test]
        public void Compose_WhenCalled_RegistersContentTypeContainerService()
        {

            var mockedRegister = Mock.Of&lt;IRegister&gt;();

            var logger = new ProfilingLogger(Mock.Of&lt;ILogger&gt;(), Mock.Of&lt;IProfiler&gt;());
            var typeLoader = new TypeLoader(Mock.Of&lt;IAppPolicyCache&gt;(), """", logger);
            var composition = new Composition(mockedRegister, typeLoader, logger, Mock.Of&lt;IRuntimeState&gt;());

            _servicesComposer.Compose(composition);

            var resolved = Current.Factory.GetInstance&lt;IPapermoonContentTypeContainerService&gt;();

            Assert.IsNotNull(resolved);
        }
    }
}
</code></pre>

<p>I've also tried mocking up Composition to see if I could verify that the <code>Register</code> method has run but as this is a static method I get the following error:</p>

<pre><code>Extension methods (here: RegisterExtensions.Register) may not be used in setup / verification expressions.
</code></pre>

<p>Here's the code that gets me to that error:</p>

<pre><code>[Test]
public void Compose_WhenCalled_RegistersContentTypeContainerService()
{
    Func&lt;IFactory, IFactory&gt; factoryFactory = null;

    var mockedRegister = Mock.Of&lt;IRegister&gt;();
    var mockedFactory = Mock.Of&lt;IFactory&gt;();

    // the mocked register creates the mocked factory
    Mock.Get(mockedRegister)
        .Setup(x =&gt; x.CreateFactory())
        .Returns(mockedFactory);

    Mock.Get(mockedRegister)
        .Setup(x =&gt; x.Register(It.IsAny&lt;Func&lt;IFactory, IFactory&gt;&gt;(), Lifetime.Singleton))
        .Callback&lt;Func&lt;IFactory, IFactory&gt;, Lifetime&gt;((ff, lt) =&gt; factoryFactory = ff);

    // the mocked factory can invoke the factory factory
    Mock.Get(mockedFactory)
        .Setup(x =&gt; x.GetInstance(typeof(IFactory)))
        .Returns(() =&gt; factoryFactory?.Invoke(mockedFactory));

    var logger = new ProfilingLogger(Mock.Of&lt;ILogger&gt;(), Mock.Of&lt;IProfiler&gt;());
    var typeLoader = new TypeLoader(Mock.Of&lt;IAppPolicyCache&gt;(), """", logger);
    var composition = new Mock&lt;Composition&gt;(mockedRegister, typeLoader, logger, new Mock&lt;IRuntimeState&gt;().Object);

    composition.Verify(c =&gt; c.Register&lt;IPapermoonContentTypeContainerService, PapermoonContentTypeContainerService&gt;(It.IsAny&lt;Lifetime&gt;()));
}
</code></pre>

<p>Ultimately, I'm failing hard (and might have set my sights too high!), I'm not 100% sure on <em>what</em> to test here. My idea is that I want to test that the <code>IPapermoonContentTypeContainerService</code> is resolvable after <code>_serviceComposer.Compose</code> runs  i.e. it's not null which ensures that it's been registered to the container. Potentially this isn't possible at which point, I wondered if testing that <code>composition.Register&lt;IPapermoonContentTypeContainerService, PapermoonContentTypeContainerService&gt;();</code> was called was enough (as the actual registration part is third-party and therefore not to be tested). Or, am I barking up the wrong tree and this shouldn't actually be tested at all?</p>

<p>Thanks!</p>

<p>Ben</p>
",https://stackoverflow.com/questions/57591852/unit-testing-umbraco-8-composers,"['c#', 'unit-testing', 'dependency-injection', 'umbraco', 'umbraco8']",320,True,1,1
Unit testing a Vue plugin,"<p>I have a plugin that console.logs data.</p>

<p>logData.spec.js</p>

<pre><code>import Vue from 'vue'
import { createLocalVue } from '@vue/test-utils'
import logData from './logData'

describe('logData plugin', () =&gt; {
  const localVue = createLocalVue()
  it('adds a $logData method to the Vue prototype', () =&gt; {
    expect(Vue.prototype.$logData).toBeUndefined()
    localVue.use(logData)
    expect(typeof localVue.prototype.$logData).toBe('function')
  })
  it('console.logs data passed to it', () =&gt; {
    const data = 'data to be logged'
    const localVue = createLocalVue()
    localVue.use(logData)
    expect(localVue.prototype.$logData(data)).toBe('data to be logged')
  })
})
</code></pre>

<p>logData.js</p>

<pre><code>export function logData (dataToLog) {
  const isLoggingData = localStorage.getItem('isLoggingData')
  if (isLoggingData) {
    console.log(dataToLog)
  }
}

export default {
  install: function (Vue) {
    Vue.prototype.$logData = logData
  }
}
</code></pre>

<p>The error I get is in my unit test is Expected: 'data to be logged"", Received: undefined. Why is the second test being read as undefined?</p>
",https://stackoverflow.com/questions/57578683/unit-testing-a-vue-plugin,"['javascript', 'vue.js', 'vue-test-utils']",1648,True,1,1
Unit Testing Mock Service Impl,"<p>I have a service and serviceImpl too in a spring boot application. When I want to test it and trying to mock my service in junit test class I got <code>NullPointerException</code> error.</p>

<p><strong>here is my service impl</strong></p>

<pre><code>package com.test;

import java.util.Date;

public class MyServiceImpl implements MyService {
    @Override
    public MyObject doSomething(Date date) {
        return null;
    }
}
</code></pre>

<p><strong>and here is my test class</strong></p>

<pre><code>package com.test;

import com.netflix.discovery.shared.Application;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.assertNull;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
@TestPropertySource(locations = ""classpath:application-integrationtest.properties"")
class MyServiceImplTest {

    @Mock
    MyService myservice;

    @Test
    void doSomethingTest() {
        assertNull(myservice.doSomething(null));
    }
}
</code></pre>
",https://stackoverflow.com/questions/55115561/unit-testing-mock-service-impl,"['java', 'spring', 'unit-testing', 'spring-boot', 'mockito']",2653,True,1,1
AngularJS unit testing - Class Undefined,"<p>I'm trying to write some basic tests for some controllers I have. I pass in some services that use other services. One service that is passed in, ""catalog service"" user a service called ""metrics service"". This metrics calls a Helper that is declared at the top of the file, and it's being pulled from a package defined in my dependencies section of my Config file. The code works/builds fine but the tests says that this Helper is undefined. What am I missing here?</p>

<p>This is the test</p>

<pre><code> beforeEach(module(""photonControllersPreSession""));

  var $controller;
  var $rootScope;
  var $scope;
  var createController;

  var $window;
  var $location;
  var loggerService;
  var controller;

  beforeEach(
    angular.mock.module( function(
      _$controller_,
      _$rootScope_,
      _$window_,
      _$location_,
      _loggerService_
    ) {

      $controller = _$controller_;
      $rootScope = _$rootScope_;
      $window = _$window_;
      $location = _$location_;
      loggerService = _loggerService_;
      $scope = $rootScope.$new();

      controller = $controller(""CatalogController"", {
        $scope: $scope,
        $location: $location,
        $window: $window,
        loggerService: loggerService
      });


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

<p>This is the service (which is used by logger service) that calls the undefined Helper</p>

<pre><code>declare var HelperUtils;

export class MetricsService {

public static $inject: Array&lt;string&gt; = [""$rootScope"", ""$window"", Constants.Photon.SERVICE_LOGGER];
private ubmHelper;
private dimensions: Array&lt;any&gt; = [];
private metricList = null;
private TAG = ""MetricsService"";
private trackingScopes: any = {};
private isEditing = false;

constructor(protected $rootScope, protected  $window:Interfaces.IPhotonWindowObject, protected loggerService: LoggerService, protected hiddenBrowserDetectionService: Services.HiddenBrowserDetectionService) {
  let ubmOptions = {
    idleInterval: 3000,
    submitInterval: 5000,
    header: {},
    logLevel: HelperUtils.LogLevelEnum.INFO,
    properties: {
      test : accountID
    }
  };
</code></pre>

<p>My karma config is below </p>

<pre><code>module.exports = function(config) {
  ""use strict"";

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: ""../"",

    // testing framework to use (jasmine/mocha/qunit/...)
    // as well as any additional frameworks (requirejs/chai/sinon/...)
    frameworks: [
      ""jasmine"",
      ""karma-typescript""
    ],

    // list of files / patterns to load in the browser
    files: [
      ""vendor/jquery/dist/jquery.js"",
      ""vendor/angular/angular.js"",
      ""vendor/angular-animate/angular-animate.js"",
      ""vendor/angular-cookies/angular-cookies.js"",
      ""vendor/angular-messages/angular-messages.js"",
      ""vendor/angular-resource/angular-resource.js"",
      ""vendor/angular-route/angular-route.js"",
      ""vendor/angular-sanitize/angular-sanitize.js"",
      ""vendor/angular-touch/angular-touch.js"",
      ""vendor/angular-mocks/angular-mocks.js"",
      //""app/photon-app.js"",
      ""app/scripts/commons/providers/ui-notification.js"",
      ""app/scripts/commons/constants.ts"",
      ""app/constants-global.ts"",
      ""app/scripts/commons/interfaces/*.ts"",
      ""app/scripts/commons/factories/*.ts"",
      ""app/scripts/commons/services/*.ts"",
      ""app/**/*.ts"",
      ""test/specs/**/*.ts"",
      {
        pattern: '**/*.js.map',
        included: false
      }
    ],

    // list of files / patterns to exclude
    exclude: [
      ""photon/**/*.d.ts"",
      ""app/scripts/commons/services/message-service.ts"" //TODO: please add this servcie back after basic sannity test are passing
    ],

    //This is neede to load all *spec.ts 
    mime: {
      'text/x-typescript': ['ts']
    },


    karmaTypescriptConfig: {
      ""compilerOptions"": {
        ""moduleResolution"": ""node"",
        ""noLib"": false,
        ""removeComments"": true,
        ""target"": ""es5"",
        // or es3, es6
        ""declaration"": false
        // Not compile .d.ts files

      },
      ""exclude"": [
        ""photon/**/*.d.ts"",
        ""app/scripts/commons/services/message-service.ts"" //TODO: please add this servcie back after basic sannity test are passing
      ],
      ""include"": [
        ""app/scripts/commons/constants.ts"",
        ""app/constants-global.ts"",
        ""app/scripts/commons/interfaces/*.ts"",
        ""app/scripts/commons/factories/*.ts"",
        ""app/scripts/commons/services/*.ts"",
        ""app/**/*.ts""
        //""test/specs/**/*.ts""
      ]
    },

    // web server port
    port: 8080,

    browsers: [
      ""Chrome""
    ],

    // Which plugins to enable
    plugins: [
      ""karma-phantomjs-launcher"",
      ""karma-chrome-launcher"",
      ""karma-jasmine"",
      ""karma-coverage"",
      ""karma-junit-reporter"",
      ""karma-typescript""
    ],

    reporters: [""progress"", ""junit"", ""coverage""],

    preprocessors: {
      ""app/**/*.ts"": ['karma-typescript']
    },
    bundlerOptions: {
      transforms: [
        require(""karma-typescript-es6-transform"")()
      ]
    },

    coverageReporter: {
      reporters: [{
        type: 'cobertura',
        dir: 'coverage',
        file: 'coverage.xml'
      }, {
        type: 'html',
        dir: 'coverage'
      }, {
        type: 'text-summary'
      }]
    },

    junitReporter: {
      //outputDir: ""../build/brazil-unit-tests"", // results will be saved as $outputDir/$browserName.xml
      //outputDir: ""../build/brazil-unit-tests/test-results.xml"", // results will be saved as $outputDir/$browserName.xml
      outputFile: ""../build/brazil-unit-tests/test-results.xml"", // if included, results will be saved as $outputDir/$browserName/$outputFile
      suite: ""PhotonPortal"", // suite will become the package name attribute in xml testsuite element
      useBrowserName: false, // add browser name to report and classes names
      nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element
      classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element
      properties: {} // key value pair of properties to add to the &lt;properties&gt; section of the report
    },

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_DEBUG,


  });
</code></pre>
",https://stackoverflow.com/questions/54373047/angularjs-unit-testing-class-undefined,"['angularjs', 'typescript', 'unit-testing', 'karma-jasmine']",257,True,0,1
Mocking IScheduler for unit testing,"<p>I'm trying to test rx.net code and I'm totally confused how to go about it. An example from this <a href=""http://introtorx.com/Content/v1.0.10621.0/16_TestingRx.html"" rel=""nofollow noreferrer"">website</a> was quite helpful, but I'm unable to connect the final piece. Below is a sample code:</p>

<pre><code>class SomeClass 
{

  constructor(IScheduler scheduler)
  {
    var interval = Observable.Interval(TimeSpan.FromSeconds(1), scheduler)
      .Take(5);
  }

}

// So in my unit test project I'll inject a TestScheduler as below

public void Test_Some_Class()
{
   var scheduler = new TestScheduler();
   var instance = new SomeClass(scheduler);
   ...
}
</code></pre>

<p>My question is in my startup file, which implementation of IScheduler should I use:</p>

<pre><code>services.AddSingleton&lt;IScheduler, ConcreteImpl&gt;()
</code></pre>

<p>This stackoverflow <a href=""https://stackoverflow.com/questions/15341864/what-are-the-default-schedulers-for-each-observable-operator"">question</a> was quite helpful, but I'm still unable to piece everything together :(</p>
",https://stackoverflow.com/questions/57677537/mocking-ischeduler-for-unit-testing,"['c#', 'asp.net-core', 'dependency-injection', 'rx.net']",538,True,0,2
unit testing with method pointer,"<p>I have a function which takes two file as parameter. It is trying to check directory1, and get path of most recent sub directory, if fail get path of second directory. I want to write a unit test, but not sure how to mock the following part.</p>

<pre><code>listFiles(File::isDirectory)
</code></pre>

<p>pseudo-code of my function</p>

<pre><code>try{           
    File[] directories = d1.listFiles(File::isDirectory);
    Arrays.sort(directories, Collections.reverseOrder());       
    return  directories[0].getAbsolutePath();;
} catch (Exception e) {
    return d2.getAbsolutePath()
}
</code></pre>
",https://stackoverflow.com/questions/56744124/unit-testing-with-method-pointer,['unit-testing'],35,False,0,0
AssertionError in Unit Testing viewModel,"<p>I have following project in Bitbucket : <a href=""https://bitbucket.org/ali-rezaei/storytel/src/master/"" rel=""nofollow noreferrer"">https://bitbucket.org/ali-rezaei/storytel/src/master/</a></p>

<p>I have following unitTest :</p>

<pre><code>@RunWith(MockitoJUnitRunner::class)
class MainViewModelTest {

    @get:Rule
    var rule: TestRule = InstantTaskExecutorRule()

    @Mock
    private lateinit var api: StorytelService

    private lateinit var viewModel: MainViewModel

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

    @Test
    fun loadPosts() {
        val networkPhoto = NetworkPhoto(1, 1, ""title"", ""url"", ""thumbnailUrl"")
        `when`(api.getPhotos()).thenReturn(Observable.just(listOf(networkPhoto)))

        val networkPost = NetworkPost(1, 1, ""title"", ""body"")
        `when`(api.getPosts()).thenReturn(Observable.just(listOf(networkPost)))

        // Make the sure that all schedulers are immediate.
        val schedulerProvider = ImmediateSchedulerProvider()

        viewModel = MainViewModel(schedulerProvider, api)

        val observer = LoggingObserver&lt;List&lt;Post&gt;&gt;()
        viewModel.posts.observeForever(observer)

        with(observer) {
            assertThat(this, `is`(notNullValue()))
            assertThat(this.value?.size, `is`(1))
        }
    }

    /**
     * simple observer that logs the latest value it receives
     */
    private class LoggingObserver&lt;T&gt; : Observer&lt;T&gt; {
        var value: T? = null
        override fun onChanged(t: T?) {
            this.value = t
        }
    }
}
</code></pre>

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

<pre><code>java.lang.AssertionError: 
Expected: is &lt;1&gt;
     but: was null
Expected :is &lt;1&gt;
Actual   :null
</code></pre>

<p>And here is MainViewModel class :</p>

<pre><code>class MainViewModel(
    private val schedulerProvider: BaseSchedulerProvider,
    private val api : StorytelService
) : BaseViewModel() {

    private val _posts = MutableLiveData&lt;List&lt;Post&gt;&gt;()
    val posts: LiveData&lt;List&lt;Post&gt;&gt;
        get() = _posts

    private val _status = MutableLiveData&lt;Status&gt;()
    val status: LiveData&lt;Status&gt;
        get() = _status

    init {
        showPhotos()
    }

    fun showPhotos() {
        EspressoIdlingResource.increment() // App is busy until further notice
        _status.postValue(Status.LOADING)
        compositeDisposable.add(api.getPhotos()
            .subscribeOn(schedulerProvider.io())
            .observeOn(schedulerProvider.ui())
            .doFinally {
                if (!EspressoIdlingResource.countingIdlingResource.isIdleNow) {
                    EspressoIdlingResource.decrement() // Set app as idle.
                }
            }
            .subscribe({
                _status.postValue(Status.SUCCESS)
                showPosts(it)
            }) {
                _status.postValue(Status.ERROR)
                Timber.e(it)
            })
    }

    private fun showPosts(networkPhotos: List&lt;NetworkPhoto&gt;) {
        EspressoIdlingResource.increment() // App is busy until further notice
        _status.postValue(Status.LOADING)
        compositeDisposable.add(api.getPosts()
            .subscribeOn(schedulerProvider.io())
            .observeOn(schedulerProvider.ui())
            .doFinally {
                if (!EspressoIdlingResource.countingIdlingResource.isIdleNow) {
                    EspressoIdlingResource.decrement() // Set app as idle.
                }
            }
            .subscribe({ networkPosts -&gt;
                _status.postValue(Status.SUCCESS)
                _posts.postValue(
                    PostAndImages(networkPosts, networkPhotos).asDomaineModel()
                )
            }) {
                _status.postValue(Status.ERROR)
                Timber.e(it)
            })
    }
}
</code></pre>

<p>How to resolve it?</p>
",https://stackoverflow.com/questions/58266032/assertionerror-in-unit-testing-viewmodel,"['android', 'unit-testing']",89,True,0,1
Unit testing database using EF,"<p>How does one unit test a service which connects to a database?</p>

<p>I have a <code>playerRepository</code> class in data access layer, which interacts with the database directly, and a <code>playerService</code> class in business layer which creates an instance of <code>playerRepository</code> and services random stuff like - deleting player, saving player, getting all players, getting the player by id/name yadda yadda.</p>

<p>I want to unit test the <code>playerService</code> without using the real database, but using in-memory database provided with EF.</p>

<p>The problem is, I'm having trouble figuring out how to set it up.</p>

<p>I have a <code>PlayerContext : DbContext</code> class, which is used as a model to code-first (done this part via tutorial on EF). And I have to add a parameter to constructor <code>DbContextOptionsBuilder&lt;PlayerContext&gt;</code>, but I don't know where to begin. I don't know how and where to setup the connection string, where does the ""default"" database store itself.</p>

<p>I want to do this by using EF without NSubstitute or Moq, I'm doing this to learn how it's done without using other frameworks except for EF.</p>

<pre><code>public class PlayerContext : DbContext
{
    public PlayerContext() : base()
    {

    }

    public DbSet&lt;Player&gt; Players { get; set; }
}

public class Player
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int DciNumber { get; set; }
}
</code></pre>

<p>I'm using visual studio provided unit testing</p>

<pre><code>[TestClass]
public class PlayerServiceTest
{
    // Should get all the players from database
    [TestMethod]
    public void GetAllPlayers()
    {
        // arrange - act
        // TODO: Return all the players from the database

        // assert
        // TODO: Should return empty list
    }
</code></pre>

<p>And the PlayerService class looks something like this</p>

<pre><code>public class PlayerService
{
    private PlayerRepository _playerRepository = new PlayerRepository();


    public List&lt;Player&gt; GetAllPlayers()
    {
        var players = _playerRepository.GetAllPlayers();

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

<p>PlayerRepository</p>

<pre><code>public class PlayerRepository
{
    public List&lt;Player&gt; GetAllPlayers()
    {
        using (var context = new PlayerContext())
        {
            var players = context.Players.ToList();

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

<p>Generally my questions are:</p>

<ol>
<li><p>How to make the <code>PlayerContext</code> with another connection string which connects to in-memory database in case of unit test, and also how to provide it with the correct connection string when not running via unit-tests</p></li>
<li><p>How to change the location of the database, because it's using a default path in <code>C:\Users</code>.</p></li>
</ol>

<p>I'm not looking for integration tests with the DAL's <code>PlayerRepository</code>, I just want to test the business layer and all I need is, when I run the tests that the PlayerService to uses the PlayerRepository which connects to in-memory database and that's it. Otherwise it should connect to the local db stored in the same folder as the main exe for the app</p>

<p>Help needed!</p>
",https://stackoverflow.com/questions/54153482/unit-testing-database-using-ef,"['c#', 'database', 'winforms', 'entity-framework', 'unit-testing']",152,True,0,1
Unit testing fs-extra writeFile,"<p>I have used <code>writeFile</code> from <code>fs-extra</code> to generate my file When I tried to do unit testing using JEST I'm always getting an error like the <code>writeFile</code> method was not called even though it has been called. Can someone plz suggest me ways to get it tested properly.</p>

<p>These are the functions I'm using.
Note: No class has been used, we are consuming it as methods</p>

<pre><code>import { writeFile } from 'fs-extra';
import { resolve as pathResolve } from 'path';

export default async function generateFile(): Promise&lt;void&gt;{
   await writeSampleFile(value);
   // other stuffs
}

async function writeSampleFile(value: string): Promise&lt;void&gt; {
  try {
    await writeFile(pathResolve(path), value, 'utf8');
  } catch (err) {
  }
}
</code></pre>

<p><code>spec.ts</code>:</p>

<pre><code>import generateFile from './x';
import * as fsExtra from 'fs-extra';

const writeFileSpy = jest.spyOn(fsExtra, 'writeFile');


describe('writeFile', async () =&gt; {
  test('it should check whether writeFile has been called', async () =&gt; {
    await generateFile();
    //Since internally it was calling writeFile i was checking for writeSampleFile as well
    expect(writeFileSpy).toHaveBeenCalled();
  });
});
</code></pre>

<p>Though I have called everything I'm not getting the method as called and the test got failed but my file is getting generated using the <code>writeFile</code>.</p>
",https://stackoverflow.com/questions/58625148/unit-testing-fs-extra-writefile,"['node.js', 'angular', 'jestjs']",1375,True,0,1
react fabric dropdown unit testing,"<p>I am new to unit testing and trying to write test cases for checking the ""text"" dropdown options. 
my code:</p>

<pre><code>const options = [
     {
        key: 'Select',
        text: 'value1',
     },
&lt;Dropdown
   placeholder=""dropdown value""
   options={options[0]}
   disabled={true}
   className=""style""
   /&gt;
</code></pre>

<p>my test file is:</p>

<pre><code>let wrapper = shallow(&lt;App /&gt;)
it('selected option text', () =&gt; {

    const dropdown= shallow(&lt;Dropdown options={options[0]} /&gt;)       
        const value= dropdown.find(Dropdown);

        expect(value.children()).toEqual('value1');

</code></pre>

<p>How can I pass the options text into children? or is there any better way to do?</p>
",https://stackoverflow.com/questions/58457685/react-fabric-dropdown-unit-testing,"['unit-testing', 'jestjs', 'enzyme']",50,False,0,0
Spring Batch Unit Testing( Junit ),"<p>Are there any references available for spring batch Junit testing?,
After so much search i am unable to find any good example references .</p>
",https://stackoverflow.com/questions/56733903/spring-batch-unit-testing-junit,"['spring', 'unit-testing', 'junit', 'spring-batch']",471,False,-3,1
Unit Testing Order of Operations,"<p>Suppose we want to make steaks.</p>

<pre><code>Public class Restaurant{
    public void MakeSteak(Steak rawSteak) {
      this.KitchenServices.AddSeasoning(rawSteak);
      this.KitchenServices.Grill(rawSteak);
    }
}
</code></pre>

<p>In the unit tests, I could make sure that given a raw steak, we both season it and grill it:</p>

<pre><code>public void MakeSteakTest() {
  var rawSteak = new Steak();
  this.restaurant.MakeSteak(rawSteak);
  this.KitchenServices.Verify(x =&gt; x.AddSeasoning(rawSteak) , Times.Once);
  this.KitchenServices.Verify(x =&gt; x.Grill(rawSteak) , Times.Once);
}
</code></pre>

<p>My question is that should we have a test to make sure that the steak is not seasoned after it's grilled? If yes, How?</p>
",https://stackoverflow.com/questions/55008028/unit-testing-order-of-operations,"['c#', 'unit-testing', 'nunit']",190,True,0,3
Java Dependency Injection Unit Testing,"<p>Can somebody make an junit test on this class?</p>

<pre><code>public class MyApplication {
    private EmailService email = new EmailService();

    public boolean processMessages (String msg , String recipient ) {
        if (msg.length ==0 | | recipient.length ==0 ) {
            return false ;
        }
        return this.email.sendEmail (msg , recipient ) ;
    }
}
</code></pre>
",https://stackoverflow.com/questions/58001572/java-dependency-injection-unit-testing,"['java', 'testing', 'junit', 'dependency-injection']",8460,True,-5,3
Unit Testing with Angular 7,"<p>I am trying to write unit test for this angular script:</p>

<pre><code>export class DataService {
  private csrfToken: string = '';

  private isContentShow: BehaviorSubject&lt;boolean&gt; = new BehaviorSubject(true);

  constructor(private http: HttpClient, private cookieService: CookieService) {
    this.token = this.cookieService.get('token');
  }

  public createData(data: Data) {
    try {
       this.http.post(  url,
                        data,
                        {
                          headers: new HttpHeaders({
                              'Content-Type':  'application/json',
                              'Authorization': this.token
                          })
                        })
      .subscribe(
        data =&gt; {
                this.isContentShow.next(true);
                },
        err =&gt; {
        this.showError();
        },
        () =&gt; console.log('Request Complete')
      );
      return true;
    } catch {
      this.showError();
      }
    }

  public getIsContentShow(): Observable&lt;boolean&gt; {
    return this.isContentShow.asObservable();
  } 
}
</code></pre>

<p>The test that I had so far and its running as expected.</p>

<pre><code> it('#getIsContentShow should return value from observable',
    (done: DoneFn) =&gt; {
    service.getIsContentShow().subscribe(value =&gt; {
      expect(value).toBe(true);
      done();
    });
  });
</code></pre>

<p>However I am trying to write the test for <code>createData()</code> function</p>

<p>I am able to mock the <code>HttpClient</code> using <code>HttpClientTestingModule</code> however I don't know how to handdle the <code>CookieService</code> and token ?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/54681585/unit-testing-with-angular-7,"['javascript', 'angular', 'unit-testing', 'angular7']",130,False,0,1
Android Unit Testing with Mockito,"<p>I have a ViewModel in which there is a method which has the following line of code:</p>

<pre><code>billDate.set(!TextUtils.isEmpty(SampleApp.getInstance().getAccountManager().getDueDate()) ?
            String.format(SampleApp.getInstance().getApplicationContext().getString(R.string.due),
                    SampleApp.getInstance().getAccountManager().getBillingDueDate()) :
            SampleApp.getInstance().getApplicationContext().getString(R.string.missing_due_date));
</code></pre>

<p>I have a test class using Mockito to test the different methods in ViewModel. But it is failing with <code>NullPointerException</code> at this line:</p>

<pre><code>String.format(SampleApp.getInstance().getApplicationContext().getString(R.string.due),
</code></pre>

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

<pre><code>java.lang.NullPointerException
at java.util.regex.Matcher.getTextLength(Matcher.java:1283)
at java.util.regex.Matcher.reset(Matcher.java:309)
at java.util.regex.Matcher.&lt;init&gt;(Matcher.java:229)
at java.util.regex.Pattern.matcher(Pattern.java:1093)
at java.util.Formatter.parse(Formatter.java:2547)
at java.util.Formatter.format(Formatter.java:2501)
at java.util.Formatter.format(Formatter.java:2455)
at java.lang.String.format(String.java:2940)
</code></pre>

<p>While running a test case, I see the log showing some error related to <code>Pattern</code>
Can somebody suggest, how to test the <code>String.format()</code> method? </p>
",https://stackoverflow.com/questions/58571448/android-unit-testing-with-mockito,"['android', 'unit-testing', 'junit', 'mockito', 'android-mvvm']",1144,True,-3,3
Unit testing functions from index.js,"<p>I have added an add-function in the fulfillment section of Dialogflow which works perfectly fine, when called. </p>

<pre><code>// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
// intentMap.set('your intent name here', yourFunctionHandler);
// intentMap.set('your intent name here', googleAssistantHandler);
agent.handleRequest(intentMap);
});

function myadd(a,b){
    return a+b
}
</code></pre>

<p>I want to unittest that function with mocha. In order to do that I have to export the function for my test file, so I tried to do this in the following manner:</p>

<pre><code>// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
// intentMap.set('your intent name here', yourFunctionHandler);
// intentMap.set('your intent name here', googleAssistantHandler);
agent.handleRequest(intentMap);
});

exports.dialogflowFirebaseFulfillment = {
    myaddfunction: (a, b) =&gt; {
        return a + b
    }
}
</code></pre>

<p>This change causes the error message: <strong>function failed on loading user code. Error message: The function exported from file index.js as dialogflowFirebaseFulfillment needs to be of type function. Got: object</strong>s</p>

<p>How will I be able to call my functions from index.js and export it for unittesting at the same time? I think I am missing a concept here.</p>

<p>I tried the below suggestion:</p>

<pre><code>import isEmpty from './works';
</code></pre>

<p>In the works.js file in the same folder I have the following code:</p>

<pre><code>function isEmpty(obj) {
    for (let key in obj) {
        if (obj.hasOwnProperty(key))
            return false;
    }
    return true;
}


export {
    isEmpty
};
</code></pre>

<p>But then I get the error: </p>

<p>import isEmpty from './works';
       ^^^^^^^</p>

<p>SyntaxError: Unexpected identifier</p>
",https://stackoverflow.com/questions/57376510/unit-testing-functions-from-index-js,"['javascript', 'dialogflow-es']",356,False,0,1
Unit testing and assert result,"<p>I have Video Service class as follows:</p>

<pre><code>public class VideoService
{
    private IFileReader _fileReader;
    private IVideoRepository _repository;
    public string _videoPath;

    public VideoService(IFileReader fileReader, IVideoRepository repository)
    {
        _fileReader = fileReader;
        _repository = repository;
    }

    public string ReadVideoTitle()
    {
        var str = _fileReader.Read(_videoPath);
        if (str == """")
        {
            return """";
        }
            else
        {
            return ""b"";
        }        
    }
}
</code></pre>

<p>then there is IFileReader and FileReader as below:</p>

<pre><code>   public interface IFileReader
    {
        string Read(string path);
    }

    public class FileReader : IFileReader
    {
        public string Read(string path)
        {
            return File.ReadAllText(path);
        }
    }
</code></pre>

<p>Now i have my unit test:</p>

<pre><code>[TestFixture]
public class VideoServiceTests
{
    private VideoService _videoService;
    private Mock&lt;IFileReader&gt; _fileReader;
    private Mock&lt;IVideoRepository&gt; _repository;
    private string _videoPath;

    [SetUp]
    public void SetUp()
    {
        _fileReader = new Mock&lt;IFileReader&gt;();
        _repository = new Mock&lt;IVideoRepository&gt;();
        _videoPath = @""test.txt"";
        _videoService = new VideoService(_fileReader.Object, _repository.Object);
        }

[Test]
     public void ReadVideoTitle_EmptyFile_ReturnError()
     {
        _fileReader.Setup(fr =&gt; fr.Read(_videoPath)).Returns("""");
        var result = _videoService.ReadVideoTitle();
        Assert.That(result, Does.Contain("""").IgnoreCase);
}
</code></pre>

<p>My problem is and what i am not understanding. When i do <code>_fileReader.Setup ..</code>
My understanding is it is a fake reader and not <code>FileReader class</code> right?, therefore when i say put whatever in <code>Read</code> parameter like: <code>test.txt</code> then i say i am expecting <code>Returns """"</code>. In Assert i am comparing it to what i get from <code>ReadVideoTitle</code>. However what is the sense of Assert here? Since <code>_fileReader</code> is just interface and not real class it will not really look and try to read fake <code>test.txt</code> file and look for output. Therefore first question why i always get <code>test Success</code> whatever i put in <code>_fileReader.Setup</code>. How it checks whether is <code>Success</code>? Shouldn'e it be just Vlaidate() if Read was really called, since it's nt really testing values? Can anyone be so kind and explain me how current example test works and what is really testing because so far i am lost. </p>
",https://stackoverflow.com/questions/55008542/unit-testing-and-assert-result,['c#'],85,False,0,0
Unit Testing with Firebase (Swift),"<p>Trying to do some simple unit testing with Firebase, but for some reason Firestore won't initialize:</p>

<p>ModelTests.swift:</p>

<pre><code>func testFirebase() throws
{
    // THIS IS ALWAYS ""UNINITIALIZED""
    let db = Firestore.firestore()

    // Because db isn't initialized correctly, this ref will always be nil.
    let ref: DocumentReference? = db.document(""unit_testing/xxx"")
    ref?.setData([
        ""id"" : ""someID"",
        ""name"" : ""goldenjoe"",
        ""another"" : ""bmus"",
        ""testDate"" : Date()
        ],
                 merge: true,
                 completion: { err in
                    if let err = err {
                        print(""Error adding document: \(err)"")
                    } else {
                        print(""Document added with ID: \(ref!.documentID)"")
                    }
                }
        )
}
</code></pre>

<p>AppDelegate.swift:</p>

<pre><code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool 
{
    // Set up Firestore
    FirebaseApp.configure()
}
</code></pre>

<p>Podfile:</p>

<pre><code>platform :ios, '11.0'

target 'MyWork' do
use_frameworks!

# ignore all warnings from all pods
inhibit_all_warnings!

# Pods for MyWork
pod 'CoreXLSX'
pod 'Eureka'
pod 'Firebase/Firestore'
pod 'Firebase/Auth'
pod 'ProgressHUD'
#pod 'GoogleSignIn'
pod 'SteviaLayout'

target 'MyWorkTests' do
  inherit! :complete
  end

end
</code></pre>

<p>However, when I run the app normally, I can use Firebase just fine in other parts of the app. Can't find anything online about a special configuration being needed for unit testing.</p>
",https://stackoverflow.com/questions/57837137/unit-testing-with-firebase-swift,"['ios', 'swift', 'xcode', 'firebase', 'cocoapods']",372,False,0,1
Grails 3.3.8 unit testing service,"<p>I am trying to test a service method that uses a file under src/main/webapp/folder, however it is not working, for any reason it seems to not have access or something, the code to get the file is the following:</p>

<pre><code>def file = grailsApplication.parentContext.getResource(""folder/file.txt"").file
</code></pre>

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

<pre><code>ServletContext resource [/folder/file.txt] cannot be resolved to absolute file path - web application archive not expanded?
</code></pre>

<p>Any ideas?
it is not the grailsApplication inyection or the get resource method I think that the service do not have access to that path when it is used by the testing framework.</p>
",https://stackoverflow.com/questions/54835096/grails-3-3-8-unit-testing-service,"['unit-testing', 'grails']",262,True,0,1
Unit testing Scala using mockito,"<p>I'm very much new to doing unit testing in Scala using Mockito. I'm getting an error in the <code>thenReturn</code> statement.</p>

<pre><code>it should ""read null when readFromPostgresTarget is called with some 
         random driver"" in {

Given(""a null query is sent as query"")
       val query = """"
       val pgObject = mock[PersistenceObject]
       val postgresPersistenceObject = 
       mock[PostgressPersistenceServiceTrait]
       val mockDF = mock[DataFrame]

When(""it is passed to readFromPostgresTarget"")
        when(postgresPersistenceObject.readFromPostgresTarget(any[String],mock[Spark 
                                      Session], pgObject)).thenReturn(mockDF)

        assert(postgresPersistenceObject.readFromPostgresTarget(query, 
                             sparkSession, pgObject) === any[DataFrame])

Then(""a null value should be returned"")
        verify(postgresPersistenceObject, times(1))
}
</code></pre>

<p>I'm getting the error-</p>

<pre><code>overloaded method value thenReturn with alternatives:
  (x$1: Unit,x$2: Unit*)org.mockito.stubbing.OngoingStubbing[Unit] &lt;and&gt;
  (x$1: Unit)org.mockito.stubbing.OngoingStubbing[Unit]
 cannot be applied to (org.apache.spark.sql.DataFrame)
                .thenReturn(mockDF)
</code></pre>

<p>I tried making the <code>mockDF</code> in <code>thenReturn(mockDF)</code> to <code>thenReturn(any[DatafRame])</code>, it's not fixing the issue.</p>

<p>I tried passing a <code>SparkSession</code> instead of the mock it isn't working.</p>

<p>I can't figure what mistake I'm doing.</p>
",https://stackoverflow.com/questions/58698160/unit-testing-scala-using-mockito,"['scala', 'mockito']",356,False,0,1
Include problems when unit testing,"<p>When I unit test classes I need to change the include paths, but then the website it self won't work. Thus every time I test I need to change almost all include paths in the files and after testing change them back again. This obviously is not practical. </p>

<p>I roughly understand why this happens; because test files are not in the root directory.</p>

<p>Question: How can I keep unit test files in the same folder as files being tested without having to change the include paths?</p>

<p>I tried defining a PATH constant. This also didn't work because the file defining the constant redefines it everytime it is included, making it useless.</p>

<pre class=""lang-php prettyprint-override""><code>require_once 'database/CrudTest.php';
require_once 'UserModel.php';
require_once 'database/UserCrud.php';
use PHPUnit\Framework\TestCase;

class UserModelTest extends TestCase{
....
</code></pre>

<p>To test classes I have to put '../' before every include in every file needed for the test. Then remove them after test.</p>
",https://stackoverflow.com/questions/56497000/include-problems-when-unit-testing,"['php', 'phpunit', 'phpstorm']",52,True,0,1
Arduino unit testing using gtest,"<p>I have been playing around with a small Arduino robot I purchased and found that there are several bugs running around in the code (that I may have placed there haha) and wanted to apply gtest to the code to locate the bug(s). The issue is #include ""Arduino.h"" is not something that I can run on my PC. And it is something I am having difficulty decoupling from my code. </p>

<p>I would like to build a test executable in my test folder that can run on my PC but still keep the majority of the functional code in the directory above so the Arduino IDE can build as well. Any help would be greatly appreciated. </p>

<p>Structure:</p>

<pre><code>&lt;Folder&gt;
-ArduinoBuild.ino
-Class.h
-Class.cpp
-&lt;test folder&gt;
 --test.cpp
 --CMakeList.txt
</code></pre>

<p>This is where the problem begins, Arduino.h is introduced to the build</p>

<p>Class.h</p>

<pre><code>#ifndef CLASS_H_
#define CLASS_H_
#include ""Arduino.h""
class Class{

  public:
    int Some_Attribute = 0;

  void member_function();

};
#endif 
</code></pre>

<p>Class.cpp</p>

<pre><code>#include ""Class.h""
void Class::member_function(){
  Some_Attribute = Some_ArduinoFunc(this-&gt;Some_Attribute);
}
</code></pre>

<p>Now, if I could get Arduino.h out of my build I could place dummy functions in my test script to cover the gap, but I would like to keep Arduino.h somewhere in the build process so that way I don't have to go adding it in every time I want to build for my Arduino. I have tried several things, one of them being moving the #include ""Arduino.h"" to the .ino file in the hopes that it would get flowed down to the Class.h/cpp file when building for Arduino, and that failed.</p>

<p>test.cpp</p>

<pre><code>// Class_test.cpp
#include &lt;gtest/gtest.h&gt;
#include ""../Class.cpp""
TEST(buildbin, member_function) {
  Class car;
  car.member_function(1);
  ASSERT_EQ(1, car.Some_Attribute);
}
</code></pre>

<p>Again, any help with this would be greatly appreciated, thank you for your time.</p>

<p>POST SOLUTION Updates:
Here is a sample header to what I had to enter into the scripts in the parent folder:</p>

<pre><code>#ifndef ARDUINO 
#include&lt;cmath&gt;                                                                                          
#define floor std::round                                                                                 
void delay(int i){} 
#endif           
</code></pre>

<p>and to access files to mimic library files all you need to do is:</p>

<pre><code>#include ""test/FakeLib.XX""
</code></pre>
",https://stackoverflow.com/questions/54995265/arduino-unit-testing-using-gtest,"['c++', 'arduino', 'googletest']",1034,True,0,1
Perform ngx-spinner unit testing,"<p>I am using <a href=""https://github.com/Napster2210/ngx-spinner"" rel=""nofollow noreferrer"">ngx-spinner</a> on my component to show a loading indictor on the page on some remote call process. On my component I have the following code for ngx spinner:</p>

<pre><code>&lt;ngx-spinner [fullScreen]=""true"" type=""ball-clip-rotate"" size=""medium"" bdColor=""rgba(51,51,51,0.1)"" color=""grey""&gt;
&lt;/ngx-spinner&gt;
</code></pre>

<p>At the component on init while the page is loading I am showing the spinner like this:""</p>

<pre><code>  constructor(
    private spinner: NgxSpinnerService) {

  }

  ngOnInit() {

    this.spinner.show();
</code></pre>

<p>and after the I am making a remote call to the server and when that work is done I am hiding the spinner.</p>

<p>My goal is to create unit test for the same i.e when the page is loaded I need to make sure the spinner is showing on the page. In order to do that I wrote the following test case:</p>

<pre><code>  it('should show loading indicator if the page is not loaded', () =&gt; {

    // pageLoaded should be try because the form will be loaded only when that is true based on ng if

    const element = getElementByTag('ngx-spinner');

    //What to write here?

  });
</code></pre>

<p>I am getting the element there in my test but I was not able to get the way to detect whether it is visible or not. I tried element.nativeElement.visible but it returned as null.</p>
",https://stackoverflow.com/questions/58822790/perform-ngx-spinner-unit-testing,"['angular', 'typescript']",1919,False,0,1
Angular Guard CanLoad Unit Testing,"<p>I'm relatively new to Angular 7, having come from AngularJS, I've written a guard implementing CanLoad which stops users without the correct claims loading a module. It checks whether the user is logged in and whether the user has a claim that's expected by the route.</p>

<pre><code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoadGuard } from './core/authentication/guards/load.guard';
import { MainMenuComponent } from './core/navigation/main-menu/main-menu.component';
import { PageNotFoundComponent } from './core/navigation/page-not-found/page-not-found.component';
import { UnauthorisedComponent } from './core/navigation/unauthorised/unauthorised.component';

const routes: Routes = [
  { path:'', component: MainMenuComponent, outlet: 'menu'},
  { path: 'authentication', loadChildren: './core/authentication/authentication.module#AuthenticationModule' },
  { path: 'home', loadChildren: './areas/home/home.module#HomeModule', canLoad: [LoadGuard], data: {expectedClaim: 'home'} },
  { path:""unauthorised"", component: UnauthorisedComponent},
  { path:'**', component: PageNotFoundComponent }
];

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

<p>The guard works, however I'm having trouble writing the unit test for it.</p>

<pre><code>import { Injectable } from '@angular/core';
import { CanLoad, Route, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthenticationService } from 'src/app/Services/Authentication/authentication.service';

@Injectable({
  providedIn: 'root'
})
export class LoadGuard implements CanLoad {

  constructor(private authService: AuthenticationService, private router: Router){}

  canLoad(route: Route): Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean {
    if (!route || !route.path) return false;
    let isValid: boolean = this.checkLoggedIn(route.path);
    if (isValid) {
      if (route.data &amp;&amp; route.data.expectedClaim) {
        let expectedClaim = route.data.expectedClaim;
        isValid = this.checkClaim(expectedClaim);
      }
    }
    return isValid;
  }

  checkLoggedIn(url: string): boolean {
    if (this.authService.checkLoggedIn()) {
      return true;
    }
    this.authService.redirectUrl = url;
    console.log('this.authService.redirectUrl (after)= ' + this.authService.redirectUrl);
    this.router.navigate(['/authentication/login']);
    return false;
  }

  checkClaim(claim: string) {
    let hasClaim: boolean = false;
    if (this.authService.currentUser) {
      hasClaim = this.authService.currentUser.claims.indexOf(claim) &gt; -1;
    }
    return hasClaim;
  }

}
</code></pre>

<p>The unit test I have below doesn't work:</p>

<pre><code>import { HttpClientModule } from '@angular/common/http';
import { fakeAsync, TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, ActivatedRoute, Route } from '@angular/router';
import { LoadGuard } from './load.guard';

class MockActivatedRouteSnapshot {
  private _data: any;
  get data(){
     return this._data;
  }
}

let mockRouterStateSnapshot : RouterStateSnapshot;

describe('LoadGuard', () =&gt; {
  let loadGuard: LoadGuard;
  let route: ActivatedRouteSnapshot;
  let authService;
  let mockRouter: any;  

  beforeEach(() =&gt; {
    mockRouter = jasmine.createSpyObj('Router', ['navigate']);

    TestBed.configureTestingModule({
      imports: [
        HttpClientModule,
      ],
      providers: [
        LoadGuard,
        { provide: ActivatedRouteSnapshot, useClass: MockActivatedRouteSnapshot},
        { provide: Router, useValue: mockRouter},
      ]
    });

  });


  it('should be created', () =&gt; {
    authService = { checkLoggedIn: () =&gt; true };
    loadGuard = new LoadGuard(authService, mockRouter);
    expect(loadGuard).toBeTruthy();
  });

  describe('check expected claims', ()=&gt;{
    it('should not be able to load an valid route needing claim when logged in without claim', fakeAsync(() =&gt; {
      authService = { checkLoggedIn: () =&gt; true };
      loadGuard = new LoadGuard(authService, mockRouter);

      let route = new Route();
      spyOnProperty(route,'data','get').and.returnValue({expectedClaim: 'policy'});
      mockRouterStateSnapshot = jasmine.createSpyObj&lt;RouterStateSnapshot&gt;('RouterStateSnapshot', ['toString']);
      mockRouterStateSnapshot.url = ""test"";

      expect(loadGuard.canLoad(route)).toBeFalsy();
    }));

});
</code></pre>

<p>It doesn't allow me to New a Route. I might just be doing the test wrong. Can anyone help with this?</p>
",https://stackoverflow.com/questions/55743139/angular-guard-canload-unit-testing,"['angular', 'jasmine', 'angular7', 'angular-guards']",1262,True,0,1
Altering objects in Unit Testing?,"<p>I'm trying to test a class. Doing so, I'm changing the objects state, yet for some reason, that change is only temporary.</p>

<p>Here is what I mean:</p>

<pre><code>class ownerTest {

Owner Tom = new Owner(); // creates owner and initializes arraylist of type pet
Pet Doggy = new Pet(""Rexy""); // creates pet object doggy

@Test
public void test1() {
    Tom.addPet(Doggy); //will add doggy on to tom's arraylist
    assertEquals(Doggy, Tom.petList.get(0)); // passes
}

@Test
public void test2() {
    assertEquals(Doggy, Tom.petList.get(0)); // fails cause arraylist is empty
}
</code></pre>

<p>I've been told that I can treat test classes much like normal classes. Then why are changes made to objects in test units only temporary?</p>

<p>Would love some clarification.</p>

<p>PS: The equals method has been adjusted accordingly so it's not about that.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/57466803/altering-objects-in-unit-testing,"['java', 'testing', 'junit']",712,True,0,1
Angular 2+ unit testing pipe,"<p>I have a pipe</p>

<pre><code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filterArrayPipe'
})
export class FilterArrayPipe implements PipeTransform {
  transform(value: any, config: any, q: string) {
    if (config &amp;&amp; q) {
      return value.filter(result =&gt; {
        return config.some(type =&gt; result[type].toString().toLowerCase().indexOf(q) &gt; -1);
      });
    } else {
      return value;
    }
  }
}
</code></pre>

<p>and now I want to make a unit test</p>

<pre><code>import { FilterArrayPipe } from './filter-array.pipe';
describe('Pipe: FilterArray Pipe', () =&gt; {
  it('providing search value should return true', () =&gt; {
      const pipe = new FilterArrayPipe();

      expect(pipe.transform([{id: 123}, {id: 456}], ['id'], '456'))
        .toBe([{id: 456}]);
  });
});
</code></pre>

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

<pre><code>Expected [ Object({ id: 456 }) ] to be [ Object({ id: 456 }) ].
</code></pre>
",https://stackoverflow.com/questions/54128497/angular-2-unit-testing-pipe,"['angular', 'unit-testing']",805,True,0,1
Condition Coverage and Unit Testing,"<p>when writing unit tests (with junit), is it necessary to separate test methods to reach a complete condition coverage?</p>

<p>take this snippet for example:</p>

<pre><code>int foo(boolean a, boolean b, boolean c){
    if(a &amp;&amp; b &amp;&amp; c)
        return 1;
    else return 0;
}
</code></pre>

<p>Is it better to write one method and different assertions for condition coverage if this if? Or one method for each condition?</p>

<pre><code>@Test
void conditionsTest(){
    assertEqual(0, foo(true, false, false));
    assertEqual(0, foo(true, true, false));
    assertEqual(1, foo(true, true, true));
    ...
}
</code></pre>

<p><strong>OR</strong></p>

<pre><code>@Test
void condition1Test(){
    assertEqual(0, foo(true, false, false));
}

@Test
void condition2Test(){
    assertEqual(0, foo(true, true, false));
}

@Test
void condition3Test(){
    assertEqual(1, foo(true, true, true));
}
</code></pre>
",https://stackoverflow.com/questions/54634403/condition-coverage-and-unit-testing,"['unit-testing', 'junit', 'separation-of-concerns', 'test-coverage']",2890,True,0,1
Unit Testing exported module functions,"<p>Trying to unit test the functions inside an exported module with the help of <code>Jest</code></p>

<p>The module is the following: </p>

<pre><code>
export default {

  errorNotification (title, text) {
    Vue.notify({
      group: 'max-fordham',
      type: 'error',
      title: title,
      text: text
    })
  },

  infoNotification (title, text) {
    Vue.notify({
      group: 'max-fordham',
      type: 'info',
      title: title,
      text: text
    })
  },

  successNotification (title, text) {
    Vue.notify({
      group: 'max-fordham',
      type: 'success',
      title: title,
      text: text
    })
  },

  warningNotification (title, text) {
    Vue.notify({
      group: 'max-fordham',
      type: 'warning',
      title: title,
      text: text
    })
  }
}
</code></pre>

<p>The test I'm trying to write is: </p>

<pre><code>import notifications from '@/services/notifications.service'

describe('Notifications tests', () =&gt; {
  test('successNotification should set title to title and text to text ', () =&gt; {
    let title = 'test'
    let text = 'test'

    //let successNotification = jest.fn()

    notifications.successNotification(title, text)
    expect(title).toEqual('test')
    expect(text).toEqual('test')
  })
})

</code></pre>

<p>When I run this I receive the following error: </p>

<blockquote>
  <p>TypeError: _vue.default.notify is not a function</p>
</blockquote>

<p>Now, as far as I understand, the error is due to me not mocking <code>_vue.default.notify</code>, however, I am not sure how to actually do that. Some help will be appreciated. </p>
",https://stackoverflow.com/questions/58239972/unit-testing-exported-module-functions,"['javascript', 'unit-testing', 'jestjs']",86,True,0,1
RxJava unit testing in Kotlin,"<p>I'm trying to unit test my code that uses RxJava's <code>Observable#flatMap</code>, but I'm running into <code>java.lang.NullPointerException</code>. How do I write my unit test (and avoid the exception)?</p>

<p><em>Code to be unit tested:</em></p>

<pre class=""lang-java prettyprint-override""><code>public void submit(final NameRequest request, final AgeRequest ageRequest) {
    model.getAccountName(request)
        .flatMap(new Function&lt;NameResponse, Observable&lt;AgeResponse&gt;&gt;() {
            @Override
            public Observable&lt;AgeResponse&gt; apply(NameResponse response)
                    throws Exception {
                final Status status = response.getStatus();
                if (status.getCode() != 1) {
                    throw new Exception(status.getDescription());
                }
                return model.getAge(ageRequest);
            }
        }, new BiFunction&lt;NameResponse, AgeResponse, AgeResponse&gt;() {
            @Override
            public AgeResponse apply(NameResponse nameResponse, AgeResponse ageResponse) {
                ageResponse.setCustomerName(nameResponse.getName());
                return ageResponse;
            }
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
}
</code></pre>

<p><em>Test code:</em></p>

<pre><code>val mockResponse = AgeResponse()
Mockito.doReturn(Observable.just(mockResponse))
                .`when`(mNetworkModel)
                .preSubmit(ageRequest)
mPresenter.submit(nameRequest, ageRequest)
</code></pre>
",https://stackoverflow.com/questions/57868526/rxjava-unit-testing-in-kotlin,"['android', 'unit-testing', 'kotlin']",146,False,0,0
Nunit unit testing random number,"<p>I'm looking to unit test a method that returns a random float as an ID. I am trying to use Red Green Refactor, but am stumped by the randomness of the code. Below find the method I am trying to test. I am aware that I am technically supposed to write the test first, but I don't know how to test for random.</p>

<pre><code>public Random ReturnDevID()
                {
                    var rnd = new Random();
                    rnd.NextDouble();
                    return rnd;
                }
</code></pre>
",https://stackoverflow.com/questions/58960725/nunit-unit-testing-random-number,"['c#', 'unit-testing', 'random', 'nunit']",394,False,-1,1
Unit testing non void methods,"<p>I am writing a application using the repository pattern. I'm currently in the view model, and want to write a unit test for a method that returns a random int. How do I go about writing a unit test for a non-void method? Would I use a mocking framework? I am not familiar with how those work. Any guidance appreciated.</p>
",https://stackoverflow.com/questions/58789245/unit-testing-non-void-methods,"['unit-testing', 'methods']",206,False,-2,1
Golang unit testing using PanicsWithValue,"<p>We are trying to test a function that raises an <code>index out of range</code> error.  </p>

<p>The code of the unit test is simple, something like:</p>

<pre><code>import (
    ""testing""

    ""github.com/stretchr/testify/assert""
)

func TestIndexOutOfRange(t *testing.T) {
    assert.PanicsWithValue(t, ""index out of range"", func() { indexOutOfRange(9) })
}
</code></pre>

<p>But unfortunately the test Fails with a strange error</p>

<pre class=""lang-none prettyprint-override""><code>=== RUN   TestIndexOutOfRange
--- FAIL: TestIndexOutOfRange (0.00s)
  &lt;autogenerated&gt;:1:
    Error Trace: badindex_test.go:55
    Error: func (assert.PanicTestFunc)(0x1c440d0) should panic with value: ""index out of range""
    Panic value: ""index out of range""
    Test: TestIndexOutOfRange
</code></pre>

<p>You can see that the panic value and the error show the same, but test still fails.<br>
Any ideas what is going on?</p>
",https://stackoverflow.com/questions/55596268/golang-unit-testing-using-panicswithvalue,"['unit-testing', 'go', 'testify']",2416,True,0,1
Unit testing if text == null,"<p>I am doing some unit tests with microsoft unit testing</p>

<p>I have this piece of code:</p>

<pre><code>public void AddComment(Case c, string text)
        {
            if (text == null)
            {
                return;
            }

            var comment = UnitOfWork.GetRepository&lt;CaseComment&gt;().Create();

            comment.Case = c;
            comment.Account = _userInfoProvider.UserName;
            comment.DateUtc = DateTimeHelper.UtcNow();
            comment.Text = text;

            UnitOfWork.GetRepository&lt;CaseComment&gt;().Insert(comment);
        }
</code></pre>

<p>And I have a Unit test for this piece of cdoe:</p>

<pre><code> if (text == null)
            {
                return;
            }
</code></pre>

<p>I the unit test like this:</p>

<pre><code> [TestMethod]
        public void BaseProcess_Should_AddCommentIfNull()
        {
            string text = null;

            var result = string.IsNullOrEmpty(text);

            Assert.AreEqual(text, null);

        }
</code></pre>

<p>It shows green. But the code coverage is still yellow and not blue.</p>

<p>Thank you</p>

<p>I have it now like this:</p>

<pre><code> [TestMethod]
        public void BaseProcess_Should_AddCommentIfNull()
        {
            string comment = ""Comment"";
            var newInstance = new Case
            {

                Reference = comment,                
                DateSubmitted = DateTime.Now,                      
                Status = CaseStatus.Submitted,
            };          

            string text = null;

            var result = string.IsNullOrEmpty(text);
            Action act = () =&gt; CorrectionRequestCaseProcess.AddComment(newInstance, comment);

            Assert.AreEqual(text, null);

        }
</code></pre>

<p>But if I do it like this:</p>

<pre><code> [TestMethod]
        public void BaseProcess_Should_AddCommentIfNull()
        {
            string comment = """";
            var newInstance = new Case
            {

                Reference = comment,                
                DateSubmitted = DateTime.Now,                      
                Status = CaseStatus.Submitted,
            };          

            string text = null;

            var result = string.IsNullOrEmpty(text);
            Action act = () =&gt; CorrectionRequestCaseProcess.AddComment(newInstance, text);

            Assert.AreEqual(text, null);

        }
</code></pre>

<p>Nothing changed<code>enter code here</code></p>

<p>And I wrote a other unit test like this:</p>

<pre><code>[TestMethod]
public void BaseProcess_should_equalToNull()
{
    string comment = ""Comment"";
    var newInstance = new Case
    {

        Reference = comment,
        DateSubmitted = DateTime.Now,
        Status = CaseStatus.Submitted,
    };

    var newComment = new CaseComment();
    newComment.Case = newInstance;
    newComment.Account = _userInfoProvider.UserName;
    newComment.DateUtc = DateTimeHelper.UtcNow();
    newComment.Text = comment;

    var comment2 = _testUnitOfWork.GetRepository&lt;CaseComment&gt;().Create();
    _testUnitOfWork.GetRepository&lt;CaseComment&gt;().Insert(newComment);
}
</code></pre>
",https://stackoverflow.com/questions/54590723/unit-testing-if-text-null,"['c#', 'unit-testing']",1432,False,0,1
Jasmine unit testing with Istanbul,"<p>I am doing unit testing with Jasmin and Istanbul.</p>

<p>I try to do unit testing on the following method:</p>

<pre><code> getDiploma(spinnerMessage: string): Observable&lt;DiplomaModel&gt; {
        const diploma = this.diplomasState.diploma;
        if (diploma) {
            // Return diploma info from store
            return observableOf(diploma);
        } else {
            // Get and return diploma info from backend
            return this.http.get&lt;DiplomaModel&gt;(this.apiDiploma, spinnerMessage).pipe(map((result) =&gt; {
                return this.setDiplomasInStore(result);
            }));
        }
    }
</code></pre>

<p>And my unit test looks like this:</p>

<pre><code> it('It should return diploma from the backend when snapshot exist ', () =&gt; {

            diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
            const diplomaState = diplomaService.getDiplomaSnapshot();
            expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));

            // tslint:disable-next-line:no-commented-code
            /*  const response = [{ mock: 'mock' } as any];
             diplomaService['getDiplomaSnapshot'] = response;
             diplomaService.getDiplomaState().subscribe(i =&gt; {
                 expect(i).toEqual(response);
             }); */
        });

it('It should return diploma if snapshot doenst exist', () =&gt; {
    const apiString = 'api/register/teachers/current/diploma';
    const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
    const spyDocument = spyOn(diplomaService, 'getDiploma').and.callThrough();

    diplomaStoreServiceMock.returnState({});
    const response = { 'mock': 'mockResult' };
    afwHttp.setupOnlyResponse(response, 200);
    diplomaService.getDiploma('spinnerText').subscribe(result =&gt; expect(result['mock']).toEqual('mockResult'));
    afwHttp.returnOnlyResponse();
    expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
    expect(spyDocument).toHaveBeenCalledWith('spinnerText');
});
</code></pre>

<p>But in Istanbul I get still a red line on this line:</p>

<pre><code> return observableOf(diploma);
</code></pre>

<p>with a I and if I hover over the I is says:</p>

<p>if Path not taken.</p>

<p>So how to solve this?</p>

<p>Thank you.</p>

<p>but that is why I have two methods. But you mean this method:</p>

<pre><code>it('It should return diploma from the backend when snapshot exist ', () =&gt; {



     diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();
        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });
</code></pre>

<p>What I have to change about this test method?</p>

<p>You mean like this:</p>

<pre><code> it('It should return diploma from the backend when snapshot exist ', () =&gt; {

        diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();
        diplomaService.getDiploma('spinnerText');
        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });
</code></pre>

<p>I also tried like this:</p>

<pre><code>it('It should return diploma from the backend when snapshot exist ', () =&gt; {
    const response = [{ mock: 'mock' } as any];
    diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
    const diplomaState = diplomaService.getDiplomaSnapshot();
    diplomaService.getDiploma('spinnerText').subscribe( i =&gt; {
        expect(i).toEqual(response);

    });
    expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
});
</code></pre>

<p>And if I add this method:</p>

<pre><code>  it('It should return diploma', () =&gt; {
        const response = [{ mock: 'mock' } as any];
        diplomaService.getDiploma('spinnerText').subscribe( i =&gt; {
            expect(i).toEqual(response);

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

<p>I get this error:</p>

<blockquote>
  <p>ERROR in
  apps/register/src/app/shared/services/src/diploma.service.spec.ts(67,31):
  error TS2345: Argument of type 'any[]' is not assignable to parameter
  of type 'Expected'.   Type 'any[]' is not assignable to
  type 'ObjectContaining'.
      Property 'jasmineMatches' is missing in type 'any[]'.</p>
</blockquote>

<p>So I have now three methods:</p>

<pre><code> it('It should return diploma from the backend when snapshot exist ', () =&gt; {
        diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();
        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });

    it('It should return diploma', () =&gt; {
        const response = [{ mock: 'mock' } as any];
        diplomaService.getDiploma('spinnerText').subscribe( i =&gt; {
            expect(i).toEqual(response);

        });
    });


    it('It should return diploma if snapshot doenst exist', () =&gt; {
        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        const spyDocument = spyOn(diplomaService, 'getDiploma').and.callThrough();
        const response = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(response, 200);
        diplomaService.getDiploma('spinnerText').subscribe(result =&gt; expect(result['mock']).toEqual('mockResult'));
        afwHttp.returnOnlyResponse();
        expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
        expect(spyDocument).toHaveBeenCalledWith('spinnerText');
    });
</code></pre>

<p>This is the hole test file:</p>

<pre><code>describe('Services: DiplomaService', () =&gt; {


    let afwHttp: AfwHttpMock;
    let diplomaService: DiplomaService;
    let diplomaStoreServiceMock: DiplomaStoreServiceMock;
    let feedbackStoreServiceMock: FeedbackStoreServiceMock;
    let multiFileUploadServiceMock: MultiFileUploadServiceMock;




    beforeEach(() =&gt; {
        afwHttp = new AfwHttpMock();
        diplomaStoreServiceMock = new DiplomaStoreServiceMock();
        multiFileUploadServiceMock = new MultiFileUploadServiceMock();
        feedbackStoreServiceMock = new FeedbackStoreServiceMock();
        diplomaService = new DiplomaService(afwHttp as any,
            diplomaStoreServiceMock as any,
            feedbackStoreServiceMock as any,
            multiFileUploadServiceMock as any);
    });

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


    it('It should return diplomadocumentList', () =&gt; {
        // tslint:disable-next-line:no-duplicate-string
        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        const spyDocumentList = spyOn(diplomaService, 'getDiplomaDocumentList').and.callThrough();
        const response = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(response, 200);

        const result2 = diplomaService.getDiplomaDocumentList('spinnerText');
        result2.subscribe(() =&gt; {
            expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
            expect(spyDocumentList).toHaveBeenCalledWith('spinnerText');
        });
        afwHttp.returnOnlyResponse();
    });


    // tslint:disable-next-line:no-commented-code

    it('It should return diploma from the backend when snapshot exist ', () =&gt; {
        diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();

        diplomaService.getDiploma('spinnerText').subscribe(result =&gt; expect(result['mock']).toEqual('mockResult'));

        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });

   // tslint:disable-next-line:no-commented-code
   /*  it('It should return diploma', () =&gt; {
        const response = [{ mock: 'mock' } as any];
        diplomaService.getDiploma('spinnerText').subscribe( i =&gt; {
            expect(i).toEqual(response);

        });
    }); */


    it('It should return diploma if snapshot doenst exist', () =&gt; {
        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        const spyDocument = spyOn(diplomaService, 'getDiploma').and.callThrough();
        const response = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(response, 200);
        diplomaService.getDiploma('spinnerText').subscribe(result =&gt; expect(result['mock']).toEqual('mockResult'));
        afwHttp.returnOnlyResponse();
        expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
        expect(spyDocument).toHaveBeenCalledWith('spinnerText');
    });

    // tslint:disable-next-line:no-identical-functions
    it('It should save diploma record to database', () =&gt; {

        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'post').and.callThrough();
        const spyDocument = spyOn(diplomaService, 'saveDiplomaMetaData').and.callThrough();
        const response = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(response, 200);

        const result2 = diplomaService.saveDiplomaMetaData(false, 'spinnerText');
        result2.subscribe(() =&gt; {
            expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
            // tslint:disable-next-line:no-commented-code
            expect(spyDocument).toHaveBeenCalledWith(false, 'spinnerText');
        });
        afwHttp.returnOnlyResponse();
    });

    it('It should save documents for  diploma record', fakeAsync(() =&gt; {
        const spy = spyOn(multiFileUploadServiceMock, 'syncFilesWithBackend').and.callThrough();
        const spyFeedback = spyOn(feedbackStoreServiceMock, 'addErrorMessage');

        multiFileUploadServiceMock.setResponse([{ error: 'error' }]);


        diplomaService.saveDocumentForDiploma([{} as any], () =&gt; { }, MultiFileUploadResourcesModel.keys, { key: 'diploma', value: 'document' });

        expect(spy).toHaveBeenCalledWith('api/register/teachers/current/diploma/documents', [{}],
            MultiFileUploadResourcesModel.keys.bijlageToevoegenSpinnerTekst,
            MultiFileUploadResourcesModel.keys.bijlageVerwijderenSpinnerTekst
        );

        tick();
        expect(spyFeedback).toHaveBeenCalled();
    }));

    // tslint:disable-next-line:no-identical-functions
    it('should return document list ', fakeAsync(() =&gt; {
        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        const spyDocumentList = spyOn(diplomaService, 'getDiplomaDocumentList').and.callThrough();
        const response = { 'mock': 'mockResult' };

        multiFileUploadServiceMock.setResponse([{}]);
        afwHttp.setupOnlyResponse(response, 200);

        const result2 = diplomaService.getDiplomaDocumentList('spinnerText');
        result2.subscribe(() =&gt; {
            expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
            expect(spyDocumentList).toHaveBeenCalledWith('spinnerText');
            expect(spyDocumentList).not.toBeNull();

        });
        afwHttp.returnOnlyResponse();

    }));

    // tslint:disable-next-line:no-identical-functions
    it('It should return diplomaSnapshot', () =&gt; {
        diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();
        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });
});
</code></pre>

<p>I have it now like this:</p>

<pre><code>it('It should return diploma from the snapshot as an observable ', () =&gt; {

        const expected = { code: '00100-00101', test: 'test' };
        afwHttp.setupOnlyResponse(expected, 200);
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        diplomaStoreServiceMock.returnState({diploma: expected});


        diplomaService.getDiploma('spinnerText').subscribe(result =&gt; expect(result['mock']).toEqual('mockResult'));
        afwHttp.returnOnlyResponse();
        expect(spyHttp).not.toHaveBeenCalledWith();

    });
</code></pre>

<p>But then I will get this error:</p>

<blockquote>
  <p>Services: DiplomaService > It should return diploma from the snapshot
  as an observable Expected undefined to equal 'mockResult'. Error:
  Expected undefined to equal 'mockResult'.
      at 
      at SafeSubscriber._next (<a href=""http://localhost:9877/src/app/shared/services/src/diploma.service.spec.ts?:65:93"" rel=""nofollow noreferrer"">http://localhost:9877/src/app/shared/services/src/diploma.service.spec.ts?:65:93</a>)
      at SafeSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (<a href=""http://localhost:9877/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/rxjs/_esm5/internal/Subscriber.js?:196:1"" rel=""nofollow noreferrer"">http://localhost:9877/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/rxjs/_esm5/internal/Subscriber.js?:196:1</a>)
      at SafeSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next
  (<a href=""http://localhost:9877/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/rxjs/_esm5/internal/Subscriber.js?:134:1"" rel=""nofollow noreferrer"">http://localhost:9877/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/rxjs/_esm5/internal/Subscriber.js?:134:1</a>)</p>
</blockquote>

<p>Ah, oke.</p>

<p>I have it now like this:</p>

<pre><code> it('It should return diploma from the snapshot as an observable ', () =&gt; {

        const expected = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(expected, 200);
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        diplomaStoreServiceMock.returnState({diploma: expected});


        diplomaService.getDiploma('spinnerText').subscribe(result =&gt; expect(result['mock']).toEqual('mockResult'));
        afwHttp.returnOnlyResponse();
        expect(spyHttp).not.toHaveBeenCalledWith();

    });
</code></pre>

<p>and it works</p>
",https://stackoverflow.com/questions/54389597/jasmine-unit-testing-with-istanbul,"['angular', 'typescript', 'unit-testing', 'jasmine', 'istanbul']",126,False,0,0
"Unit Testing using mocha, node","<p>I'm new to unit testing in the Node world and am struggling with this: I've setup a after cb to delete the records I've added during my tests, however I keep getting an error <code>Error: done() called multiple times</code> every time I delete the record on the db. Here's my code:</p>

<pre><code>after((done) =&gt; {
    User.deleteOne({email: user_email}, function(err, result) {
        if(err) console.log(err);
        console.log(result);
        done();
    });
});
</code></pre>

<p>If I do anything else (like just console something within the <code>after</code> block, I get no error at all.</p>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/55614613/unit-testing-using-mocha-node,"['node.js', 'mocha.js']",29,True,0,1
Anonymous Types in Unit Testing,"<p>I'm writing an application that allows users to ""log on"" by registering with the same email. (Don't worry, it's not an application that will run on the internet, and also doesn't hold critical data. It's a temporary registration and will only run in local networks.) The MVC method is supposed to return the API key and some other data upon successfully logging in. I created a unit test to check this behavior:</p>

<pre><code>[Fact]
public void Register_ExistingEmail()
{
    //Arrange
    DbContext context = new DbContext(InMemoryDbContextOptionsExtensions.UseInMemoryDatabase(new DbContextOptionsBuilder&lt;DbContext&gt;(), ""VoteInMemDb"").Options);
    context.Users.Add(new User { ApiToken = ""TestToken123"", Email = ""commonname@commondomain.com"", JsonData = ""{}"" });
    context.SaveChanges();
    //logger, hub and settings are being mocked using Moq and are set up in the constructor
    RegistrationController regCon = new RegistrationController(logger, context, hub, settings);

    //Act
    IActionResult result = regCon.Register(""commonname@commondomain.com"", ""{}"", false);

    //Assert
    try
    {
        //attempt to cast to expected result type
        JsonResult jsonResult = (JsonResult)result;

        Assert.Equal(new
        {
            apiToken = ""TestToken123"",
            currentScreen = ClientScreen.welcome.ToString(),
            cookieDuration = settings.Value.ApiTokenDuration
        }, jsonResult.Value);
    }
    catch (EqualException e)
    {
        throw e;
    }
    catch
    {
        Assert.True(false);
    }
}
</code></pre>

<p>Now, even though it successfully returns the object as expected, it still throws an <code>EqualException</code>:</p>

<pre><code>Testname:   project.unit_tests.UnitTest1.Register_ExistingEmail
FullName für Test:  project.unit_tests.UnitTest1.Register_ExistingEmail
Testquelle: D:\Repositories\project.unit-tests\UnitTest1.cs : Zeile 77
Testergebnis:   Fehler
Testdauer:  0:00:01.009

Ergebnis StackTrace:    at project.unit_tests.UnitTest1.Register_ExistingEmail() in D:\Repositories\project.unit-tests\UnitTest1.cs:line 104
Ergebnis Meldung:   
Assert.Equal() Failure
Expected: { apiToken = TestToken123, currentScreen = welcome, cookieDuration = 1440 } (&lt;&gt;f__AnonymousType0`3[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]])
Actual:   { apiToken = TestToken123, currentScreen = welcome, cookieDuration = 1440 } (&lt;&gt;f__AnonymousType1`3[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]])
</code></pre>

<p>I see that it is 99% the same object, besides the <code>&lt;>f__AnonymousTypeX`3</code> part. Is this because I'm using anonymous <code>Types</code> for generating <code>JsonResults</code>? Do I have to create models for every anonymous <code>Type</code> I'm returning to unit test the method?</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/55590730/anonymous-types-in-unit-testing,"['c#', 'unit-testing', 'xunit', 'anonymous-types']",582,False,0,0
Unit testing Android Tab Layout,"<p>I am new to Android Unit testing and trying to write some test cases for Android tab layout with <code>Robolectric</code>. I am able to verify the tab count and tab titles. But I am not able to verify some content in tabs. Can anyone help me in getting the fragment content and verify some elements in that?</p>

<p>Here is my code</p>

<pre><code>public void verifyTabsDefaultText() throws Exception{
    ViewPager viewPager = searchActivity.findViewById(R.id.container);
    FragmentPagerAdapter tabAdapter = (FragmentPagerAdapter) viewPager.getAdapter();

    viewPager.setCurrentItem(0);

    TextView hintTextView = tabAdapter.getItem(0).getActivity().findViewById(R.id.search_hint_text_view);

    assertTrue(hintTextView.getVisibility() == View.VISIBLE);

}
</code></pre>

<p><code>tabAdapter.getItem(0)</code> is giving <code>null</code> value.</p>

<p>Thanks in advance. </p>
",https://stackoverflow.com/questions/57057785/unit-testing-android-tab-layout,"['android', 'robolectric']",2078,False,0,3
Unit testing with Apache Camel,"<p>I want to test below camel route. All the example which i find online has route starting with file, where as in my case i have a spring bean method which is getting called every few minutes and finally message is transformed and moved to jms as well as audit directory. </p>

<p>I am clue less on write test for this route. 
All i have currently in my test case is 
<code>Mockito.when(tradeService.searchTransaction()).thenReturn(dataWithSingleTransaction);</code></p>

<pre><code>from(""quartz2://tsTimer?cron=0/20+*+8-18+?+*+MON,TUE,WED,THU,FRI+*"")
.bean(TradeService.class)
.marshal()
.jacksonxml(true)
.to(""jms:queue:out-test"")
.to(""file:data/test/audit"")
.end();
</code></pre>
",https://stackoverflow.com/questions/54880731/unit-testing-with-apache-camel,"['apache-camel', 'spring-boot-test']",5223,True,0,2
Test Switch Case - Unit testing,"<p>I am new to unit testing and I ran into the this case.
I am using JEST and Enzyme - REACT JS</p>

<p>I am familiar calling clicks and onChange events  but not sure how to set up a test for the following:</p>

<pre><code>updateUser = (e) =&gt; {
  var tempUser = this.state.user;

  switch(e.target.id){
     case ""firstName"":
           tempUser.FirstName = e.target.value;
           break;
     case ""lastName"":
           tempUser.LastName = e.target.value;
           break;
     case ""email"":
           tempUser.Email = e.target.value;
           break;
      case ""userName"":
           tempUser.Username = e.target.value;
           break;
      default:
           break;
    }

this.setState({
    user: tempUser,
   })
}
</code></pre>

<p>So I tried to apply the same set up I have been using to test updateUser - not sure if its the correct approach.</p>

<pre><code>describe(' Test', () =&gt; {
let wrapper;

 beforeEach(() =&gt; wrapper = shallow(&lt;Component {...baseProps} /&gt;));

it('UpdateUser method', () =&gt; {
 wrapper.instance().updateUser = jest.fn();
 wrapper.setState({
   user:{
         tempUser :{
            FirstName: """",
            LastName:"""",
            Email:"""",
            Username:"""",
          },
      },
  }),
wrapper.update();
expect(wrapper.instance().updateUser).toBeDefined();
expect(wrapper.state().user).toEqual({}); 
})
</code></pre>

<p>Thanks for the help - hope to learn how to test switch cases and get this test to pass.</p>
",https://stackoverflow.com/questions/54927861/test-switch-case-unit-testing,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",10942,True,0,2
Mocking Kafka APIs for Unit Testing,"<p>I want to mock the Confluent Kafka APIs for Consumer and Producer in GO for Unit Testing, Is there any way (process/steps/library) to mock them successfully?</p>
",https://stackoverflow.com/questions/59316913/mocking-kafka-apis-for-unit-testing,"['unit-testing', 'go', 'apache-kafka', 'confluent-platform']",5613,False,7,1
Unit testing loading images/pages,"<p>I am writing unit tests for a web application using Python/Selenium and JS/jQuery. The test in question involves ensuring that a message with animated icon displays after the user submits a payment before the confirmation screen loads. </p>

<p>The payment is handled via a third-party iframe. The loading message and image do not display on a different URL -- it's the same URL as where the iframe itself is.</p>

<p>I've tried using JavaScript to stop the page load with <code>self.driver.execute_script(""return window.stop;"")</code>, but this isn't working.</p>

<p>I've also tried using Selenium to send the escape key with <code>self.driver.find_element_by_tag(""body"").send_keys(Keys.ESCAPE)</code> but this is also failing to stop the page load before the confirmation page loads.</p>

<p>I've also tried just <code>assert ""Loading Text"" in self.driver.page_source</code> without stopping the loading of the confirmation screen, but this also didn't work. </p>

<p>If I manually click the stop button, it does stop the page load. I tried using this function to simulate a click on the stop button, but no avail. A stop button never appears during the automated test -- it remains a reload button even though the page is processing a request. </p>

<pre><code>def stop_page_load():
    def click_based_on_coordinates(x,y):
        win32api.SetCursorPos((x,y))
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)

        click_based_on_coordinates(78, 50)
</code></pre>

<p>Not at all sure how to test this item. Thoughts?</p>
",https://stackoverflow.com/questions/59164842/unit-testing-loading-images-pages,"['javascript', 'python', 'selenium', 'unit-testing', 'python-unittest']",231,False,0,0
Angular Unit Testing injecting parameters,"<p>i am trying to setup unit tests using inject. But i am not sure how to set the parameters. </p>

<p>The constructor for the class being tested (auth.service.ts) is:</p>

<pre><code>constructor(private http : HttpClient, private token: TokenStorage) {}
</code></pre>

<p>Unit Test class (auth.service.spec.ts)</p>

<pre><code>import { TestBed, inject } from '@angular/core/testing';
import { AuthService } from './auth.service';
import { HttpClient, HttpHandler, HttpClientModule } from '@angular/common/http';
import { TokenStorage } from './token.storage';

describe('AuthService', () =&gt; {
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            providers: [AuthService, HttpClient, HttpHandler, HttpClientModule, TokenStorage]
        });
    });
    it('should be created', inject([AuthService], (service: AuthService) =&gt; {
        expect(service).toBeTruthy();
    }));
});
</code></pre>
",https://stackoverflow.com/questions/55871783/angular-unit-testing-injecting-parameters,"['angular', 'unit-testing', 'karma-jasmine', 'inject']",2773,True,0,1
else path not taken in unit testing,"<p>I am working on angular 6</p>

<blockquote>
  <p>I don't have any  else statement in my below code.But I am unable to cover branches due to else path not taken .What I need to do to get 100% branch coverage in this case?</p>
</blockquote>

<pre><code> getHeaderDocumentList(documents: any) {
            if (documents) {
                documents.result.docAttachment.forEach(element =&gt; {
                    this.headerdocumentdetails.push(element.DocumentUniqueID);
                });
            }
        }
</code></pre>
",https://stackoverflow.com/questions/58877215/else-path-not-taken-in-unit-testing,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-coverage']",26217,True,14,2
Unit Testing a Blazor RenderFragment element,"<p>I've started to write a method for dynamically building a RenderFragment Element. As such I'm also trying to write Unit Tests alongside the method.</p>

<p>I'm starting with a very basic element and it fails. Here's the concrete method under test:</p>

<pre><code>public RenderFragment buildFragment(string element, string elementContent, string[] attribute, string[] attributeContent)
    {
        RenderFragment content = builder =&gt; {
            builder.OpenElement(0, element);
            if (attribute != null)
            {
                for (int i = 0; attribute.Length - 1 &gt;= i; ++i)
                {
                    builder.AddAttribute(0, attribute[i], attributeContent[i]);
                }
            }
            if (!string.IsNullOrEmpty(elementContent))
            {
                builder.AddContent(0, elementContent);
            }
            builder.CloseElement();
        };

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

<p>This is my first basic test against the method using xUnit:</p>

<pre><code>public void BuildFragmentReturnsOneElement()
        {
            //Arrange
            RenderFragment fragment = builder =&gt;
            {
                builder.OpenElement(0, ""p"");
                builder.CloseElement();
            };

            //Act
            RenderFragment result = _dynamicContentHelper.buildFragment(""p"", string.Empty, null, null);

            //Assert
            Assert.Same(fragment, result);
        }
</code></pre>

<p>The error I receive is:</p>

<blockquote>
  <p>Message: Assert.Same() Failure
  Expected: RenderFragment { Method = Void b__2_0(Microsoft.AspNetCore.Blazor.RenderTree.RenderTreeBuilder), Target = &lt;>c { } }
  Actual:   RenderFragment { Method = Void b__0(Microsoft.AspNetCore.Blazor.RenderTree.RenderTreeBuilder), Target = &lt;>c__DisplayClass0_0 { attribute = null, attributeContent = null, element = ""p"", elementContent = """" } }</p>
</blockquote>

<p>I don't understand why <strong>Target</strong> on my <strong>fragment</strong> object is different from the <strong>Target</strong> on <strong>result</strong>.</p>
",https://stackoverflow.com/questions/54307878/unit-testing-a-blazor-renderfragment-element,"['c#', 'xunit', 'blazor']",2553,True,6,2
Unit testing with EF Core and in memory database,"<p>I am using ASP.NET Core 2.2, EF Core and MOQ. As you can see in the following code,  I have two tests, and running both together, with both database name ""MovieListDatabase"" I got an error in one of the tests with this message:</p>

<pre><code>Message: System.ArgumentException : An item with the same key has already 
been added. Key: 1
</code></pre>

<p>If I run each one separately they both pass.</p>

<p>And also, having a different database name in both tests, like ""MovieListDatabase1"" and ""MovieListDatabase2"" and running both together it pass again.</p>

<p>I have two questions:
Why does this happen? and how can I refactor my code to re-use the in-memory database in both tests and make my test to look a bit cleaner?</p>

<pre><code> public class MovieRepositoryTest
{
    [Fact]
    public void GetAll_WhenCalled_ReturnsAllItems()
    {

        var options = new DbContextOptionsBuilder&lt;MovieDbContext&gt;()
            .UseInMemoryDatabase(databaseName: ""MovieListDatabase"")
            .Options;

        // Insert seed data into the database using one instance of the context
        using (var context = new MovieDbContext(options))
        {
            context.Movies.Add(new Movie { Id = 1, Title = ""Movie 1"", YearOfRelease = 2018, Genre = ""Action"" });
            context.Movies.Add(new Movie { Id = 2, Title = ""Movie 2"", YearOfRelease = 2018, Genre = ""Action"" });
            context.Movies.Add(new Movie { Id = 3, Title = ""Movie 3"", YearOfRelease = 2019, Genre = ""Action"" });
            context.SaveChanges();
        }

        // Use a clean instance of the context to run the test
        using (var context = new MovieDbContext(options))
        {
            var sut = new MovieRepository(context);
            //Act
            var movies = sut.GetAll();

            //Assert
            Assert.Equal(3, movies.Count());
        }
    }

    [Fact]
    public void Search_ValidTitlePassed_ReturnsOneMovie()
    {
        var filters = new MovieFilters { Title = ""Movie 1"", YearOfRelease = 2018, Genre = ""Action"" };

        var options = new DbContextOptionsBuilder&lt;MovieDbContext&gt;()
            .UseInMemoryDatabase(databaseName: ""MovieListDatabase"")
            .Options;

        // Insert seed data into the database using one instance of the context
        using (var context = new MovieDbContext(options))
        {
            context.Movies.Add(new Movie { Id = 1, Title = ""Movie 1"", YearOfRelease = 2018, Genre = ""Action"" });
            context.Movies.Add(new Movie { Id = 2, Title = ""Movie 2"", YearOfRelease = 2018, Genre = ""Action"" });
            context.Movies.Add(new Movie { Id = 3, Title = ""Movie 3"", YearOfRelease = 2019, Genre = ""Action"" });
            context.SaveChanges();
        }

        // Use a clean instance of the context to run the test
        using (var context = new MovieDbContext(options))
        {
            var sut = new MovieRepository(context);

            //Act
            //var movies = _sut.Search(_filters);
            var movies = sut.Search(filters);

            //Assert
            Assert.Single(movies);
        }
    }
}
</code></pre>

<p>And this is the repository class</p>

<pre><code> public class MovieRepository: IMovieRepository
{
    private readonly MovieDbContext _moviesDbContext;
    public MovieRepository(MovieDbContext moviesDbContext)
    {
        _moviesDbContext = moviesDbContext;
    }

    public IEnumerable&lt;Movie&gt; GetAll()
    {
        return _moviesDbContext.Movies;
    }

    public IEnumerable&lt;Movie&gt; Search(MovieFilters filters)
    {
        var title = filters.Title.ToLower();
        var genre = filters.Genre.ToLower();
        return _moviesDbContext.Movies.Where( p =&gt; (p.Title.Trim().ToLower().Contains(title) | string.IsNullOrWhiteSpace(p.Title))
                                                   &amp; (p.Genre.Trim().ToLower().Contains(genre) | string.IsNullOrWhiteSpace(p.Genre))
                                                   &amp; (p.YearOfRelease == filters.YearOfRelease | filters.YearOfRelease == null)
                                             );
    }
}
</code></pre>

<p>Thanks</p>
",https://stackoverflow.com/questions/54264787/unit-testing-with-ef-core-and-in-memory-database,"['c#', 'entity-framework', 'unit-testing', '.net-core', 'moq']",53275,True,28,7
Unit testing for URLSessionDelegate method - Swift,"<p>I have a custom delegate class called <strong><code>CertificatePinningDelegate</code></strong> which conforms to <strong><code>URLSessionDelegate</code></strong>. I'm using the delegate method </p>

<pre><code>urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -&gt; Void) 
</code></pre>

<p>to authenticate with the server. Now I want to write a unit test for this.</p>

<p>I've been trying to manually call the delegate method to pass a custom <strong><code>URLAuthenticationChallenge</code></strong> object, which seems impossible. Does anyone know any alternative/better option for this?</p>
",https://stackoverflow.com/questions/58850154/unit-testing-for-urlsessiondelegate-method-swift,"['swift', 'xcode', 'unit-testing', 'urlsession', 'urlauthenticationchallenges']",178,False,6,0
Unit testing RxJava with a Completable.timer,"<pre><code>Android Studio 3.5.2
RxJava2
Kotlin 1.3.50
</code></pre>

<p>I have the following class that acts like a timer.</p>

<pre><code>class DelayTimerImp(private val scheduler: IScheduler)
    : DelayTimer {

    override fun createTimeout(delay: Long, timeUnites: TimeUnit): Completable {
        return Completable.timer(delay, TimeUnit.SECONDS, scheduler.main())
    }
}
</code></pre>

<p>And I am using it in a method like this:</p>

<pre><code>private fun startTimeoutRequest(delay: Long) {
    compositeSubscription.add(delayTimer.createTimeout(delay, TimeUnit.SECONDS)
            .subscribeOn(schedulers.io())
            .subscribe(::timeoutHasExceeded, ::timeoutError))
}
</code></pre>

<p>And in my test class and it uses the <code>TestScheduler</code> to return the <code>io</code> thread. I am mocking the delayTimer. Even though I <code>thenReturn(Completable.complete())</code> the methods in the <code>timeOutHasExceeded</code> never go into them. I am thinking that if <code>Completable</code> has completed in go into that method.</p>

<pre><code>@Test
fun `should reload and show loading state`() {
    // Arrange
    whenever(delayTimer.createTimeout(10, TimeUnit.SECONDS))
            .thenReturn(Completable.complete())

    // Act
    vipInformationPresenterImp.tryAgainTapped()

    // Assert methods in the timeOutHasExceeded
}
</code></pre>

<p>Also If I change the following to this by changing the delay to <code>1</code>:</p>

<pre><code>whenever(delayTimer.createTimeout(1, TimeUnit.SECONDS))
                .thenReturn(Completable.complete())
</code></pre>

<p>I will get a <code>crash</code> on the following line:</p>

<pre><code>.subscribeOn(schedulers.io())
</code></pre>

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

<p>Many thanks in advance</p>
",https://stackoverflow.com/questions/58804251/unit-testing-rxjava-with-a-completable-timer,"['android', 'kotlin', 'rx-java2']",2043,True,5,1
Unit Testing Firebase Database with Android,"<p>I have created an app that allows users to create a transaction. When this transaction is created it is added to the database (Firebase Realtime Database). Once a transaction is created, a series of approvals have to be made before the transaction is carried out.</p>

<p>In order to approve a transaction, a user must click on the transaction on the transaction requests page which displays the desired transactions. Once a user clicks on this transaction the user is shown the relevant dialog box. When a user clicks the ""approve"" button on this dialog box, the value of the corresponding ""flag"" in the database is set to true.</p>

<p>I am trying to write a test using Mockito to test that this flag is indeed being set to true but I am struggling to do so. I have watched multiple videos on unit testing in android studio on youtube and have read through all the posts on here that involve firebase unit testing with android studio but I have still been unable to carry out my desired test.</p>

<p>As my research has lead me to a dead end I was hoping someone on here could either send me in the right direction to some sample code that I have not yet seen, or better yet help me write my desired test.</p>

<p>The code that I am trying to test is within this class:</p>

<pre><code>public class Request extends AppCompatActivity {

private static final String TAG = ""Request"";

//Firebase Stuff
FirebaseDatabase database;
DatabaseReference start, ref;
DatabaseReference user;

RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;

Dialog custDialog;

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

    final String passedEmail = getIntent().getStringExtra(""Email"");

    //Init Firebase
    database = FirebaseDatabase.getInstance();
    start = database.getReference(""Transaction"");
    ref = database.getReference(""User"");

    //Load Menu
    recycler_menu = findViewById(R.id.recycler_menu);
    recycler_menu.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recycler_menu.setLayoutManager(layoutManager);

    loadMenu();
}

private void loadMenu() {
    FirebaseRecyclerAdapter&lt;Transaction, TransRequestHolder&gt; adapter = new FirebaseRecyclerAdapter&lt;Transaction, TransRequestHolder&gt;(Transaction.class, R.layout.trans_item, TransRequestHolder.class, start) {
        @Override
        protected void populateViewHolder(TransRequestHolder viewHolder, final Transaction model, int position) {
            final String passedUserType= getIntent().getStringExtra(""userType"");
            final String passedEmail= getIntent().getStringExtra(""Email"");
            final String receiver = model.getReceiver().replace('.', ' ');
            final String shopA = model.getShopA().replace('.', ' ');

            //custB
            if(passedEmail.equalsIgnoreCase(model.getReceiver()) &amp;&amp; model.getCustflag() == false) {
                viewHolder.txtTransactionA.setText(model.getAmount());
                viewHolder.txtTransactionC.setText(model.getCurrency());
                viewHolder.txtTransactionR.setText(model.getReceiver());
                final Transaction clickItem = model;
                viewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(android.view.View view, int position, boolean isLongClick) {
                        Toast.makeText(Request.this, ""Receiving: "" + shopA, Toast.LENGTH_SHORT).show();
                        final String key = model.getKey();
                        custDialog = new Dialog(Request.this);
                        custDialog.setContentView(R.layout.dialog_template);
                        final EditText Write = custDialog.findViewById((R.id.write));
                        Button Approve = custDialog.findViewById(R.id.approve);

                        Write.setEnabled(true);
                        Approve.setEnabled(true);

                        Approve.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String newShopB = Write.getText().toString().replace(""."", "" "");
                                start.child(key).child(""custflag"").setValue(true);
                                start.child(key).child(""shopB"").setValue(newShopB);
                                Toast.makeText(Request.this, ""CustB Approval"", Toast.LENGTH_SHORT).show();
                                custDialog.cancel();
                            }
                        });
                        custDialog.show();
                    }
                });
            }
            //shopA
            else if (passedEmail.equalsIgnoreCase(model.getShopA()) &amp;&amp; (model.getCustflag() == true &amp;&amp; model.getShopAflag() == false)) {
                viewHolder.txtTransactionA.setText(model.getAmount());
                viewHolder.txtTransactionC.setText(model.getCurrency());
                viewHolder.txtTransactionR.setText(model.getReceiver());
                final Transaction clickItem = model;
                viewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(android.view.View view, int position, boolean isLongClick) {
                        Toast.makeText(Request.this, ""Receiving: "" + shopA, Toast.LENGTH_SHORT).show();
                        final String key = model.getKey();
                        //Dialog option number one
                        customDialog(""Transaction Approval"", ""Are you sure you want to approve this transaction?"", ""cancel"", ""okMethod2"", passedEmail, key);
                    }
                });
            }
            //shopB
            else if (passedEmail.equalsIgnoreCase(model.getShopB()) &amp;&amp; (model.getShopAflag() == true &amp;&amp; model.getShopBflag() == false)) {
                viewHolder.txtTransactionA.setText(model.getAmount());
                viewHolder.txtTransactionC.setText(model.getCurrency());
                viewHolder.txtTransactionR.setText(model.getReceiver());
                final Transaction clickItem = model;
                viewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(android.view.View view, int position, boolean isLongClick) {
                        Toast.makeText(Request.this, ""Receiving: "" + shopA, Toast.LENGTH_SHORT).show();
                        final String key = model.getKey();
                        //Dialog option number one
                        customDialog(""Transaction Approval"", ""Are you sure you want to approve this transaction?"", ""cancel"", ""okMethod3"", passedEmail, key);
                    }
                });
            }
            else {
                viewHolder.itemView.setVisibility(View.GONE);
            }
        }
    };
    recycler_menu.setAdapter(adapter);
}
</code></pre>

<p>}</p>

<p>I hope I have provided enough information. I would appreciate any help anyone can give me.</p>
",https://stackoverflow.com/questions/55265005/unit-testing-firebase-database-with-android,"['java', 'android', 'firebase', 'mockito']",976,False,4,0
Unit testing on browser (Typescript + Webpack),"<p>I want to add unit test to <a href=""https://github.com/s1n7ax/open-unicode-converter"" rel=""nofollow noreferrer"">this</a> project. It's a basic webpack + typescript project that will be used by another web application. Unit test should run on browser.</p>

<p>I tried <code>mocha</code> but just <code>import 'mocha'</code> throws compile error.
(I have test file in <code>project_folder/test/test.ts</code> which is the entry for webpack.)</p>

<pre><code>WARNING in ./node_modules/mocha/lib/mocha.js 219:20-37
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts

WARNING in ./node_modules/mocha/lib/mocha.js 227:24-70
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts

WARNING in ./node_modules/mocha/lib/mocha.js 277:24-35
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts

WARNING in ./node_modules/mocha/lib/mocha.js 327:35-48
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts

WARNING in ./node_modules/mocha/lib/mocha.js 342:23-44
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts

ERROR in ./node_modules/mocha/lib/browser/growl.js
Module not found: Error: Can't resolve '../../package' in 'C:\Users\s1n7ax\Documents\GitHub\open-unicode-converter\node_modules\mocha\lib\browser'
 @ ./node_modules/mocha/lib/browser/growl.js 127:13-37
 @ ./node_modules/mocha/lib/mocha.js
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts

ERROR in ./node_modules/mkdirp/index.js
Module not found: Error: Can't resolve 'fs' in 'C:\Users\s1n7ax\Documents\GitHub\open-unicode-converter\node_modules\mkdirp'
 @ ./node_modules/mkdirp/index.js 2:9-22
 @ ./node_modules/mocha/lib/reporters/xunit.js
 @ ./node_modules/mocha/lib/reporters/index.js
 @ ./node_modules/mocha/lib/mocha.js
 @ ./node_modules/mocha/browser-entry.js
 @ ./test/test.ts
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! open-unicode-converter@1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the open-unicode-converter@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\s1n7ax\AppData\Roaming\npm-cache\_logs\2019-03-02T20_59_10_221Z-debug.log
</code></pre>

<p>If test is written without import statement, there are no compile errors, but at runtime it throws an error because method <code>describe</code> is not defined.</p>

<p>It's important the test to be a typescript file, because typescript classes has to be imported. Is there a library that can be used with typescript + webpack and runs on browser?</p>

<h3>test/test.ts</h3>

<pre><code>import 'mocha'
describe('sample', () =&gt; {
    it('should return something', () =&gt; {
    })
});
</code></pre>

<h3>webpack.config.js</h3>

<pre><code>const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');


let distPath = path.resolve(__dirname, 'dist');
let srcPath = path.resolve(__dirname, 'src');
let testPath = path.resolve(__dirname, 'test');

module.exports = {
    mode: 'development',
    devtool: 'inline-source-map',
    entry: ""./test/index.test.ts"",
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    plugins: [
        // this copy index.html from test/index.html to dist
        new CopyWebpackPlugin([
            {from: path.resolve(__dirname, 'test'), to: distPath, ignore: ['*.ts', '*.tsx', '*.js']}
        ]),
    ],
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    output: {
        filename: '[name].js',
        path: distPath
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        compress: true,
        port: 9000
    }
};
</code></pre>

<h3>package.json</h3>

<pre><code>""scripts"": {
    ""build"": ""webpack"",
    ""watch"": ""webpack --watch"",
    ""test:browser"": ""npm run build &amp;&amp; start http://localhost:9000 &amp;&amp; webpack-dev-server""
}
</code></pre>
",https://stackoverflow.com/questions/54963128/unit-testing-on-browser-typescript-webpack,"['typescript', 'unit-testing', 'webpack']",1679,True,4,1
Unit testing function with Firestore implementation,"<p>Can someone guide/help me how to write unit test for the getProfileDetails() function:</p>

<p>I have gone through various answers on Stackoverflow but unable to solve this</p>

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

<pre><code>    class EditProfileViewModel(private val mFireStore: FirebaseFirestore,
                               private val mStorageReference: StorageReference) {

    fun getProfileDetails() {
    mFireStore.collection(Constants.USER).document(""document_id"")
                .get()
                .addOnSuccessListener {documentSnapshot -&gt;
    if (documentSnapshot != null){
    val userProfile = documentSnapshot.toObject(UserProfile::class.java)
    Log.d(""TAG"",""UserProfile ${userProfile.toString()}"")
    }
    }.addOnFailureListener { ex -&gt;

                    Log.d(""TAG"",ex.message.toString())
                }
    }

    }
</code></pre>

<p>I am able to mock firestore instance using mockito, but not able to figure a way to test code on onSuccess and onFailure.
    Let me know if any other detail is required.</p>
",https://stackoverflow.com/questions/57874648/unit-testing-function-with-firestore-implementation,"['android', 'kotlin', 'google-cloud-firestore']",216,False,3,0
DynamoDB and Unit Testing .NET core,"<p>We are implementing DynamoDB data store. For our unit tests we have got that covered for Web.API, services, repository layers. However, I have not found any mocking frameworks/unit test for DynamoDB for .NET Core, only to implement the local DynamoDB (<a href=""https://aws.amazon.com/blogs/aws/amazon-dynamodb-libraries-mappers-and-mock-implementations-galore/"" rel=""nofollow noreferrer"">https://aws.amazon.com/blogs/aws/amazon-dynamodb-libraries-mappers-and-mock-implementations-galore/</a>) Amazon indicates that it's best to run the local instance (Dynamo Local), however, this is not ideal for us, since we have Azure dev-ops pipelines in place. This causes other issues,like deleting tables for each test run, making sure the local db instance is running etc.</p>

<p>I was thinking of extending the DynamoDBclient, DynamoContext etc and then use these to simulate, however, this seems like a lot of work and I am not sure if it is worthwhile. Can anyone suggest an easier alternative or have come across a framework, or implemented a good unit testing framework for DynamoDB for .NET Core. We really don't want to go down the path to use the local DynamoDB on our build server. </p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/55463654/dynamodb-and-unit-testing-net-core,"['unit-testing', '.net-core', 'mocking', 'amazon-dynamodb']",3060,False,3,0
Unit Testing MassTransit Consumer With XUnit,"<p>My team is just getting started with using MassTransit and we are trying to figure out how unit testing IConsumer implementations work. The MassTransit documentation is incomplete and all of the examples I have found so far use NUnit. We are trying to use XUnit with Moq to do our unit testing. </p>

<p>I know that we need to set up one instance of the MassTransit test harness, which in NUnit is done with a OneTimeSetup and to replicate that we should use IClassFixture in XUnit. I'm struggling with getting that to work with the test harness, though.</p>

<p>I have seen Chris Patterson's ConsumerTest_Specs.cs example on the MassTransit GitHub, but I'm having a hard time translating it to work in XUnit and Moq.
<a href=""https://github.com/MassTransit/MassTransit/blob/master/src/MassTransit.Tests/Testing/ConsumerTest_Specs.cs"" rel=""nofollow noreferrer"">https://github.com/MassTransit/MassTransit/blob/master/src/MassTransit.Tests/Testing/ConsumerTest_Specs.cs</a></p>

<p>I'm trying to test a very simple consumer to start with. All it does is receive the message and then make a call to a repository. I want to write an XUnit test that mocks the repository and verifies that the repository method was called. </p>

<p>Does anyone have any examples of how to do something like this?</p>

<pre><code>public class NewVMRequestRejectedConsumer : IConsumer&lt;INewVMRequestRejected&gt;
{
    private readonly INewVMRequestRepository _newVMRequestRepository;

    public NewVMRequestRejectedConsumer(INewVMRequestRepository newVMRequestRepository)
    {
        _newVMRequestRepository = newVMRequestRepository;
    }

    public Task Consume(ConsumeContext&lt;INewVMRequestRejected&gt; context)
    {
        _newVMRequestRepository.AddReasonForRejection(context.Message.RequestId, context.Message.Reason);
        return Task.CompletedTask;
    }
}
</code></pre>
",https://stackoverflow.com/questions/55642001/unit-testing-masstransit-consumer-with-xunit,"['c#', '.net', 'moq', 'xunit', 'masstransit']",1690,True,3,1
Feign Unit Testing Not found response,"<p>I'm trying to implement a unit test involving a FeignClient call which should return a 404 Not Found.</p>

<p>As Feign is trowing a FeignException for 404, what is the proper way to implement this test case?</p>

<p>I'm trying something like this...</p>

<pre><code>when(mockedApiClient.userDataDelete(anyString()))
                .thenThrow( ... );
</code></pre>

<p>What should I throw?</p>
",https://stackoverflow.com/questions/58727847/feign-unit-testing-not-found-response,"['java', 'spring-cloud-feign']",18415,True,3,6
Unit testing private variables in Swift,"<p>I have a hard time to grasp how to implement unit tests in a class where all my fields are private.</p>

<p>The class is calculating a user's position with BLE and CoreLocation - not that important. I have a protocol, which when a new location is found I'm calling it and all the classes which conform to that protocol will receive a room id and room name. So, what that means is that literally all the fields in my class are private, because yeah, there's no reason any outside class should access them right? But that also means I can literally test nothing in that class, even though there are quite a few functions which I would like to test. I mean, I could just make the variables internal instead of private, but it just seems wrong to do that just to unit test. I've heard about dependency injection, but it just seems like so much effort.</p>

<p>For example I have this function:</p>

<pre><code>
private var beacons: [AppBeacon] = []
private var serverBeacons:[Beacon] = []

private func addBeacons(serverBeacons: [Beacon]){
        for beacon in serverBeacons {
            let beacon = AppBeacon(id: beacon.id, uuid: beacon.uuid, building: beacon.building, name: beacon.name)
            beacons.append(beacon)
       }
   }
</code></pre>

<p>there's no way I can test whether the beacons array was actually filled up as I wanted to or not for example. The public features of my class are basically a function called startLocating and the result which is the room id and name and I know in black box testing which unit testing imitates (right?) I should not care about the intermediate steps, but honestly, with this much functionality should I just say, doesn't matter? And assume i did populate the beacons with some rssi values of my choice, the actual location algorithm is executed on a node.js server, so I honestly don't know what to test client side? </p>

<p>It's classic MVC and there's no way I can change it architecture until the deadline that I have, so I don't know what's the best way to go from here? Just don't test the functionalities? Make the fields internal instead of private? We do testing of the algorithm itself server side, so testing whether the the room id is the expected room id, is already tested.</p>

<p>I read on another post the following:</p>

<p><em>""Unit testing by definition is black box testing, which means you don't care about the internals of the unit you test. You are mainly interested to see what's the unit output based on the inputs you give it in the unit test.
Now, by outputs we can assert on several things:</em></p>

<ul>
<li>the result of a method</li>
<li>the state of the object after acting on it,</li>
<li>the interaction with the dependencies the object has</li>
</ul>

<p><em>In all cases, we are interested only about the public interface, since that's the one that communicates with the rest of the world.
Private stuff don't need to have unit tests simply because any private item is indirectly used by a public one. The trick is to write enough tests that exercise the public members so that the private ones are fully covered.</em></p>

<p><em>Also, one important thing to keep in mind is that unit testing should validate the unit specifications, and not it's implementation. Validating implementation details adds a tight coupling between the unit testing code and the tested code, which has a big disadvantage: if the tested implementation detail changes, then it's likely that the unit test will need to be changed also, and this decreases the benefit having unit test for that piece of code.""</em></p>

<p>And from that I essentially understand it as that I should just not unit test this?</p>
",https://stackoverflow.com/questions/56058681/unit-testing-private-variables-in-swift,"['ios', 'swift', 'unit-testing', 'private']",1397,True,3,2
Unit Testing with Go-Chi/Chi,"<p>I am trying to write unit tests for my rest endpoints using Go-Chi as my mux.</p>

<p>Previously I was using gorilla/mux but moved to Chi because it is easier to maintain as my application grows.</p>

<p>With Gorilla/mux, I was able to use ""ServeHTTP"" to send a test request but using go-chi/chi it does not seem to do the same thing.</p>

<pre class=""lang-golang prettyprint-override""><code>var writer *httptest.ResponseRecorder
var r = chi.Mux{}

func TestMain(m *testing.M) {
    setUp()
    code := m.Run()
    os.Exit(code)
}

func setUp() {
    d, _ := database.ConnectToDB(database.TESTDBNAME)
    writer = httptest.NewRecorder()
    r := chi.NewMux()
    r.Route(""/companies"", func(r chi.Router) {
        r.Get(""/"", GetCompanies(d))
        r.Get(""/{id}"", GetCompany(d))
        r.Post(""/"", PostCompany(d))
        r.Put(""/{id}"", PutCompany(d))
        r.Delete(""/{id}"", DeleteCompany(d))
    })
}

func TestPostCompany(t *testing.T) {
    tables := []struct {
        company   model.Company
        result int
    }{
        {model.Company{Name:""Test""}, 200},
    }

    for _, table := range tables {
        company, err := json.Marshal(table.company)
        if err != nil {
            t.Errorf(""JSON Error"")
        }
        companyJson := strings.NewReader(string(company))
        request, err := http.NewRequest(""POST"", ""/companies"", companyJson)
        if err != nil {
            t.Error(err)
        }
        r.ServeHTTP(writer, request)
        if writer.Code != table.result {
        t.Error(writer.Body)
        }
    }
}
</code></pre>

<p>Right now the test is showing a 404 error but I would like it to give a 200 error. This request works fine while running my application and testing manually.</p>

<p>I believe the issue has something to do with ""ServeHTTP"". Maybe it works differently with chi. Does anyone know how to get this test to run successfully?</p>
",https://stackoverflow.com/questions/56711561/unit-testing-with-go-chi-chi,"['unit-testing', 'go', 'go-chi']",2199,False,3,0
Unit Testing React HashRouter with Jest,"<p>I am desperately trying to Unit Test my HashRouter routes but cannot get my head around how. I managed to get a solution using Enzyme but am forced to use ReactTestingLibrary by tech lead.</p>

<p>Can anyone help out pointing me in the right direction?</p>

<p><strong>App Component</strong></p>

<pre><code>import React, { Component } from 'react';
import { HashRouter } from 'react-router-dom'
import { create } from 'jss';
import { StylesProvider, jssPreset } from '@material-ui/styles';

import './App.css';
import Routes from './Routes';

class App extends Component {

  render() {
    return (
      &lt;HashRouter&gt;
        &lt;Routes /&gt;                                      
      &lt;/HashRouter&gt;
    );
  }
}

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

<p><strong>Routes Component</strong></p>

<pre><code>import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import { withRouter } from 'react-router';

import NetworksList from './pages/NetworksList';
import DealsList from './pages/DealsList';

class Routes extends Component {

  render() {
    return (
      &lt;div&gt;
        &lt;Route path=""/networks"" component={NetworksList} /&gt;
        &lt;Route path=""/deals"" component={DealsList} /&gt;
      &lt;/div&gt;
    );
  }
}

export default withRouter(Routes);
</code></pre>

<p><strong>App Component Test</strong></p>

<pre><code>import React from 'react';
import App from './App';
import { render } from '@testing-library/react';
import { createMemoryHistory } from 'history'
import { Router } from 'react-router-dom'

import Routes from './Routes';


beforeEach(() =&gt; {
  jest.resetAllMocks();
});


it.only('should render networks list page at #/networks', () =&gt; {

  const history = createMemoryHistory()
  history.push('networks');

  const { container, getByText } = render(
    &lt;Router history={history}&gt;
      &lt;Routes /&gt;
    &lt;/Router&gt;
  )

});
</code></pre>
",https://stackoverflow.com/questions/58218371/unit-testing-react-hashrouter-with-jest,"['reactjs', 'unit-testing', 'jestjs']",2257,False,3,1
Unit testing LitElement events in firstUpdated,"<p>I have a simple mixin:</p>

<pre><code>export const mixin = superclass =&gt; class extends superclass {
  firstUpdated() {
    super.firstUpdated();
    this.dispatchEvent(new CustomEvent('my-event', {
      bubbles: true,
      composed: true,
      detail: {
        myEventTriggered: true,
      },
    }));
  }
};
</code></pre>

<p>I want to test if <code>my-event</code> is fired. This is my test:</p>

<pre><code>it('dispatches the custom event', async () =&gt; {
  const tag = class extends mixin(LitElement) {};
  const el = await fixture(`&lt;${tag}&gt;&lt;/${tag}&gt;`);
  setTimeout(() =&gt; el.firstUpdated());
  const { detail } = await oneEvent(el, 'my-event');
  expect(detail.myEventTriggered).to.be.true;
});
</code></pre>

<p>This works as expected but I'm not sure about the <code>setTimeout(() =&gt; el.firstUpdated());</code> line. Shouldn't <code>firstUpdated</code> be called after <code>await fixture</code>? I'm just following <a href=""https://open-wc.org/testing/testing-helpers.html#testing-events"" rel=""nofollow noreferrer"">open-wc's testing guide</a>.</p>
",https://stackoverflow.com/questions/55275282/unit-testing-litelement-events-in-firstupdated,"['unit-testing', 'web-component', 'lit-element']",2171,True,3,1
Unit Testing Jest in Reactjs Component state,"<p>Hello :) I'm starting to learn <strong>Unit Testing</strong> using <strong>JEST &amp; Enzyme</strong></p>

<p>on my version (already done) of ""Color Guessing Game"" using with <strong>Reactjs</strong>, 
but when I started to test my Square Component I can't even test my color state value and my color state when clicked (clickSquare function)...</p>

<p>and I can't find much resources about it, can you see what's wrong, and how can I test my Square Component?</p>

<p><strong>Square.js Component:</strong></p>

<pre><code>import React, { Component } from 'react';



class Square extends Component {




constructor(props) {
    super(props);
    this.state = {
      color: undefined
    }
    this.clickSquare = this.clickSquare.bind(this);
  }

  componentDidMount() {
    if (this.props.color) {
      this.setState({
        color: this.props.color
      })
    }
  };

  componentWillReceiveProps(props) {
    //results in the parent component to send updated props,, 
    //whenever the propositions are updated in the parent, runs this
    //to update the son as well
    this.setState({
      color: props.color
    })

  }

  clickSquare() {
    if (this.state.color === this.props.correctColor) {
      this.props.gameWon(true);
      console.log('correct', this.state.color)

    } else {
      this.setState({
        color: 'transparent'
      })
      //    this.props.gameWon(false);
      console.log('wrong')

    }
  };

  render() {

    return (
      &lt;div className='square square__elem'
        style={{ backgroundColor: this.state.color }}
        onClick={this.clickSquare}&gt;
      &lt;/div&gt;
    );
  }
};

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

<p><strong>Square.test.js Testing:</strong></p>

<pre><code>import React from 'react';

import Square from '../components/Square/Square';

import { shallow, mount } from 'enzyme';


describe('Square component', () =&gt; {

    let wrapper;
    beforeEach(() =&gt; wrapper = shallow(
        &lt;Square
            color={undefined}
            clickSquare={jest.fn()}
        /&gt;
    ));


    it('should render correctly', () =&gt; expect(wrapper).toMatchSnapshot());

    it('should render a &lt;div /&gt;', () =&gt; {
        expect(wrapper.find('div.square.square__elem').length).toEqual(1);
    });

    it('should render the value of color', () =&gt; {
        wrapper.setProps({ color: undefined});
        expect(wrapper.state()).toEqual('transparent');
      });

});
</code></pre>

<blockquote>
  <p>Expected value to equal:
        ""transparent""
      Received:
        {""color"": undefined}</p>

<pre><code>Difference:

  Comparing two different types of values. Expected string but received object.
</code></pre>
</blockquote>
",https://stackoverflow.com/questions/54892546/unit-testing-jest-in-reactjs-component-state,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",54008,True,10,1
Unit testing DateTime controller using NUnit,"<p>I am creating a React / .NET Core project and one of the pages displays the current date and time. My controller class is as follows:</p>

<pre><code>namespace TestingReactDotNet.Controllers {

    [Route (""api/[controller]"")]
    public class DayTodayController : Controller {

        [HttpGet, Route (""GetDate"")]
        public  string GetDate () {

            var info = $""Today is {DateTime.Now.ToString(""dddd, dd MMMM yyyy"")} and the time is {DateTime.Now.ToString(""hh:mm tt"")}"";
            return info;

        }
    }
}
</code></pre>

<p>I am trying to unit test this and mock the date and time but am struggling to do this (I have looked at other Stack Overflow questions and Googled but I am still having trouble). I originally wanted to use <code>Moq</code> but it seems that this may not be possible? </p>

<p>Here is what I have so far for my test:</p>

<pre><code>namespace TestingReactDotNetTests
{
    public class DayTodayTests
    {
        [Test]
        public void ReturnsDateAndTime()
        {
            var controller = new DayTodayController();
            string result = controller.GetDate();
            string expected = ""Today is Tuesday 27 August 2019 and the time is 10:00"";
            Assert.AreEqual(expected, result); 


        }
    }
}
</code></pre>

<p>My question is - how can I set the date and time so that when <code>DateTime.Now</code> is called in the string, it isn't the current date and time? </p>
",https://stackoverflow.com/questions/57672373/unit-testing-datetime-controller-using-nunit,"['c#', 'unit-testing', 'asp.net-core', 'nunit', 'moq']",588,True,3,1
Unit testing for exit() in C,"<p>I'm using the CUnit framework for the way it displays the testing results. (I'm a programming &amp; S.O. newbie so step by step answers really appreciated). </p>

<p>Is there any way I can use the same CUnit framework for when I'm testing for functions that I expect to exit()? It doesnt seem so to me, but I'm keen to ask anyway - it would display the pass/fail result along with my other CUnit tests so its ideal.</p>

<p>If not, I've been looking at other noob-friendly solutions (such as <a href=""https://stackoverflow.com/questions/6904769/c-unit-testing-returning-from-a-stubbed-graceful-exit-routine"">this SO post</a>), but I cannot use GOTO/setjmp/longjmp. The solution also needs to be portable.</p>

<p>I'm using Mac &amp; gcc command line to run this code.</p>

<p><strong>EDIT</strong>
One of the suggested solutions is to use C Pre-Processor (CPP) Directive /<a href=""https://locklessinc.com/articles/mocking/"" rel=""nofollow noreferrer"">""mocking""</a>, which looks ideal? I have used the below code in my test.c file:</p>

<pre><code>#define ERROR(PHRASE) {fprintf(stderr,""Fatal Error %s occurred in %s, line %d\n"",PHRASE, FILE, LINE); exit(2);} 
#ifdef ERROR(PHRASE)
#define ERROR(PHRASE) {printf(""In test phase"");} 
#endif 
#ifndef ERROR(PHRASE #define ERROR(PHRASE) {printf(""Not In test phase"");} 
#endif
</code></pre>

<p>Here is the error message that the terminal gives me:</p>

<pre><code>test.c:30:9: warning: 'ERROR' macro redefined [-Wmacro-redefined]
#define ERROR(PHRASE) {printf(""In test phase"");}
        ^
test.c:26:9: note: previous definition is here
#define ERROR(PHRASE) {fprintf(stderr,""Fatal Error %s occured in %s, lin...
        ^
test.c:32:14: warning: extra tokens at end of #ifndef directive
      [-Wextra-tokens]
#ifndef ERROR(PHRASE) {printf(""Not In test phase"");}
</code></pre>

<p>Removing the (PHRASE) still gives the same errors.</p>

<p><strong>EDIT</strong>
If helpful for anyone else, mocking using the #ifdef was the easiest way to solve this issue in the end. <a href=""https://gcc.gnu.org/onlinedocs/cpp/Ifdef.html"" rel=""nofollow noreferrer"">This website</a> was helpful too.</p>
",https://stackoverflow.com/questions/54228652/unit-testing-for-exit-in-c,"['c', 'exit', 'cunit']",1524,True,3,3
Fragment Unit Testing: launchFragment throws ClassCastException,"<p>I'm trying to call methods within my Fragment class in my unit test but I keep getting the error <code>java.lang.ClassCastException: androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity cannot be cast to com.nu.rms.inspections.ui.activity.InspectionActivity</code></p>

<p>I'm following Google's <a href=""https://developer.android.com/training/basics/fragments/testing"" rel=""nofollow noreferrer"">docs</a>. I'm confused why the empty fragment activity is having a cast attempted to become my InspectionActivity (the parent activity the fragment resides in), perhaps this is expected?</p>

<p>What can I do to alleviate the CastClassException and use my fragment's methods within my unit test? (<a href=""https://stackoverflow.com/questions/56237797/espresso-test-fail"">related question that doesn't solve my issue</a>)</p>

<p><strong>Test</strong></p>

<pre><code>@RunWith(AndroidJUnit4::class)
class ExampleUnitTest {
    @Test
    fun `inspection failure point to location mapping is correct`() {
        val scenario = launchFragment&lt;ContentFragment&gt;()
        scenario.onFragment { fragment -&gt;
            //TODO: test logic
        }
    }
...
}
</code></pre>

<p><strong>Fragment Class</strong></p>

<pre><code>import androidx.fragment.app.Fragment
...
class ContentFragment : Fragment() {...}
</code></pre>

<p><strong>Stack Trace</strong></p>

<pre><code>java.lang.ClassCastException: androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity cannot be cast to com.nu.rms.inspections.ui.activity.InspectionActivity
    at com.nu.rms.inspections.ui.fragment.ContentFragment.clearRFIDCache(ContentFragment.kt:565)
    at com.nu.rms.inspections.ui.fragment.ContentFragment.showStep1(ContentFragment.kt:222)
    at com.nu.rms.inspections.ui.fragment.ContentFragment.access$showStep1(ContentFragment.kt:37)
    at com.nu.rms.inspections.ui.fragment.ContentFragment$onViewCreated$1.onChanged(ContentFragment.kt:77)
    at com.nu.rms.inspections.ui.fragment.ContentFragment$onViewCreated$1.onChanged(ContentFragment.kt:37)
    at androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
    at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:131)
    at androidx.lifecycle.LiveData.setValue(LiveData.java:289)
    at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:33)
    at androidx.lifecycle.Transformations$2$1.onChanged(Transformations.java:153)
    at androidx.lifecycle.MediatorLiveData$Source.onChanged(MediatorLiveData.java:152)
    at androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
    at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:126)
    at androidx.lifecycle.LiveData$ObserverWrapper.activeStateChanged(LiveData.java:424)
    at androidx.lifecycle.LiveData.observeForever(LiveData.java:214)
    at androidx.lifecycle.MediatorLiveData$Source.plug(MediatorLiveData.java:141)
    at androidx.lifecycle.MediatorLiveData.addSource(MediatorLiveData.java:96)
    at androidx.lifecycle.Transformations$2.onChanged(Transformations.java:150)
    at androidx.lifecycle.MediatorLiveData$Source.onChanged(MediatorLiveData.java:152)
    at androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
    at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:126)
    at androidx.lifecycle.LiveData$ObserverWrapper.activeStateChanged(LiveData.java:424)
    at androidx.lifecycle.LiveData.observeForever(LiveData.java:214)
    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:418)
    at androidx.lifecycle.LiveData$LifecycleBoundObserver.onStateChanged(LiveData.java:376)
    at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:361)
    at androidx.lifecycle.LifecycleRegistry.forwardPass(LifecycleRegistry.java:300)
    at androidx.lifecycle.LifecycleRegistry.sync(LifecycleRegistry.java:339)
    at androidx.lifecycle.LifecycleRegistry.moveToState(LifecycleRegistry.java:145)
    at androidx.lifecycle.LifecycleRegistry.handleLifecycleEvent(LifecycleRegistry.java:131)
    at androidx.fragment.app.FragmentViewLifecycleOwner.handleLifecycleEvent(FragmentViewLifecycleOwner.java:51)
    at androidx.fragment.app.Fragment.performStart(Fragment.java:2639)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:915)
    at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
    at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
    at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
    at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
    at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
    at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManagerImpl.java:1696)
    at androidx.fragment.app.BackStackRecord.commitNow(BackStackRecord.java:293)
    at androidx.fragment.app.testing.FragmentScenario$1.perform(FragmentScenario.java:312)
    at androidx.fragment.app.testing.FragmentScenario$1.perform(FragmentScenario.java:291)
    at androidx.test.core.app.ActivityScenario.lambda$onActivity$1$ActivityScenario(ActivityScenario.java:534)
    at androidx.test.core.app.ActivityScenario$$Lambda$0.run(Unknown Source)
    at org.robolectric.android.fakes.RoboMonitoringInstrumentation.runOnMainSync(RoboMonitoringInstrumentation.java:53)
    at androidx.test.core.app.ActivityScenario.onActivity(ActivityScenario.java:527)
    at androidx.fragment.app.testing.FragmentScenario.internalLaunch(FragmentScenario.java:290)
    at androidx.fragment.app.testing.FragmentScenario.launch(FragmentScenario.java:203)
    at com.nu.rms.inspections.ExampleUnitTest.inspection failure point to location mapping is correct(ExampleUnitTest.kt:56)
    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.robolectric.RobolectricTestRunner$HelperTestRunner$1.evaluate(RobolectricTestRunner.java:600)
    at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:260)
    at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:130)
    at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:42)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.internal.SandboxTestRunner$1.evaluate(SandboxTestRunner.java:84)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at androidx.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:104)
    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/58651075/fragment-unit-testing-launchfragment-throws-classcastexception,"['android', 'unit-testing', 'android-fragments', 'testing', 'android-fragmentactivity']",4052,True,3,1
.netcore unit testing not running properly,"<p>I have created some unit tests for a simple c#/dotnet-core console application.
I have created the reference on the testing project but for some reason the ""dotnet test"" cmd is still reporting the following error:</p>

<blockquote>
  <p>UnitTest1.cs(12,25): error CS0103: The name 'LinkChecker' does not
  exist in the current context
  [/Users/med.bensalem/Desktop/dotnet-projects/checklinksTests/checklinksTests.csproj]
  UnitTest1.cs(19,25): error CS0103: The name 'LinkChecker' does not
  exist in the current context
  [/Users/med.bensalem/Desktop/dotnet-projects/checklinksTests/checklinksTests.csproj]</p>
</blockquote>

<p>Project structure:</p>

<pre><code>.
├── checklinksTests
│   ├── UnitTest1.cs
│   ├── checklinksTests.csproj
└── checklinksconsole
    └── code
        ├── LinkChecker.cs
        ├── Program.cs
        └── checklinksconsole.csproj
</code></pre>

<p>Please find below the code I project source code:</p>

<p><strong>Main application - checklinksconsole:</strong></p>

<p><em>checklinksconsole.csproj - file:</em>
    </p>

<pre><code>  &lt;PropertyGroup&gt;
    &lt;OutputType&gt;Exe&lt;/OutputType&gt;
    &lt;TargetFramework&gt;netcoreapp2.2&lt;/TargetFramework&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=""HtmlAgilityPack.NetCore"" Version=""1.5.0.1"" /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;
</code></pre>

<p><em>Program.cs - file:</em></p>

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

namespace checklinksconsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var site = ""https://www.google.com"";
            var client = new HttpClient();
            var body = client.GetStringAsync(site);
            Console.WriteLine(body.Result);

            Console.WriteLine();
            Console.WriteLine(""Links:"");
            var links = LinkChecker.GetLinks(body.Result);
            links.ToList().ForEach(Console.WriteLine);
        }
    }
}
</code></pre>

<p><em>LinkChecker.cs - file:</em></p>

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

namespace checklinksconsole
{
    public class LinkChecker
    {
        public static IEnumerable&lt;string&gt; GetLinks(string page)
        {
            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(page);
            var links = htmlDocument.DocumentNode.SelectNodes(""//a[@href]"")
                .Select(n =&gt; n.GetAttributeValue(""href"", string.Empty))
                .Where(l =&gt; !String.IsNullOrEmpty(l))
                .Where(l =&gt; l.StartsWith(""http""));
            return links;
        }
    }
}
</code></pre>

<p><strong>Unit testing - checklinksTests:</strong></p>

<p><em>checklinksTests.csproj - file:</em></p>

<pre><code>&lt;Project Sdk=""Microsoft.NET.Sdk""&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;netcoreapp2.2&lt;/TargetFramework&gt;

    &lt;IsPackable&gt;false&lt;/IsPackable&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=""Microsoft.NET.Test.Sdk"" Version=""15.9.0"" /&gt;
    &lt;PackageReference Include=""xunit"" Version=""2.4.0"" /&gt;
    &lt;PackageReference Include=""xunit.runner.visualstudio"" Version=""2.4.0"" /&gt;
  &lt;/ItemGroup&gt;

  &lt;ItemGroup&gt;
    &lt;ProjectReference Include=""..\checklinksconsole\code\checklinksconsole.csproj"" /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;
</code></pre>

<p><em>UnitTest1.cs - file:</em></p>

<pre><code>using System;
using Xunit;

namespace checklinksTests
{
    public class UnitTest1
    {
        [Fact]
        public void WithoutHTTPAtTheStartOfTheLink_NoLinks()
        {
            var links = LinkChecker.GetLinks(""&lt;a href=\""google.com\"" /&gt;"");
            Assert.Equal(links.Count(),0);
        }

        [Fact]
        public void WithHTTPAtTheStartOfTheLink_LinkParses()
        {
            var links = LinkChecker.GetLinks(""&lt;a href=\""http://google.com\"" /&gt;"");
            Assert.Equal(links.Count(),1);
            Assert.Equal(links.First(), ""google.com"");
        }
    }
}
</code></pre>

<p>Any idea on what is wring with my code.</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/56566243/netcore-unit-testing-not-running-properly,"['c#', '.net-core', 'xunit.net']",161,True,2,1
Unit testing asynchronous HTTP request function,"<p>I'm trying to write unit tests in XCode, but i encountered problem with asynchronous function. The main idea is to check the length of received JSON</p>

<p>The function I'm trying to test (existing in someVC class):</p>

<pre class=""lang-swift prettyprint-override""><code>func getSomeCount(url: String){
        Alamofire.request(url, method: .get).responseJSON { (response) in
            if response.result.isSuccess{
                self.someJSON = JSON(response.result.value!)
                self.length = self.someJSON!.count
            }else{
                self.length = 0
                print(""Error \(String(describing: response.result.error))"")
            }
        }
    }
</code></pre>

<p>and the test looks like this:</p>

<pre><code>func testAPIResponse(){
        let someVC = SomeVC()
        someVC.getSomeCount(url: ""http:\\www.someapi.com"")
        XCTAssertEqual(someVC.length, 1234)
}
</code></pre>

<p>I know that I should use expectations, but don't know how to implement them correctly in this case. The tests fails saying that 0 is not equal to 1234. How it should be done properly?</p>
",https://stackoverflow.com/questions/56103036/unit-testing-asynchronous-http-request-function,"['swift', 'xcode', 'unit-testing', 'asynchronous']",300,False,2,0
Unit Testing spark dataframes transformation chaining,"<p>I am very new to scala spark ecosystem and wondering what would be the best way to unit test a chained dataframe transformation.So here is code sample of the method that I would like to test</p>

<pre><code>def writeToParquet(spark: SparkSession, dataFrame: DataFrame, col1: DataType1, col2:DataType2): Unit {
    dataFrame
        .withColumn(""date"", some_columnar_date_logic)
        .withColumn(""hour"", some_more_functional_logic)
        .... //couple more transformation logic
        .write
        .mode(SaveMode.Append)
        .partitionBy(""col1"", ""col2"", ""col3"")
        .parquet(""some hdfs/s3/url"")        
} 
</code></pre>

<p>The problem is parquet is of <code>Unit</code> return type which makes testing difficult.
The problem is further amplified by the fact that, transformations are immutable in nature, which makes mocking and spying a bit difficult</p>

<p>To create dataframe, I have dumped test dataset in csv </p>
",https://stackoverflow.com/questions/54403226/unit-testing-spark-dataframes-transformation-chaining,"['scala', 'unit-testing', 'apache-spark', 'apache-spark-sql', 'parquet']",4716,True,2,2
Android Livedata repository unit testing prob,"<p>I am trying to write Unit test for a database fetching method in Repository.</p>

<pre><code>public class CategoriesRepository {

private final CategoryDao categoryDao;
private final AppExecutors mAppExecutors;
private MutableLiveData&lt;List&lt;Category&gt;&gt; categoryLivedata;


 public LiveData&lt;List&lt;Category&gt;&gt; getCategories() {

  categoryLivedata.setValue(null);
  categoryLivedata = (MutableLiveData&lt;List&lt;Category&gt;&gt;) 
  categoryDao.getAllCategory();
  return categoryLivedata;
 }


} 
</code></pre>

<p>When I am trying to write unit test for the above method,</p>

<pre><code>public class CategoriesRepositoryTest {

    private CategoryDao categoryDao = mock(CategoryDao.class);
    private CategoriesRepository repo = CategoriesRepository.getInstance(categoryDao, new InstantAppExecutors());

    @Rule
    public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule();

    @Test
    public void getCategoriesTest(){
        MutableLiveData&lt;List&lt;Category&gt;&gt; dbData = new MutableLiveData&lt;List&lt;Category&gt;&gt;();
        List&lt;Category&gt; categoryTest = TestUtils.createCategoryList();
        dbData.setValue(categoryTest);
        when(categoryDao.getAllCategory()).thenReturn(dbData);

        Observer&lt;List&lt;Category&gt;&gt; observer = mock(Observer.class);


        LiveData&lt;List&lt;Category&gt;&gt; categories = repo.getCategories();
        categories.observeForever(observer);  // line no. 45
        verify(observer).onChanged(categoryTest);

    }

}
</code></pre>

<p>It is returning nullpointerexception:</p>

<pre><code>java.lang.NullPointerException
    at com.cybage.roomapplication.category.CategoriesRepositoryTest.getCategoriesTest(CategoriesRepositoryTest.java:45)
    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.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.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>Please help me to solve the problem.</p>
",https://stackoverflow.com/questions/56972852/android-livedata-repository-unit-testing-prob,"['android', 'unit-testing', 'mvvm', 'repository', 'android-livedata']",283,False,2,0
Save variable during unit testing Laravel,"<p>Variable <code>$this-&gt;id</code> not visible in another function <code>testExemple</code></p>

<p>If I pass this variable to a normal function that does not start on a “test” and not to a testing function, everything will work.</p>

<p>Can I fix this somehow? </p>

<pre><code>class LoginTest extends TestCase
{
    protected $id;
    public function testLogin()
    {
        $response = $this-&gt;json('post', 'auth/login', 
            ['email' =&gt; 'admin@mail.com', 'password' =&gt; '12345678'])
            -&gt;assertJsonStructure(['data' =&gt; ['id', 'name', 'email']]);

        $response-&gt;assertStatus(201);

        $userData = $response-&gt;getContent();
        $userData = json_decode($userData, true);
        $this-&gt;id = $userData['data']['id'];
    }
    public function testExemple()
    {
        echo($this-&gt;id);
    }
}
</code></pre>
",https://stackoverflow.com/questions/55256481/save-variable-during-unit-testing-laravel,"['php', 'laravel', 'unit-testing', 'phpunit']",1905,True,2,3
Angular8 unit testing jasmine timeout issue,"<p>Running into random unit test failures with this failure mode</p>

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

<p>Some of these tests that failed do not even have async testing going on!</p>

<p>Wondering if this snippet of code is correct or not; it is a pattern we use across the board in all tests in Angular</p>

<pre><code>beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({ . // Should this be **return TestBed.configureTestingModule**
      imports: [
        ...CommonTestModules
      ],
      declarations: [FooComponent]
    })
    .compileComponents();
  }));
</code></pre>

<p>Should the promise of compileComponents be returned from the callback? I read somewhere that the promises are awaited for by the async wrapper which eventually calls done() when the promises are resolved. But here this pattern looks like it is not returning the promise and we are not invoking the ""await"" keyword anywhere either. Does this code appear wrong without the return statement?</p>
",https://stackoverflow.com/questions/58292245/angular8-unit-testing-jasmine-timeout-issue,"['angular', 'karma-jasmine', 'angular-unit-test', 'karma-jasmine-ajax']",1753,True,2,2
Unit testing Angular component + ngrx store,"<p>Trying to testing my angular component. </p>

<p>I've got root state and module state, it looks like:</p>

<pre><code>state {
  auth: {
  // user data
  },
  messagesModule:{
   // here's module state
    messages:[...]
  }
}
</code></pre>

<p>Initial messages state is empty object.</p>

<p>component: </p>

<pre><code>export class MessagesComponent {
  public messages$: Observable&lt;number&gt;;

  constructor(private store: Store&lt;any&gt;) {
   this.messagesLengh$ = store.pipe(select('getMessagesLengh'));
  }
...
</code></pre>

<p>selector</p>

<pre><code>export const msgLength = (state: AppState) =&gt; state.messages.lenght;
</code></pre>

<p>test</p>

<pre><code>describe('MessagesComponent', () =&gt; {
  let component: MessagesComponent;
  let fixture: ComponentFixture&lt;MessagesComponent&gt;
  let store: Store&lt;fromFeature.State&gt;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        StoreModule.forRoot({
          ...fromRoot.reducers,
          messagesModule: combineReducers(fromFeature.reducers),
        }),
    // other imports
      ],
      ...
    });

    store = TestBed.get(Store);

    spyOn(store, 'dispatch').and.callThrough();

    fixture = TestBed.createComponent(MessagesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () =&gt; {
    expect(component).toBeTruthy();
  });
</code></pre>

<p>So here's the trouble: test fails because ""couldn't find messages of undefined"".  I consoled log my test component, there is store. Any ideas, please.</p>
",https://stackoverflow.com/questions/54755013/unit-testing-angular-component-ngrx-store,"['angular', 'unit-testing', 'karma-jasmine', 'ngrx']",4217,False,2,1
Iceberg Class and Google Unit Testing,"<p>I am going through the process of doing unit testing of a existing code which is written not with unit testing in mind.</p>

<p>There is a few class structured like something like this:</p>

<pre><code>class Texture
{
public:
    friend class Model;
private:
 void Load( int a, int b);
 void Update(int a, int b);
 void Use(int a, int b);    
}

class Material
{
public:
    friend class Model;
private:
 void Load(int a);
 void Update(int a);
 void Use(int a);    
}

class Mesh
{
public:
    friend class Model;
private:
 void Load(int a, int b, int c);
 void Update(int a, int b, int c);
 void Use(int a, int b, int c);    
}


class Model
{
    public:

    void Load(); // call all the individual Load()
    void Use(); // call all the individual Use()
}
</code></pre>

<p>The reason why they are kept as private is because it is design in such a way where only Model class can call them, hence the friend. </p>

<p>[<em>In the actual code there is a Attorney-Client idiom which limit the access of Model to these class, but I leave it out of the code snippet</em>]</p>

<p>Now I am trying to do unit testing for the classes. While figuring out how to test these private functions, I came across this terminology of an <a href=""https://www.artima.com/weblogs/viewpost.jsp?thread=125574"" rel=""nofollow noreferrer"">Iceberg Class</a> which I feel the above class is in a way guilty of. </p>

<p>Most article touching on this topic also mentioned that if there is a need to test a private function, it mostly means that class is overdoing and these functions are better off in another standalone class where they stay as public.</p>

<p>So right now, I am not sure if this is a bad code design and I should redesign them to make unit testing easier, or those I just proceed with unit testing as it is.</p>

<p>Would like to hear your opinions</p>
",https://stackoverflow.com/questions/56536150/iceberg-class-and-google-unit-testing,"['c++', 'unit-testing', 'googletest', 'friend']",425,True,2,2
PDO Extension on Laravel unit testing,"<p>I've been struggling with setting up unit test with my Laravel application, I'm facing error... it says that PDO extension is not installed and giving me error that ""PDOException driver not found"" but it's installed!!!. When I serve my application everything is OK!!!</p>

<p>PDO is also installed:</p>

<pre><code>  28 =&gt; ""json""
  29 =&gt; ""exif""
  30 =&gt; ""mysqli""
  31 =&gt; ""pdo_mysql""
  32 =&gt; ""pdo_sqlite""
  33 =&gt; ""Phar""
  34 =&gt; ""posix""
  35 =&gt; ""readline""
  36 =&gt; ""shmop""
</code></pre>

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

<pre class=""lang-php prettyprint-override""><code>&lt;?php

namespace Tests\Unit;

use App\Models\User\User;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        factory(User::class)-&gt;create();
        $this-&gt;assertTrue(true);
    }
}

</code></pre>

<p>Trace of error:</p>

<pre><code> /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Connection.php:624
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Connection.php:459
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Connection.php:411
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/Processor.php:32
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2653
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:1347
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:835
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:800
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:663
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:206
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Support/Collection.php:419
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:207
 /home/soheil/Documents/Projects/PHP/EcollegeMe/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:181
 /home/soheil/Documents/Projects/PHP/EcollegeMe/tests/Unit/ExampleTest.php:18

 Caused by
 PDOException: could not find driver


</code></pre>
",https://stackoverflow.com/questions/55391167/pdo-extension-on-laravel-unit-testing,"['php', 'laravel', 'unit-testing', 'testing']",206,False,2,1
Swift package unit testing with CoreData,"<p>I have a swift bunch of files that provides some services above CoreData. I had unit tests running fine. I decided to move all this into a Swift Package using XCode 11.</p>

<p>The unit tests don't run anymore, having a runtime error of <code>caught ""NSInternalInconsistencyException"", ""NSFetchRequest could not locate an NSEntityDescription for entity name</code>.</p>

<p>To do my unit tests, I have a xcdatamodel file that is included in the test group if the package. But it seems XCode is not allowing me to really include this xcdatamodel file as part of the test target.</p>

<p>How can I include this xcdatamodel in the test target ?</p>
",https://stackoverflow.com/questions/58258965/swift-package-unit-testing-with-coredata,"['swift', 'core-data', 'package-managers', 'xcode11']",549,True,2,2
Unit testing of method returning enum,"<p>I am trying to create a test case of a method. Inside which another method is getting called which is returning an enum type.
How to expect and return for this method which is returning enum.</p>

<pre><code>public class xyz {

    public request pqrs(Rest rest) { 
        Confirm cnf= new Confirm();
        cnf.getAct().toString();
    }
}
</code></pre>

<p><p></p>

<pre><code>public class Confirm {

    public Hgs getAct() {
        return act
    }
}
</code></pre>

<p><p></p>

<pre><code>public enum Hgs{

}
</code></pre>

<p>How to expect and return for getAct()?</p>
",https://stackoverflow.com/questions/57090829/unit-testing-of-method-returning-enum,"['junit', 'easymock']",450,False,1,1
Unit testing asynchronous call in angular,"<p>I have following function in a service 'MyService':</p>

<pre><code>myFunction(input: MyInput){
this.someService.someFunction(&lt;any&gt; input).then(result =&gt; {
  console.log('Somefunction worked successfully');
  return result;
}).catch(reason =&gt; {
  throw new Error('Somefunction failed');
})
}
</code></pre>

<p>And unit test for myFunction is as:</p>

<pre><code>// create test data
spyOn(someService, 'someFunction').and.returnValue(Promise.resolve(dummyResult));

// invoke target unit
const response = myService.myFunction(dummyInput);

// validations
expect(someService.someFunction).toHaveBeenCalled();
expect(someService.someFunction).toHaveBeenCalledTimes(1);
expect(someService.someFunction).toHaveBeenCalledWith(dummyInput);
expect(response).toBe(dummyResult)
</code></pre>

<p>First three validations pass, but last one doesn't as call to someFunction is asynchronous and hence response is still undefined at time of validation.</p>

<p>How to handle such scenario? 
I came across fakeAsync but examples are a bit different from this.</p>
",https://stackoverflow.com/questions/57747624/unit-testing-asynchronous-call-in-angular,['angular-test'],11,False,1,0
Unit testing retries with project reactor,"<p>I have a piece of code that goes something like this:</p>

<pre><code>somePublisher
  .subscribeOn(...)
  .flatMap { x -&gt; someFunctionThatReturnsMono(x) }
  .retry(3)
  .subscribe()
</code></pre>

<p>So far I have managed to unit test happy paths, like whether the code inside <code>map {...}</code> is getting called, using the tools from reactor-test.</p>

<p>Now I want to test errors and retries. How can I test to make sure <code>someFunctionThatReturnsMono(x)</code> is getting called at most 4 times when  consecutive errors occur?</p>
",https://stackoverflow.com/questions/57046917/unit-testing-retries-with-project-reactor,"['unit-testing', 'project-reactor']",2669,True,1,2
Unit testing using doctest in python,"<p>Define a function definition of 'isPalindrome' which checks if given number positive number is palindrome or not and return True and False correspondingly.</p>

<ul>
<li>write a doctest which checks the function call 'isPalindrome(121)' returns True.</li>
<li>write a doctest which checks the function call 'isPalindrome(344)' returns False.</li>
<li>write a doctest which checks the function call 'isPalindrome(-121)' raises ValueError with an error message as 'x must be positive integer'.</li>
<li>write a doctest which checks the function call 'isPalindrome('hello')' raises TypeError with an error message as 'x must be an integer'.</li>
</ul>

<p>I tried below but its giving answer as -</p>

<p>True
4
1
1
4
0</p>

<p>but the expected answer is</p>

<p>True
4
1
1
4
2</p>

<pre><code>#!/bin/python3
import math
import os
import random
import re
import sys
import inspect

# Complete the isPalindrome function below.
def isPalindrome(x):
    # Write your doctests below.
    """"""
    &gt;&gt;&gt; isPalindrome(121)
    True
    &gt;&gt;&gt; isPalindrome(344)
    False
    &gt;&gt;&gt; isPalindrome(-121)
    ValueError: x must be positive integer.
    &gt;&gt;&gt; isPalindrome(""hello"")
    TypeError: x must be integer.
    """"""  

    # Write the functionality below
    try:
        x = int(x)
        temp=x
        rev=0
        if(x&gt;0):
            while(x&gt;0):
                dig=x%10
                rev=rev*10+dig
                x=x//10
            if(temp==rev):
                return True
            else:
                return False
        elif(x&lt;0):
            raise TypeError
        else:
            raise ValueError
    except ValueError:
        raise ValueError(""x must be positive integer"")
    except TypeError:
        raise TypeError(""x must be an integer"")


if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    x = input()

    if x.isdigit():
        x = int(x)

    res = isPalindrome(x)

    doc = inspect.getdoc(isPalindrome)

    func_count = len(re.findall(r'isPalindrome', doc))
    true_count = len(re.findall(r'True', doc))
    false_count = len(re.findall(r'False', doc))
    pp_count = len(re.findall(r'&gt;&gt;&gt;', doc))
    trace_count = len(re.findall(r'Traceback', doc))

    fptr.write(str(res)+'\n')
    fptr.write(str(func_count)+'\n')
    fptr.write(str(true_count)+'\n')
    fptr.write(str(false_count)+'\n')
    fptr.write(str(pp_count) + '\n')
    fptr.write(str(trace_count) + '\n')

    fptr.close()
</code></pre>

<p>Please suggest</p>
",https://stackoverflow.com/questions/54617620/unit-testing-using-doctest-in-python,"['python-3.x', 'doctest']",15626,True,1,7
Unit testing services annotations without Symfony,"<p>I got a few bundles that are not installed in <code>Symfony</code> yet.</p>

<p>These bundles have a <code>services.yml</code> file in them:</p>

<pre><code>mybundle/src/Bundle/Resources/config/services.yml
</code></pre>

<p>The <code>services.yml</code> contains classes and arguments from the bundle that are later used by <code>Symfony</code>, but not by the bundle itself:</p>

<pre><code>mybundle.data.download.get:
  class: mybundle\data\download\getinfo\get
  arguments:
  - ""@bundle.myDepdendency.generate""
  - ""@bundle.myDepdendency.dosomething""
  - ""@bundle.helloThere""
</code></pre>

<p>I have working unit tests in <code>Symfony</code> for <code>services.yml</code> that checks that all classes are loaded correctly, however since I am developing the bundles independently outside of Symfony, I'd like to have a test to know if <code>services.yml</code> contains all the classes and their arguments.</p>

<p>So the question is:</p>

<p>Is there a way to test if <code>services.yml</code> contains given classes and their arguments without using Symfony?</p>
",https://stackoverflow.com/questions/55181481/unit-testing-services-annotations-without-symfony,"['php', 'unit-testing', 'symfony', 'yaml']",46,True,1,1
Mocking Jenkins class for unit testing,"<p>I have written a class for cancelling a build of a particular job based on build number.</p>

<p>Now I am not understanding how to mock Jenkins related stuffs for my unit tests</p>

<p>This is the class</p>

<p>/**
 * Cancel the builds of a particular job
 */</p>

<pre><code>import jenkins.model.*

def call(Map options = [:]) {
if(!options.job)
    error ""Parameter job (jenkins job path) is missing""
if(!options.numbers)
    error ""Parameter numbers (build numbers) is missing""
def numbers = options.numbers instanceof List ? (options.numbers?.flatten() as Set):options.numbers

for(def number:numbers) {     
    echo ""Cancelling the job $options.job with build number $number""
    abortBuild(options.job, number)
}

}

def abortBuild(String job, Integer number) {
def build = Jenkins.instance.getItemByFullName(job)
        .getBuildByNumber(number)
if(null != build &amp;&amp; build.isBuilding() || build.isInQueue()) {
    build.finish(hudson.model.Result.ABORTED, new java.io.IOException(""Aborting build""))
}
}

return this
</code></pre>

<p>Test class which I tried  was wrapping this class</p>

<pre><code>   class WrapCancelBuilds extends BasePipelineTest {
   List&lt;String&gt; messagePublished = []
   String errorMessage


  def run( def jobName, def numbers ) {
  super.setUp()

  def script = loadScript('vars/cancelBuilds.groovy')
  helper.registerAllowedMethod(method('echo', String.class), { message -&gt;
     messagePublished.add(message)
  })
  helper.registerAllowedMethod(method('error', String.class), { message -&gt;
     errorMessage = message
  })
  helper.registerAllowedMethod(method('abortBuild', String.class, int), {
    true
  })     
  script([job:jobName,numbers:numbers])

  }
</code></pre>

<p>I get following error message
java.lang.NullPointerException: Cannot invoke method getItemByFullName() on null object</p>

<p>How to resolve it</p>
",https://stackoverflow.com/questions/56269982/mocking-jenkins-class-for-unit-testing,"['jenkins', 'mocking', 'jenkins-plugins', 'powermock', 'jenkins-groovy']",545,False,1,0
Mock Spring Controller for unit testing,"<p>I'm trying to test a rest call that is a part of an mvc controller. 
My unit test is currently returning a 404 error code, instead of a 200 status code, which would determine that the request was sent successfully.</p>

<p>Here's the signature of my method that I'm trying to test:</p>

<pre><code>@PreAuthorize(""hasRole('ROLE_SSL_USER')"")
@PostMapping(value = ""/employee"", consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity&lt;Object&gt; postEmployee(HttpEntity&lt;String&gt; httpEntity, @RequestHeader(""DB-Client-Id"") String clientId,
        @RequestHeader(""X-Forwarded-Client-Dn"") String dn) throws IOException, ValidationException {}
</code></pre>

<p>Here's my unit test class:</p>

<pre><code>public class ControllerTest {

  @InjectMocks
  private Controller aController;

  private MockMvc mockMvc;

  @Before
  public void setup() {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.standaloneSetup(aController).build();
  }

  @Test
  public void PostEmpTest() {

    try {
        this.mockMvc.perform(post(""/employee"")
                    .contentType(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  }
}
</code></pre>

<p>Am I missing something from my perform() call that is resulting in the 404 bad request code?</p>
",https://stackoverflow.com/questions/55927592/mock-spring-controller-for-unit-testing,"['java', 'spring-mvc', 'model-view-controller', 'junit', 'mockito']",1734,True,1,1
Enzyme Unit testing private React Components,"<p>I have a component which looks something like :</p>

<pre><code>export default class MyComponent extends Component {

 render() {
  return(
        &lt;div&gt;
           &lt;PrivateComponent1/&gt;
           &lt;PrivateComponent2/&gt;
           &lt;PrivateComponent3/&gt;
          &lt;/div&gt;
      );
 }
}
</code></pre>

<p>Now I need to write unit tests for the private components with enzyme. I could think of only two approaches to unit test them</p>

<ol>
<li>Use <code>mount</code> instead of <code>shallow</code> and mount MyComponent but then then we need to worry about the 
 private components dependencies.</li>
<li><code>export</code> those private components and write unit tests separately, but they may not be useful anywhere else in the project and exporting may not make any sense.</li>
</ol>

<p>Please advice if there exists some standard way</p>
",https://stackoverflow.com/questions/54359649/enzyme-unit-testing-private-react-components,"['reactjs', 'unit-testing', 'enzyme']",50,False,1,0
Python unit testing: psycopg2 query coverage,"<p>We're doing unit testing via the usual unittest module of python. This works very well with coverage, but it does not really help to find out if queries are tested well. Is there any tool to collect coverage information for queries used in psycopg2? Some of our queries are quite complex and as such can have multiple paths, depending on the data that is currently in the database.</p>

<p>I'd split up the queries, but that would have a bigger performance impact, as the query planner will not be able to optimize as well as in a single query.</p>

<p>[TL;DR]: Is there any tool to collect coverage information for queries used in psycopg2?</p>
",https://stackoverflow.com/questions/59323586/python-unit-testing-psycopg2-query-coverage,"['python', 'unit-testing', 'code-coverage', 'psycopg2']",104,False,1,0
Unit testing a private callback factory,"<p>I am trying to create unit tests for a private callback factory with an alarm manager class. I don't want to test the private method directly as I think this contravenes  TDD good practice but I cannot figure out a good way to test this.</p>

<p>Please don't just tell me my code is bad (I already know!). I just want to know if it is possible to use the unittest framework to test this or if I need to re-architect my code.</p>

<p>My class is an alarm manager that is responsible for managing the creation, scheduling and sound of an alarm. When an alarm is created, it is passed to a scheduler with a callback function. To create this callback function, there is a private callback factory that takes in the alarm object to generate the custom callback (while capturing some variables from the manager class)</p>

<p>The problem I have is that unless I use the full functionality of the scheduler, the callback will never get executed but obviously there will be a lot of pain with patching time to make sure it executes in a reasonable time. Furthermore, the callback is never returned to the user so no easy way of checking (or even calling it there)</p>

<p>The manager class looks largely like the code below:</p>

<pre class=""lang-py prettyprint-override""><code>class Manager:

    def __init__(self):
        self._scheduler = alarm.scheduler.Scheduler()
        self._player = sound.player.Player()

    def create_alarm(self, name, new_alarm):
        self._scheduler.add_job(name, new_alarm.find_next_alarm(),\
            self._create_callback(name, new_alarm))

    def _create_callback(self, name, callback_alarm):
        def callback():
           self._player.play(callback_alarm.get_playback())
        return callback
</code></pre>

<p>Overall, is there a way to somehow extract the callback object if I make the scheduler a mock object. Or is there some other clever way to test that the callback is doing what it should be?</p>
",https://stackoverflow.com/questions/57661127/unit-testing-a-private-callback-factory,"['python-3.x', 'callback', 'python-unittest', 'private-methods']",132,False,1,0
C# - Unit testing a WebApi controller,"<p>I am used to test Web controllers in Java in which a real request is being sent to the controller even under a unit test.</p>

<p>When it comes to C# the doc I am seeing like <a href=""https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-with-aspnet-web-api"" rel=""nofollow noreferrer"">here</a> or <a href=""https://www.c-sharpcorner.com/article/unit-testing-controllers-in-web-api/"" rel=""nofollow noreferrer"">here</a> it seems to check the call workflow to the controller methods but not an entire http message workflow.</p>

<p>In particular, say i have the following controller:</p>

<pre><code>public class SessionController : ApiController
{
    [HttpDelete]
    [ResponseType(typeof(IHttpActionResult))]
    [Route(""api/v1/sessions/{session-id}"")]
    [ActionName(""stop_session"")]
    [ValidateModel]
    public IHttpActionResult StopSession([FromUri(Name = ""session-id"")] Guid sessionId)
    {
        Console.WriteLine($""Stopping session {sessionId}"");

        SessionRepository.Instance.Remove(sessionId);

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

<p>If i create the following unit test:</p>

<pre><code>    [TestMethod]
    public void TestStopSession()
    {
        SessionController controller = new SessionController()
        {
            Request = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri(""http://localhost:9000/api/v1/zada"")
            }
        };
        controller.Configuration = new HttpConfiguration();

        var res = controller.StopSession(new Guid());

        Assert.IsInstanceOfType(res, typeof(OkResult));
    }
</code></pre>

<p>As you can see, in test I am putting a different URL and even a different method and still the unit test passes successfully.</p>

<p>What is the way to unit test the entire HTTP workflow?</p>
",https://stackoverflow.com/questions/56725046/c-unit-testing-a-webapi-controller,"['c#', 'unit-testing']",175,False,1,1
Xamarin Forms Unit Testing a Command,"<p>I am trying to unit test a Command in Xamarin.Forms.</p>

<p>I have my view-model class as an example like this</p>

<pre><code>public class CarViewModel
{
    public Command SelectedCommand { get; } =&gt; new Command(OnSelected);

    public Car SelectedCar
    {
      get { return _selectedCar; }
      private set { _selectedCar = value; }
    }

    private void OnSelected(object obj)
    {
      if (obj is Car car) 
      {
        SelectedCar = car;
      }
    }
}
</code></pre>

<p>This class is the <code>BindingContext</code> for my view and the <code>SelectedCommand</code> above is fired when user taps on a ListView item, so it is a method that is bound to a <code>Command</code> in XAML using a <code>TapGestureRecognizer</code> like</p>

<pre><code>&lt;TapGestureRecognizer Command=""{Binding SelectedCommand}"" .../&gt;
</code></pre>

<p>I am trying to unit test this class, so my <code>CarViewModel</code> class is subject under test (SUT) inside my test.</p>

<p>I just started looking at mocking libraries / isolation frameworks and I see Moq is quite popular.</p>

<p>My questions are:</p>

<ol>
<li>Since I dont have any dependencies in my <code>CarViewModel</code> below, I dont think I need to mock that class in my test.  It is subject under test which to my understanding should not be mocked.  Only dependencies should be mocked.  Is this correct?</li>
<li>How do I unit test to confirm that my <code>SelectedCommand</code> has been called and that it has set <code>SelectedCar</code> property?  If I am right in 1 above, then Moq is not even needed to test this since I have no dependency to mock for my <code>CarViewModel</code> class.</li>
</ol>
",https://stackoverflow.com/questions/54369595/xamarin-forms-unit-testing-a-command,"['c#', 'unit-testing', 'xamarin.forms', 'mocking', 'moq']",1648,True,1,1
AngularJS unit testing Karma - unknown provider,"<p>I am trying to set up unit tests on our legacy AngularJS app. I am using the standard karma along with angular-mock to set up the tests cases. But I am getting issues with <code>Unknown provider</code> when I am trying to inject some services and factory. My karma.conf looks something like this (I have removed a lot of stuff for brevity)</p>

<pre><code>module.exports = function(config) {   config.set({

     basePath: '',

     // frameworks to use
     // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
     frameworks: ['jasmine'],

     // list of files / patterns to load in the browser
     files: [
       './node_modules/angular/angular.js',
       ""http://cf._____.com/content/myfootprints/js/priorityqueue.js"",
       ""http://cf._____.com/content/myfootprints/js/ng-flow-standalone.js"",
       INCLUDED ALL THE DEPENDENCIES HERE 
       './node_modules/angular-mocks/angular-mocks.js',
       './static/js/app/main.js',
       './static/tests/**/*.js'
     ]
     preprocessors: {
       './static/js/app/**/main.js':['webpack', 'sourcemap'],
       './static/js/app/**/*.js':['webpack', 'sourcemap'],
     },
</code></pre>

<p>In our application we have a main.js that is importing all the controllers and factories into the application using <code>imports</code> and <code>requireDir</code>. It looks something like this </p>

<pre><code>const requireDir = require('webpack-requiredir');

    import './isocurrency.js';
    import './myfp_uirouter.js';
    import './infobubble.js';
    // other imports
    requireDir(require.context('./controllers', true, /.*\.js$/))
    requireDir(require.context('./directives', true, /.*\.js$/))
    requireDir(require.context('./factories', true, /.*\.js$/))
    requireDir(require.context('./filters', true, /.*\.js$/))
</code></pre>

<p>I have a file with unit tests that looks something like this </p>

<pre><code>describe('Unit test file, function(){
  var generalUtilFactory;
  beforeEach(inject(function($injector){
    generalUtilFactory = $injector.get('generalUtilsFactory'); &lt;--- getting unknown provider 
    // Also tried to inject it in 
    //via function($rootScope,... _generalUtilFactory_)
  }));

Other code
  .
  .
  .
  .

});
</code></pre>

<p>Now I do have general util factory that is being imported through the main.js and is being registered in the app module. I checked to see it in debugger. It looks like this</p>

<pre><code>angular.module('app').factory('generalUtilsFactory', ['$timeout', '$filter', 'FileSaver', 'Blob', function($timeout, $filter, FileSaver, Blob) {
    var generalUtilsFactory = {};

    generalUtilsFactory.getKeys = function(o){
</code></pre>

<p>I am not quite sure what is happening here. All the needed files have been included and all the es6 they have been properly converted. Some help in this would be appreciated</p>
",https://stackoverflow.com/questions/55802830/angularjs-unit-testing-karma-unknown-provider,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine']",116,False,1,1
Resolve dependencies on unit testing xUnit,"<p>I have a service that converts a razor view into string and I want to unit test it. Problem is that it has some dependencies in the constructor (IRazorViewEngine, ITempDataProvider, IServiceProvider) which are injected via dependency injection in the normal startup class, but for testing I don't know how can I supply these dependencies.</p>

<p>The method I want to test is ""RenderToStringAsync()""</p>

<pre><code>    public ViewRenderService(IRazorViewEngine razorViewEngine, ITempDataProvider tempDataProvider
        , IServiceProvider serviceProvider)
    {
        _razorViewEngine = razorViewEngine;
        _tempDataProvider = tempDataProvider;
        _serviceProvider = serviceProvider;
    }

    public async Task&lt;string&gt; RenderToStringAsync(string viewName, object model)
    {
        var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
        var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

        using (var sw = new StringWriter())
        {
            var viewResult = _razorViewEngine.GetView(""~/"", viewName, false);

            if (viewResult.View == null)
            {
                throw new ArgumentNullException($""{viewName} does not match any available view"");
            }

            var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = model
            };

            var viewContext = new ViewContext(
                actionContext,
                viewResult.View,
                viewDictionary,
                new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                sw,
                new HtmlHelperOptions()
            );

            await viewResult.View.RenderAsync(viewContext);
            return sw.ToString();
        }
    }
}
</code></pre>

<p>Any help on how can I provide these dependencies ? Thanks</p>
",https://stackoverflow.com/questions/58411576/resolve-dependencies-on-unit-testing-xunit,"['c#', '.net', 'razor', 'xunit', 'asp.net-core-2.1']",440,False,1,0
Invalid Argument Exception - Laravel Unit Testing,"<p>I am running a unit test to check that</p>

<ol>
<li>View page exists</li>
<li>AssertSee that text appears on the page and with a string limit</li>
</ol>

<p>I am getting an invalid argument exception:</p>

<pre><code>1) Tests\Feature\ViewAllPostTest::testCanViewAllPosts
InvalidArgumentException: You requested 1 items, but there are only 0 items available.

C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Support\Arr.php:472
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Support\Collection.php:1486
C:\projects\car-torque-laravel\database\factories\PostFactory.php:12
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:274
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:292
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\GuardsAttributes.php:122
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:300
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:219
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:178
C:\projects\car-torque-laravel\tests\Feature\ViewAllPostTest.php:19
</code></pre>

<p>My source code is as follows:</p>

<p>Test Function</p>

<pre><code>namespace Tests\Feature;

use App\Post;
use Tests\TestCase;

class ViewAllPostTest extends TestCase
{

    /**
     * @group posts
     *
     * @return void
     */
    public function testCanViewAllPosts()
    {
        //arrange
        $post = factory(Post::class)-&gt;create();

        //action
        $response = $this-&gt;get('/posts');

        //assert
        $response-&gt;assertStatus(200);
        $response-&gt;assertSee($post-&gt;body);
        $response-&gt;assertSee(str_limit($post-&gt;body));

    }
}
</code></pre>

<p>Factory Class</p>

<pre><code>use App\Post;
use App\User;
use Faker\Generator as Faker;

$factory-&gt;define(Post::class, function (Faker $faker) {
    return [
        'body' =&gt; $faker-&gt;text,
        'user_id' =&gt; User::all()-&gt;random()-&gt;id,
        'created_at' =&gt; now(),
        'updated_at' =&gt; now(),
    ];
});
</code></pre>
",https://stackoverflow.com/questions/56059523/invalid-argument-exception-laravel-unit-testing,"['laravel', 'phpunit', 'factory']",956,True,1,1
"Dart, Flutter Redux Thunk unit testing","<p>I have written the following code and am trying to test a redux thunk action in flutter. Unfortunately when I debug the code, I can see the thunkMiddleware doesn't intercept the action as expected (as the returned <code>Function(store)</code> never gets triggered).</p>

<p><strong>state.dart</strong></p>

<pre><code>@JsonSerialize()
class Pokemon {
  final String name;
  final String url;

  Pokemon(this.name, this.url);

  factory Pokemon.fromJson(Map&lt;String, dynamic&gt; json) =&gt;
      _$PokemonFromJson(json);
}

// state
@immutable
class PokemonsState {
  final List&lt;Pokemon&gt; pokemons;
  final bool isLoading;
  final Exception ex;

  const PokemonsState(
      {this.pokemons = const [], this.isLoading = false, this.ex});

  PokemonsState copyWith(
      {List&lt;Pokemon&gt; pokemons, bool isLoading, Exception ex}) {
    return PokemonsState(
        pokemons: pokemons ?? this.pokemons,
        isLoading: isLoading ?? this.isLoading,
        ex: ex ?? this.ex);
  }
}

// reducer
PokemonsState pokemonsState(PokemonsState state, action) {
  switch (action.runtimeType) {
    case FetchPokemons:
      return state.copyWith(isLoading: true);
    case AddPokemons:
      if (action.error == null)
        return state.copyWith(
            pokemons: action.payload, isLoading: false, ex: null);

      return state.copyWith(ex: action.error, isLoading: false);
  }
  return state;
}

// actions
class FetchPokemons {}

class AddPokemons {
  final List&lt;Pokemon&gt; payload;
  final Exception error;

  AddPokemons({this.payload, this.error});
}

// thunks
loadPokemons(Client client) {
  return (Store&lt;AppState&gt; store) async {
    store.dispatch(FetchPokemons());
    try {
      var res = await client.get(pokemonUrl);
      if (res.statusCode == HttpStatus.ok) {
        final pokemons = jsonDecode(res.body)['results'];
        store.dispatch(AddPokemons(
            payload:
                List&lt;Pokemon&gt;.from(pokemons.map((i) =&gt; Pokemon.fromJson(i)))));
      } else {
        throw HttpException(res.reasonPhrase);
      }
    } on Exception catch (e) {
      store.dispatch(AddPokemons(error: e));
    }
  };
}


</code></pre>

<p><strong>state_test.dart</strong></p>

<pre><code>class MockClient extends Mock implements Client{}

void main(){

    Store&lt;PokemonsState&gt; store;

    setUp(() {
      store = Store(pokemonsState,
          initialState: PokemonsState(), middleware: [thunkMiddleware]);
    });

    test('add Pokemons success should add a list of pokemons to the store',
            () {
          final client = MockClient();

          when(client.get(argThat(isInstanceOf&lt;String&gt;()))).thenAnswer((_) async =&gt;
              Response(
                  '{""results"": [{""name"": ""p1"", ""url"": ""u1""}, {""name"": ""p2"", ""url"": ""u2""}]}',
                  200));

          store.dispatch(loadPokemons(client));
          expect(store.state.pokemons.length, 2);
        });
      });

}
</code></pre>

<p>Any help in fixing the test would be most appreciated!</p>
",https://stackoverflow.com/questions/57975956/dart-flutter-redux-thunk-unit-testing,"['flutter', 'dart', 'redux-thunk', 'flutter-test', 'flutter-redux']",919,True,1,1
Android unit testing content resolver class,"<p>I want to test the following method in Android.  I have used Junit and Mockito. </p>

<p>How do I mock <code>contentResolver.delete</code> method? </p>
",https://stackoverflow.com/questions/54071334/android-unit-testing-content-resolver-class,"['java', 'android', 'unit-testing', 'junit', 'mockito']",680,True,1,1
Unit testing memory leaks using xUnit,"<p>I recently read <a href=""https://michaelscodingspot.com/find-fix-and-avoid-memory-leaks-in-c-net-8-best-practices/"" rel=""nofollow noreferrer"">this article</a> and it was all about finding, fixing and avoiding memory leaks. I had a feeling that my ASP.NET Core 3.1 app was leaking because it kept increasing the memory usage for the first few minutes but after I kept it opened for like 5 minutes, it sticked to 350 MB in the <em>Diagnostic Tools</em> in Visual Studio 2019. Everything is probably okay because I usually don't forget to dispose stuff (by <em>using</em> block) but I wanted to make sure because my web app is listening to web sockets event for lifetime unless a CancellationToken is requested by the user.</p>

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

<p>In that article, I saw that it's possible to test an object for memory leak.</p>

<pre><code>[Test]
void MemoryLeakTest()
{
  var weakRef = new WeakReference(leakyObject)
  // Ryn an operation with leakyObject
  GC.Collect();
  GC.WaitForPendingFinalizers();
  GC.Collect();
  Assert.IsFalse(weakRef.IsAlive);
}
</code></pre>

<p>Can the following code be tested for memory leaks in unit testing using xUnit? More specifically, <code>timer</code> and <code>_subscription</code>.</p>

<pre><code>using Binance.Entity;
using Binance.Extensions;
using Binance.Helpers;
using Binance.Interfaces;
using Binance.Models.Redis;
using Binance.Net;
using Binance.Net.Interfaces;
using Binance.Net.Objects;
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Sockets;
using Hangfire;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Binance.Services
{
    public interface IBotService
    {
        void RunStart(Bot bot);
        Task StopAsync();
    }

    public class BotService : IBotService, IDisposable
    {
        private readonly ILogger _logger;
        private readonly IConfiguration _configuration;
        private readonly IBinanceClient _client;
        private readonly IBinanceSocketClient _socketClient;
        private readonly INotificationService _notificationService;

        public BotService(
            ILogger&lt;BotService&gt; logger,
            IConfiguration configuration,
            IBinanceClient client,
            IBinanceSocketClient socketClient,
            INotificationService notificationService)
        {
            _logger = logger;
            _configuration = configuration;
            _client = client;
            _socketClient = socketClient;
            _notificationService = notificationService;
        }

        private void ApplyCredentialsOnClient()
        {
            BinanceClient.SetDefaultOptions(new BinanceClientOptions()
            {
                ApiCredentials = new ApiCredentials(_configuration.GetValue&lt;string&gt;(""BinanceConfig:ApiKey""), _configuration.GetValue&lt;string&gt;(""BinanceConfig:SecretKey"")),
                AutoTimestamp = true,
                AutoTimestampRecalculationInterval = TimeSpan.FromMinutes(30)
            });

            BinanceSocketClient.SetDefaultOptions(new BinanceSocketClientOptions()
            {
                ApiCredentials = new ApiCredentials(_configuration.GetValue&lt;string&gt;(""BinanceConfig:ApiKey""), _configuration.GetValue&lt;string&gt;(""BinanceConfig:SecretKey"")),
                AutoReconnect = true,
                ReconnectInterval = TimeSpan.FromHours(24)
            });
        }

        private UpdateSubscription _subscription;

        public void RunStart(Bot bot)
        {
            BackgroundJob.Enqueue(() =&gt; Start(bot));
        }

        public void Start(Bot bot)
        {
            ApplyCredentialsOnClient();

            bool locked = false;
            Timer timer = null; 

            BinanceKline lastKnownKline = null;
            _subscription = _socketClient.SubscribeToKlineUpdates(bot.CryptoPair.Symbol, bot.TimeInterval.Interval, async data =&gt;
            {
                if (data.Data.Final)
                {
                    lastKnownKline = data.Data.ToKline();

                    // Static logic

                    // Clean up
                    if (locked)
                    {
                        locked = false;
                        timer?.Dispose();
                    }
                }
                // This block won't be executed before the static block is executed first
                else if (lastKnownKline != null &amp;&amp; lastKnownKline.Close != data.Data.Close)
                {
                    lastKnownKline = data.Data.ToKline();

                    if (!locked)
                    {
                        locked = true;

                        timer = new Timer(async state =&gt;
                        {
                            // Real time logic

                            bool condition = true;
                            if (condition)
                            {
                                timer?.Change(Timeout.Infinite, 0);
                            }
                        }, null, TimeSpan.Zero, TimeSpan.FromSeconds(scheduledTime));
                    }
                }
            }).Data;
        }

        public async Task StopAsync()
        {
            await _socketClient.Unsubscribe(_subscription);
        }

        private bool _disposed = false;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                _client.Dispose();
            }

            _disposed = true;
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/59375952/unit-testing-memory-leaks-using-xunit,"['unit-testing', 'asp.net-core', 'memory-leaks']",672,False,1,0
Unit testing - Failed to load ApplicationContext,"<p>I have a simple TestNG (Same result with JUnit) <code>@Test</code> under class as below</p>
<pre><code>@ContextConfiguration(classes = { Config.class })
@ActiveProfiles({ &quot;dev&quot; })
public class TestDAO extends AbstractTestNGSpringContextTests {
</code></pre>
<p>It started failing after merging several code branches.</p>
<p>The error is general/with unspecified origin</p>
<pre><code>[main] ERROR org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@33065d67] to prepare test instance [com.TestDAO]
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.testng.AbstractTestNGSpringContextTests.springTestContextPrepareTestInstance(AbstractTestNGSpringContextTests.java:149)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:515)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:217)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:144)
    at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:169)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:756)
    at org.testng.TestRunner.run(TestRunner.java:610)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
    at org.testng.TestNG.runSuites(TestNG.java:1133)
    at org.testng.TestNG.run(TestNG.java:1104)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.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)
    ... 30 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 47 more
Caused by: java.lang.IllegalStateException: No ServletContext set
    at org.springframework.util.Assert.state(Assert.java:70)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:450)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$825de2bf.CGLIB$resourceHandlerMapping$31(&lt;generated&gt;)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$825de2bf$$FastClassBySpringCGLIB$$14c639e2.invoke(&lt;generated&gt;)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$825de2bf.resourceHandlerMapping(&lt;generated&gt;)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
</code></pre>
<p>It seems that the context is loaded twice, where should I found the issue?</p>
<p>It's not related to <a href=""https://stackoverflow.com/questions/46548056/error-creating-bean-with-name-resourcehandlermapping-defined-in-class-path-res"">OAuth2SecurityConfiguration </a> as other answer refer to</p>
<blockquote>
<p>OAuth2SecurityConfiguration bean isn't automatically created by boot and neither it is mandatory for MethodSecurityConfigurer</p>
</blockquote>
<p>And not related to <a href=""https://github.com/spring-projects/spring-boot/issues/7699"" rel=""nofollow noreferrer"">RoleHierarchy</a></p>
<blockquote>
<p>Comment out “expressionHandler.setRoleHierarchy(roleHierarchy);”, exception disappear.</p>
</blockquote>
",https://stackoverflow.com/questions/58505726/unit-testing-failed-to-load-applicationcontext,"['java', 'spring', 'unit-testing', 'applicationcontext', 'unmappedresourcehandler']",2827,True,1,1
Unit testing with bazel and containers,"<p>I'm trying to understand how to do testing the right way when working with bazel and containers. An application should be specified as an image in the form:</p>

<pre><code>py_library(
    name = ""mylib"",
    ...
)

py_test(
    name = ""mylib_test"",
    ...
)

py3_image(
    name = ""helloimage"",
    srcs = [""hello.py""],
    main = ""hello.py"",
    deps [
        "":mylib"",
    ]
)
</code></pre>

<p>This setup is far from ideal, since unit tests should ideally run inside the same container base image, i.e. they should run within the container and not the dev's local environment. How have are people dealing with this, since this seems like a fundamental problem with Bazel's container setup?</p>
",https://stackoverflow.com/questions/55720714/unit-testing-with-bazel-and-containers,"['containers', 'bazel']",193,False,1,0
Unit testing AWS SNS Publishing message,"<p>I'm wondering how can I test a method like this:</p>

<pre><code>public PublishResponse broadcast(String eventJson, Class&lt;? extends BaseEvent&gt; type) {
    //Build Sns client.
    AwsCredentials awsCredentials = AwsBasicCredentials
            .create(snsConfiguration.getAwsAccessKeyId(), snsConfiguration.getAwsSecretAccessKey());
    StaticCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(awsCredentials);
    SnsClient snsClient = SnsClient.builder().credentialsProvider(credentialsProvider).build();
    //Prepare message attributes.
    Map&lt;String, MessageAttributeValue&gt; messageAttributes = new HashMap&lt;&gt;();
    MessageAttributeValue messageAttributeValue = MessageAttributeValue.builder().dataType(""String"").stringValue(type.getName())
            .build();
    messageAttributes.put(""type"", messageAttributeValue);
    //Publish message with event json to Amazon SNS.
    return snsClient.publish(PublishRequest.builder()
            .message(eventJson)
            .messageAttributes(messageAttributes)
            .topicArn(snsConfiguration.getTopicARN())
            .build());
}
</code></pre>

<p>All the code here depend on AWS SDK api. I know that I could some moking here but at the end time his method's responsibility is to send a message to SNS. How to write united  testing for such thing?</p>
",https://stackoverflow.com/questions/58718714/unit-testing-aws-sns-publishing-message,"['java', 'junit', 'mocking', 'amazon-sns', 'aws-sdk-java-2.0']",1961,False,1,0
Override Object Property for unit testing purposes,"<p>I am using Jest to perform unit tests on a Node.js app, where the code source is written in TypeScript and then compiled into JavaScript.</p>

<p>In one of the classes that I wish to test, an external module is imported and a method from this module is used. I want to mock the calls to this method, in order to test only my code.</p>

<p>However, when I run the test, I get the following error:</p>

<p><code>TypeError: Cannot redefine property: methodName</code></p>

<p>The problem is that this method has the following Object Properties:</p>

<pre><code>{ value: [Function],
  writable: false,
  enumerable: true,
  configurable: false }
</code></pre>

<p>The <code>configurable: false</code> is what makes it a big problem. I cannot redefine the properties before my mock call to make it writable.</p>

<p>Here is what the relevant code looks like:</p>

<p><strong>Tested Class</strong></p>

<pre><code>import externalType from 'external-module-name';

export class ClassName {
    public propertyName: externalType;

    public method(param: string): Promise&lt;any&gt; {
        return new Promise((resolve, reject) =&gt; {
            this.propertyName.externalMethod(param)
            .then((res) =&gt; {
                resolve(res);
            })
            .catch((err) =&gt; {
                reject(err);
            });
        });
    }
}
</code></pre>

<p><strong>Unit Test</strong></p>

<pre><code>import { ClassName } from 'path/to/class';

describe('class', () =&gt; {
    const class = new ClassName;

    it(""Blahblah"", (done) =&gt; {
        Object.defineProperty(class['propertyName'], 'externalMethod', {writable: true});
        const spy = jest.spyOn(class['propertyName'], 'externalMethod').mockReturnValue(Promise.resolve());
        class.method('string')
        .then((result) =&gt; {
            // Various expect()
            done();
        });
    });
});
</code></pre>

<p><strong>What I tried so far</strong></p>

<ol>
<li><p>I added the following line in my test:</p>

<p><code>Object.defineProperty(class['module'], 'methodName', {writable: true});</code></p></li>
<li><p>I defined my mock call as following:</p>

<p><code>jest.spyOn(class['module'], 'methodName').mockReturnValue(Promise.resolve());</code></p></li>
<li><p>I defined my mock call as following:</p>

<p><code>class.propertyName.externalMethod = jest.fn().mockImplementation((query) =&gt; {
    return Promise.resolve();
});</code></p></li>
<li><p>I tried to override the property that I'm calling, as following:</p>

<p><code>class.propertyName = &lt;any&gt; {
    externalMethod = (param: any) =&gt; {
        return Promise.resolve();
    }
}</code></p></li>
</ol>

<p>For this one I get the error <code>TypeError: Cannot assign to read only property externalMethod of object class</code>, which makes sense since readable is set to false.</p>

<p>But everything seems blocked from the attribute <code>configurable</code>. I'm sure there is something that can be done because I am probably not the only one who wants to perform unit tests on a class that imports an external module, as secure as it is.</p>

<p>So my question is: <strong>what would be a clean and working way of mocking the external method?</strong> And if it is strictly impossible, <strong>what would be a way of testing my class without calling that external method?</strong></p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/57755086/override-object-property-for-unit-testing-purposes,"['javascript', 'typescript', 'jestjs', 'object-properties']",10340,True,8,3
Unit Testing using Karma and jasmine,"<p>Hello performing testing on my login.component.spec.ts file and I am getting an error of </p>

<blockquote>
  <p>Failed: Uncaught (in promise): ReferenceError: toastr is not defined
  and not able to understand where the problem is</p>
</blockquote>

<pre><code>`login.component.spec.ts `:
 import { async, ComponentFixture, TestBed ,inject} from '@angular/core/testing';
    import {DebugElement} from '@angular/core';
    import {FormsModule,FormGroup,ReactiveFormsModule} from '@angular/forms';
    import { LoginComponent } from './login.component';
    import { By,BrowserModule } from '@angular/platform-browser';
    import { NgxLoadingModule } from 'ngx-loading';
    import { RouterModule } from '@angular/router';
    import { routes } from '../../app.routing';
    import { P404Component } from '../../views/error/404.component';
    import {P500Component} from '../../views/error/500.component';
    import {RegisterComponent} from '../register/register.component';
    import {ForgotPasswordComponent} from '../forgot-password/forgot-password/forgot-password.component';
    import {ResetpasswordComponent} from '../resetpassword/resetpassword.component';
    import {ChangepasswordComponent} from '../changepassword/changepassword.component';
    import {DefaultLayoutComponent} from '../../containers/default-layout/default-layout.component' ;
    import {AppAsideModule,AppBreadcrumbModule,AppHeaderModule,AppFooterModule,AppSidebarModule,
    } from '@coreui/angular';
    import { PerfectScrollbarModule } from 'ngx-perfect-scrollbar';
    import { APP_BASE_HREF } from '@angular/common';
    import { HttpClientModule,HttpClient } from '@angular/common/http'; 
    // import { ToasterService } from '../../services/toaster.service';
    import { ToasterService } from '../../services/toaster.service';
    describe('LoginComponent', () =&gt; {
      let component:LoginComponent ;
      let fixture: ComponentFixture&lt;LoginComponent&gt;;
      let de:DebugElement;
      let el:HTMLElement;
      beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
          declarations: [ LoginComponent,
    RegisterComponent,
    ForgotPasswordComponent,
    ResetpasswordComponent,
     ChangepasswordComponent,
    DefaultLayoutComponent,
    P404Component,
    P500Component],
          imports:[
            HttpClientModule,
            RouterModule.forRoot(routes),
             FormsModule,
             BrowserModule,
             NgxLoadingModule,
             ReactiveFormsModule,
             AppAsideModule,
             AppBreadcrumbModule,
             AppHeaderModule,
             AppFooterModule,
             AppSidebarModule,
             PerfectScrollbarModule,
           ] ,
           providers:[ ToasterService, { provide: APP_BASE_HREF, useValue: '/' }],           
        })
        .compileComponents().then(() =&gt;{
          fixture = TestBed.createComponent(LoginComponent);
          component = fixture.componentInstance;
          de=fixture.debugElement.query(By.css('form'));
          // el=de.nativeElement;
        });
      }));    
      beforeEach(() =&gt; {
        fixture = TestBed.createComponent(LoginComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });    
      it('should create', () =&gt; {
        expect(component).toBeTruthy();      
      });
    });
</code></pre>

<p>Getting ouptut as this:</p>

<blockquote>
  <p>Failed: Uncaught (in promise): ReferenceError: toastr is not defined
  ReferenceError: toastr is not defined
      at ToasterService.setting (webpack:///./src/app/services/toaster.service.ts?:27:9)
      at new ToasterService (webpack:///./src/app/services/toaster.service.ts?:15:14)
      at _createClass (webpack:///./node_modules/@angular/core/fesm5/core.js?:8710:20)
      at _createProviderInstance (webpack:///./node_modules/@angular/core/fesm5/core.js?:8684:26)
      at resolveNgModuleDep (webpack:///./node_modules/@angular/core/fesm5/core.js?:8647:21)
      at NgModuleRef_.get (webpack:///./node_modules/@angular/core/fesm5/core.js?:9355:16)
      at resolveDep (webpack:///./node_modules/@angular/core/fesm5/core.js?:9720:45)
      at createClass (webpack:///./node_modules/@angular/core/fesm5/core.js?:9600:32)
      at createDirectiveInstance (webpack:///./node_modules/@angular/core/fesm5/core.js?:9477:20)
      at createViewNodes (webpack:///./node_modules/@angular/core/fesm5/core.js?:10697:36)</p>
</blockquote>

<p>toaster.service.ts</p>

<pre><code>import { Injectable } from '@angular/core';
declare var toastr:any;
@Injectable()
export class ToasterService {   
  constructor() { 
    this.setting();
  }
  Info(title:string)
  {
    toastr.info(title);
  }    
  Success(title:string)
  {
    toastr.success(title);
  }    
  Error(title:string){
    toastr.error(title);
  }    
  setting()
  {
    toastr.options = {
      ""closeButton"": false,
      ""debug"": false,
      ""newestOnTop"": false,
      ""progressBar"": false,
      ""positionClass"": ""toast-top-right"",
      ""preventDuplicates"": false,
      ""onclick"": null,
      ""showDuration"": ""300"",
      ""hideDuration"": ""1000"",
      ""timeOut"": ""1800"",
      ""extendedTimeOut"": ""1000"",
      ""showEasing"": ""swing"",
      ""hideEasing"": ""linear"",
      ""showMethod"": ""fadeIn"",
      ""hideMethod"": ""fadeOut""
    }
  }
}
</code></pre>
",https://stackoverflow.com/questions/56005086/unit-testing-using-karma-and-jasmine,"['angular6', 'karma-jasmine']",276,False,1,0
Angular unit testing prime ng calendar,"<p>Inside a unit test, when I have a regular element I can set its value, trigger a change event and verify the form value matches like so:</p>

<pre><code>const hostElement = fixture.nativeElement;
const userIdSelect: HTMLInputElement = 
hostElement.querySelector('select[formcontrolname=""userId""]');
userIdSelect.value = 'myUser';
userIdSelect.dispatchEvent(new Event('change'));  
fixture.detectChanges();
expect(component.form.controls.userId.value).toBe('myUser');
</code></pre>

<p>I cant seem to get it to work with the prime ng calendar control. </p>

<pre><code>const myDate= new Date(2019,11,31);
const myDateInput: HTMLInputElement = hostElement.querySelector('p-calendar[formcontrolname=""myDate""] input');
myDateInput.value = myDate.toLocaleDateString();
myDateInput.dispatchEvent(new Event('input'));
expect(component.form.controls.myDate.value).toBe(myDate.toLocaleDateString());
</code></pre>

<p>I have a feeling this is because the form is bound to the p-calendar element, and not to its child input:</p>

<pre><code>&lt;p-calendar dateFormat=""dd/mm/yy"" formControlName=""myDate""
showIcon=""true""
[readonlyInput]=""false""&gt;&lt;/p-calendar&gt;
</code></pre>

<p>I've tried dispatching various events on the input (blur, input, etc), but no matter what I cant seem to get the form to get updated. Any ideas? Am I supposed to be setting the value of the p-calendar element instead of its input?</p>
",https://stackoverflow.com/questions/55748751/angular-unit-testing-prime-ng-calendar,"['angular', 'unit-testing', 'primeng', 'primeng-calendar']",1864,True,1,1
Unit Testing function inside foreach loop,"<p>I am writing a unit test case, I have a scenario in which there is a function inside the loop. Can anyone tell me how I can unit test that?</p>

<pre><code>function xyz(scope) {
 //how to test this loop
  angular.forEach(scope.$error, function (field) {
   angular.forEach(field, function (errorField) {
     errorField.$setTouched();
    });
   });
  }
</code></pre>
",https://stackoverflow.com/questions/56701455/unit-testing-function-inside-foreach-loop,"['javascript', 'angularjs', 'jasmine']",1687,False,1,0
TestNG Unit Testing Tar and 7z,"<p><a href=""https://i.stack.imgur.com/Uhhb6.jpg"" rel=""nofollow noreferrer"">folder structure is here</a></p>

<p><a href=""https://i.stack.imgur.com/9fLiy.jpg"" rel=""nofollow noreferrer"">console output is here</a></p>

<p>I'd like to write a test class for the 2 methods below</p>

<pre><code>package jfe;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;

public class JThreadFile {

    /**
     * uncompresses .tar file
     * @param in
     * @param out
     * @throws IOException
     */
    public static void decompressTar(String in, File out) throws IOException {
        try (TarArchiveInputStream tin = new TarArchiveInputStream(new FileInputStream(in))){
            TarArchiveEntry entry;
            while ((entry = tin.getNextTarEntry()) != null) {
                if (entry.isDirectory()) {
                    continue;
                }
                File curfile = new File(out, entry.getName());
                File parent = curfile.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }
                IOUtils.copy(tin, new FileOutputStream(curfile));
            }
        }
    }

    /**
     * uncompresses .7z file
     * @param in
     * @param destination
     * @throws IOException
     */
    public static void decompressSevenz(String in, File destination) throws IOException {
        //@SuppressWarnings(""resource"")
        SevenZFile sevenZFile = new SevenZFile(new File(in));
        SevenZArchiveEntry entry;
        while ((entry = sevenZFile.getNextEntry()) != null){
            if (entry.isDirectory()){
                continue;
            }
            File curfile = new File(destination, entry.getName());
            File parent = curfile.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(curfile);
            byte[] content = new byte[(int) entry.getSize()];
            sevenZFile.read(content, 0, content.length);
            out.write(content);
            out.close();
        }
        sevenZFile.close();
    }

}

</code></pre>

<p>I use testNG and try to read from a folder, filter the folder for certain extensions (.tar and .7z) feed those files to the uncompress methods and compare the result to the actualOutput folder with AssertEquals. I manage to read the file names from the folder (see console output) but can't feed them to decompressTar(String in, File out). Is this because ""result"" is a String array and I need a String? I have no clue how DataProvider of TestNG handles data. Any help would be appreciated :) Thank you :)</p>

<pre><code>import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class JThreadFileTest {

    protected static final File ACT_INPUT = new File(""c:\\Test\\TestInput\\""); //input directory
    protected static final File EXP_OUTPUT = new File(""c:\\Test\\ExpectedOutput\\""); //expected output directory
    protected static final File TEST_OUTPUT = new File(""c:\\Test\\TestOutput\\"");

    @DataProvider(name = ""tarJobs"")
    public Object[] getTarJobs() {

        //1
        String[] tarFiles = ACT_INPUT.list(new FilenameFilter()
        {
          public boolean accept(File dir, String name)
          {
            return name.endsWith("".tar"");
          }
        });

        //2
        Object[] result = new Object[tarFiles.length];

        int i = 0;
        for (String filename : tarFiles) {
            result[i] = filename;
            i++;
        }
        return result;


    }

    @Test(dataProvider = ""tarJobs"")
    public void testTar(String result) throws IOException {
        System.out.println(""Running test"" + result);
        --&gt; JThreadFile.decompressTar(result, TEST_OUTPUT);
        Assert.assertEquals(TEST_OUTPUT, EXP_OUTPUT);
    }

}
</code></pre>
",https://stackoverflow.com/questions/59412168/testng-unit-testing-tar-and-7z,"['java', 'unit-testing', 'testng', 'apache-commons', 'apache-commons-compress']",188,False,1,0
Unit testing async function with callback,"<p>Trying to write unit tests for reading a json file with the readFile function however I get the error: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout. I must be doing something wrong when mocking the json file.</p>

<p>The function:</p>

<pre><code>function jsonReader(filePath, cb) {
  fs.readFile(filePath, (err, fileData) =&gt; {
    if (err) {
      return cb &amp;&amp; cb(err);
    }
    try {
      const object = JSON.parse(fileData);
      return object;
    } catch (err) {
      return cb &amp;&amp; cb(err);
    }
  });
}
module.exports = jsonReader;
</code></pre>

<p>Then the testfile:</p>

<pre><code>const jsonReader = require('.././ReadJson');
jest.mock('fs', () =&gt; {
  const MOCK_FILE_INFO = { 'test.json': JSON.stringify({ name: 'myname' }) };
  return {
    readFile: (fpath, opts) =&gt; {
      if (fpath in MOCK_FILE_INFO) {
        return MOCK_FILE_INFO[fpath];
      }
    }
  };
});


test('Test file', (done) =&gt; {
  function callback(data) {
    expect(data.name).toBe('myname');
    done();
  }

  jsonReader('test.json', callback);
});
</code></pre>

<p>I tried to change the timeout but if I put it higher the execution also takes longer and it's still giving the same error. </p>
",https://stackoverflow.com/questions/57559591/unit-testing-async-function-with-callback,"['javascript', 'node.js', 'jestjs']",513,True,1,1
Best practice for unit testing gRPC,"<p>is this a best practice while performing integration tests on the gRPC services? i.e. opening and closing channels after each unit test using annotations @BeforeEach and @AfterEach</p>

<pre><code>private ManagedChannel channel;

private DepartmentServiceGrpc.DepartmentServiceBlockingStub deptService;

@BeforeEach
public void initEach(){
    channel = ManagedChannelBuilder.forAddress(""localhost"", 8080)
            .usePlaintext()
            .build();

    deptService = DeptServiceGrpc.newBlockingStub(channel);
}

@AfterEach
public void cleanUpEach(){
    channel.shutdown();
}
</code></pre>
",https://stackoverflow.com/questions/57502996/best-practice-for-unit-testing-grpc,"['java', 'junit5', 'grpc-java']",3481,True,1,2
Unit Testing and Continuation-Local Storage,"<p>I would like to harness CLS (continuation-local storage) in my TypeScript app so that I have somewhere I can put metadata (e.g. user ID, request ID) for various uses (e.g. logging) without having to pass the data in each method call.</p>

<p>I have attempted to use both <a href=""https://www.npmjs.com/package/cls-hooked"" rel=""nofollow noreferrer"">cls-hooked</a> and <a href=""https://www.npmjs.com/package/async-local-storage"" rel=""nofollow noreferrer"">async-local-storage</a>. However, I haven't been able to get either working from my Jest unit test.</p>

<pre class=""lang-js prettyprint-override""><code>const als = require('async-local-storage');
als.enable();

// ... some code

describe('Authorization tests', () =&gt; {
  test('Cannot call without correct scope', () =&gt; {
    als.set('id', ""123123123123"");
    expect(() =&gt; service.registerApp(ctxt, app)).toThrowError(AuthorizationError.NOT_AUTHORIZED);
  });
});
</code></pre>

<p>The above setting of the datum <code>id</code> does not fail.</p>

<pre class=""lang-js prettyprint-override""><code>export function authorize(requiredPermissions: string[]) {
    return (target: any, name: any, descriptor: any) =&gt; {
        const protectedFunction = descriptor.value;
        const als = require('async-local-storage');
        console.log(`&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;My ID ${als.get('id')}`);

        // ... some code
    }
}
</code></pre>

<p>However the above code simply outputs:</p>

<pre><code>&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;My ID null
</code></pre>

<p>Is what I'm attempting possible? Thanks in advance.</p>
",https://stackoverflow.com/questions/55024423/unit-testing-and-continuation-local-storage,"['javascript', 'node.js', 'typescript', 'jestjs']",882,True,0,2
How to run Vue unit testing?,"<p>I'm following this tutorial to implement Vue unit test: <a href=""https://v2.vuejs.org/v2/cookbook/unit-testing-vue-components.html"" rel=""nofollow noreferrer"">https://v2.vuejs.org/v2/cookbook/unit-testing-vue-components.html</a></p>
<p>However, after creating a component and a test component, I have no idea how to actually run the test. My test file is located in test/unit/myfirsttest.spec.js. Do I need to run a command or configure something?</p>
<p>Thanks so much in advance,</p>
",https://stackoverflow.com/questions/56729231/how-to-run-vue-unit-testing,"['unit-testing', 'vue.js']",91,False,0,0
Controlling defined values during unit testing,"<p>I would like to know if it's possible to change an included header with a set of defined values as preprocessor directives for another one during testing.</p>

<p>I have a set of values defined in a header</p>

<pre><code>//Accelconfig.h
#define sampling_rate 1 // It can be 1, 10 or 25

#ifndef accel_sample_rate
    #define accel_sample_rate 25 //default sampling 25Hz
#endif
#if accel_sample_rate == 1
    #define sampleRateBits LIS2DH12_BITS_ODR_1HZ
#elif accel_sample_rate == 10
    #define sampleRateBits LIS2DH12_BITS_ODR_10HZ
#elif accel_sample_rate == 25
    #define sampleRateBits LIS2DH12_BITS_ODR_25HZ
#else
    #define sampleRateBits LIS2DH12_BITS_ODR_25HZ //default if invalid parameter
#endif
</code></pre>

<p>That I use to do some calculations, like the dataset duration based on the number of samples and the sample duration. Currently, it's set to 1, but will be changed to other values later on.</p>

<p>I'm unit testing a function (with unity / ceedling) that does one of such calculations, and I would need to test a corner case that requires the value to be more than 1, but I don't want to change the value in the header and I would prefer to avoid <code>#ifdef TEST</code> clauses, as they don't provide much more control either. I was wondering if there's a way to change the header for another one <code>accel_config_test.h</code> that can have its values changed dynamically from the test.</p>
",https://stackoverflow.com/questions/57522756/controlling-defined-values-during-unit-testing,"['c', 'unit-testing', 'c-preprocessor']",1238,True,0,4
Unit testing for Google Cloud Functions,"<p>I was trying to write unit testing for Google Cloud Functions referring to Google Cloud Platform unit testing docs but not able to understand how to mock when Google Cloud Storage is used. Below is sample code for which I am trying to write unit testing :</p>

<pre><code>exports.listFiles = async(req, res) =&gt; {
  let bucketName = req.body.bucket || req.query.bucket

  // Import the Google Cloud Storage library
  const {Storage} = require('@google-cloud/storage');

  // Initiate a Storage client
  const storage = new Storage();

  // List files in the bucket and store their name in the array called 'result'
  const [files] = await storage.bucket(bucketName).getFiles();
  let result = [];
  files.forEach(file =&gt; {
    result.push(file.name);
  });

  // Send the result upon a successful request
  res.status(200).send(result);
};
</code></pre>
",https://stackoverflow.com/questions/59283121/unit-testing-for-google-cloud-functions,"['google-cloud-platform', 'google-cloud-functions', 'mocha.js', 'chai', 'sinon']",2004,True,0,3
how to Unit testing eShopOnContainer (IntegrationEventsLog ),"<p>This question is specifically related to the eshoponcontainers <a href=""https://github.com/dotnet-architecture/eShopOnContainers"" rel=""nofollow noreferrer"">https://github.com/dotnet-architecture/eShopOnContainers</a> , and more specifically the IntegrationEvengLog service.</p>

<p>I have the following class that I needed mocked and passed to </p>

<pre><code>IEventsContextIntegrationEventService integrationService = NEEDS MOCKING;
var handler = new CreateCoinCommandHandler(context, mapper, integrationService);`
</code></pre>

<p>I already mocked the <code>context</code> with an in-memory dbcontext, mapper is already taken care of, the only param i need is the <code>integrationService</code> which also takes in <code>context</code> and it has its own dbcontext that needs to be mocked.</p>

<p>Here is my integration service class that I do not know how to mock properly (prefer using a in-memory like i do for `context.</p>

<p>I am sorry for the vagueness but not sure how else to put it</p>

<pre><code>public class EventsContextIntegrationEventService: IEventsContextIntegrationEventService
{
    private readonly Func&lt;DbConnection, IIntegrationEventLogService&gt; integrationEventLogServiceFactory;
    private readonly IEventBus eventBus;
    private readonly EventsContext context;
    private readonly IIntegrationEventLogService eventLogService;

    public EventsContextIntegrationEventService(IEventBus eventBus, EventsContext context,
    Func&lt;DbConnection, IIntegrationEventLogService&gt; integrationEventLogServiceFactory)
    {
        this.context = context ?? throw new ArgumentNullException(nameof(context));
        this.integrationEventLogServiceFactory = integrationEventLogServiceFactory ?? throw new ArgumentNullException(nameof(integrationEventLogServiceFactory));
        this.eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus));
        eventLogService = this.integrationEventLogServiceFactory(this.context.Database.GetDbConnection());
    }

    public async Task PublishThroughEventBusAsync(IntegrationEvent evt)
    {
        try
        {
            await eventLogService.MarkEventAsInProgressAsync(evt.Id);
            eventBus.Publish(evt);
            await eventLogService.MarkEventAsPublishedAsync(evt.Id);
        }
        catch (Exception)
        {
            await eventLogService.MarkEventAsFailedAsync(evt.Id);
        }
    }

    public async Task SaveIntegrationEventAndEventContextChangesAsync(IntegrationEvent evt)
    {
        //Use of an EF Core resiliency strategy when using multiple DbContexts within an explicit BeginTransaction():
        //See: https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency            
        await ResilientTransaction.New(context)
            .ExecuteAsync(async () =&gt; {
                // Achieving atomicity between original catalog database operation and the IntegrationEventLog thanks to a local transaction
                await context.SaveChangesAsync();
                await eventLogService.SaveEventAsync(evt, context.Database.CurrentTransaction.GetDbTransaction());
            });
    }
}
</code></pre>
",https://stackoverflow.com/questions/54596984/how-to-unit-testing-eshoponcontainer-integrationeventslog,"['.net', 'asp.net-core', 'microservices']",134,False,0,0
Javascript unit testing a simple file,"<p>I have a simple app that I am trying to write a unit test for. I want to unit test the help button in the sample code below to make sure the loading status becomes an empty string. However, I cannot figure out how to get a fake DOM working. I have tried jsdom, jsdomifiy, jsdom-global, etc. I always end up with appStatus being undefined, then I can't set the innerHTML property. I am trying to use karma and mocha, but if there is a better way please let me know. I don't really have a package.json to share because I have tried so many things.</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>var appStatus = document.getElementById('appStatus');
appStatus.innerHTML = 'Loading your app...';


function help() {
console.log('help clicked');
appStatus.innerHTML = '';
}</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;App&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;span id=""appStatus""&gt;&lt;/span&gt;
    &lt;button onclick=""help()""&gt;Help&lt;/button&gt;
  &lt;/body&gt;
&lt;/html&gt;</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/58239377/javascript-unit-testing-a-simple-file,"['javascript', 'html', 'unit-testing', 'jsdom']",90,False,0,0
Unit Testing with Mockery return false,"<p>I have written this test :</p>

<pre><code>public function testSetVisitorLog()
{
    $visitorRepositoryMock = Mockery::mock('App\Repositories\VisitorStatisticRepository');
    $this-&gt;app-&gt;instance('App\Repositories\VisitorStatisticRepository',$visitorRepositoryMock);
    $visitorRepositoryMock-&gt;shouldReceive('setLog')-&gt;once();

    $visitorAction = new VisitorStatisticAction($visitorRepositoryMock);
    $this-&gt;assertEquals(true,$visitorAction-&gt;setLog('fars'));
}
</code></pre>

<p>I call setLog in VisitorStatisticAction class with an string input </p>

<p>in VisitorStatisticAction i have this :</p>

<pre><code>public function setLog($organizationSlug)
{
    dd($this-&gt;repository-&gt;setLog($organizationSlug));
    if (!$this-&gt;repository-&gt;setLog($organizationSlug)) {
        return false;
    }
    return true;
}
</code></pre>

<p>I don't know why <code>dd($this-&gt;repository-&gt;setLog($organizationSlug));</code> is return <strong>null</strong></p>

<p>setLog in repository is this :</p>

<pre><code>public function setLog($organizationSlug)
{
    $visitor = new VisitorStatistic();
    $visitor-&gt;organization_slug = $organizationSlug;
    $visitor-&gt;ip = request()-&gt;ip();
    $visitor-&gt;url = url()-&gt;current();
    $visitor-&gt;save();
    return $visitor;
}
</code></pre>
",https://stackoverflow.com/questions/55122296/unit-testing-with-mockery-return-false,"['laravel', 'unit-testing', 'testing', 'mockery']",43,True,0,1
unit testing covering the branch case,"<p>I am trying write unit test for below .js using mocha</p>

<pre><code>const fs = require('fs')
const defaultValue = 255

const envValue = process.env.Var1Value
const valueToUse = envValue &amp;&amp; !isNaN(envValue) ? parseInt(envValue) : defaultValue

module.exports.MyFun = () =&gt; {
  //use the value of 'valueToUse'
}
</code></pre>

<p>In my unit testing, I am trying to cover the cases for ""valueToUse"" both from environment and from default value.
I trying to understand how can cover both the scenarios for unit testing. If I set the process.env.Var1Value before loading the module (using require) it covers the first scenario, but not the other case and in reverse if I don't set the env variable it cover the other case, as the module is being loaded only once... how shall I have an unit test that covers both the scenario?  Thanks in advance!</p>
",https://stackoverflow.com/questions/55013051/unit-testing-covering-the-branch-case,"['node.js', 'unit-testing', 'mocha.js']",128,True,0,1
Angular 1.5 ngMaterial Karma Unit testing,"<p>I have introduced ngMaterial in our app using AngularJS 1.5 version. Everything looks good but karma test case fails with message </p>

<blockquote>
  <p>""Error: [$injector:nomod] Module 'ngMaterial' is not available! You either misspelled the module name or forgot to load it.""</p>
</blockquote>

<p>Below is my code. Can someone please help with this error.</p>

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

  var myComponentComponent = {
    templateUrl: 'app/myComp/myComp.html',
    controller: myComponentController,
    controllerAs: 'vm'
  };

  /* @ngInject */
  function myComponentController($sce, $templateCache, viewport) {
    var vm = this;

  }

  angular.module('core', ['ngMaterial', 'ngMessages'])
    .component('myComponent', myComponentComponent);

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

<hr>

<pre><code>describe('testCore', function () {
  beforeEach(module('core'));
  beforeEach(module('ngMaterial'));
  beforeEach(module('ngMessages'));

  var $window;
  var $componentController;
  var scope;
  var $rootScope;
  var controller;

  beforeEach(inject(function (_$window_, _$componentController_, _$rootScope_) {
    $window = _$window_;
    $componentController = _$componentController_;
    $rootScope = _$rootScope_;
    scope = $rootScope.$new();
    controller = $componentController('myComponent', null, scope.mockData);
    scope.$apply();
  }));



  it('should initialize component', function () {

  });


});
</code></pre>
",https://stackoverflow.com/questions/58772861/angular-1-5-ngmaterial-karma-unit-testing,"['angularjs', 'karma-jasmine', 'angularjs-material']",65,False,0,0
Unit testing with flutter scoped model,"<p>Developing an app I end up with some logic in my scoped model. My search does not show any examples on unit testing. Does anyone have an experience with in writing a test for scoped model? How can I mock lifecycle of the scoped model?</p>
",https://stackoverflow.com/questions/55170613/unit-testing-with-flutter-scoped-model,"['unit-testing', 'flutter', 'scoped-model']",503,False,-1,1
Unit Testing an Xml format function,"<p>I'm trying to create a unit test for <code>xml.Format</code> function, but I can't seem to acquire <code>customerName</code> value, I don't know what I am doing wrong here. Please enlighten me.</p>

<pre><code>[Test]
        public async System.Threading.Tasks.Task Format()
        {
            var script = ""var xml = $Xml.Parse('&lt;Customer&gt;&lt;Name&gt;John&lt;/Name&gt;&lt;/Customer&gt;');  $Probe.SetValue('a', xml.Format('&lt;p&gt;Hello {{Customer/Name}}!&lt;/p&gt;') + '');"";
            var probe = await this.SaveProcessAsync("""", script, """");

            // ensure our proxy is called
            Assert.AreEqual(""&lt;p&gt;Hello John!&lt;/p&gt;"", probe.GetValue(""a""));
        }
</code></pre>

<p>This is NUnit output,</p>

<p>Expected: <code>Hello John!</code></p>

<p>But was: <code>""Hello !""</code></p>
",https://stackoverflow.com/questions/59262273/unit-testing-an-xml-format-function,"['c#', 'xml', 'unit-testing', 'xml-parsing', 'nunit']",35,True,-1,1
NUnit Unit Testing which involves dbcontext,"<p>I have the code below, which is now testable. The problem is when it reaches the Entity Framework (EF) related code, it kinda hangs there (infinite loop). I think my interim solution is to comment out my EF related code. </p>

<p>I understand that to test EF, I might need thing like MOQ or integration testing which I plan to come out with later on. Meanwhile, how do I 'split' out all this EF code, so that I can perform NUnit testing for other testable code? Here is one of the methods I have:</p>

<pre><code>public void PlaceDeposit(BankAccount account, decimal _transaction_amt)
{   

    if (_transaction_amt &lt;= 0)               
        _msgPrinter.PrintMessage(""Amount needs to be more than zero. Try again."", false);
    else if (_transaction_amt % 10 != 0)
        _msgPrinter.PrintMessage($""Key in the deposit amount only with multiply of 10. Try again."", false);
    else if (!PreviewBankNotesCount(_transaction_amt))
        _msgPrinter.PrintMessage($""You have cancelled your action."", false);
    else
    {
        var transaction = new Transaction()
        {
            AccountID = account.Id,
            BankAccountNoTo = account.AccountNumber,
            TransactionType = TransactionType.Deposit,
            TransactionAmount = _transaction_amt,
            TransactionDate = DateTime.Now
        };
        repoTransaction.InsertTransaction(transaction);
        // Add transaction record - End

        account.Balance = account.Balance + _transaction_amt;

        ctx.SaveChanges();

        _msgPrinter.PrintMessage($""You have successfully deposited {Utility.FormatAmount(_transaction_amt)}"", true);
    }
}
</code></pre>

<p>I have this test method in NUnit, which works fine:</p>

<pre><code>[TestCase(""Amount needs to be more than zero. Try again."",0)]
[TestCase(""Amount needs to be more than zero. Try again."",-1)]
[TestCase(""Key in the deposit amount only with multiply of 10. Try again."", 1)]
[TestCase(""Key in the deposit amount only with multiply of 10. Try again."", 5)]
public void ShowErrorMessage_OnPlaceDeposit(string expectedMessage, decimal transactionAmount)
{
    // Arrange - Start
    var mock = new MockMessagePrinter();

    MeybankATM atmCustomer = new MeybankATM(new RepoBankAccount(), new RepoTransaction(), mock);

    BankAccount bankAccount = new BankAccount()
    {
        FullName = ""John"",
        AccountNumber = 333111,
        CardNumber = 123,
        PinCode = 111111,
        Balance = 2000.00m,
        isLocked = false
    };
    // Arrange - End

    // Act
    atmCustomer.PlaceDeposit(bankAccount, transactionAmount);

    // Assert                       
    Assert.AreEqual(expectedMessage, mock.Message);
}
</code></pre>

<p>Now, all I have I left is to test the balance update part:</p>

<pre><code>account.Balance = account.Balance + _transaction_amt;
</code></pre>
",https://stackoverflow.com/questions/55104971/nunit-unit-testing-which-involves-dbcontext,"['c#', 'nunit']",400,False,0,0
Android unit testing Location not mocked,"<p>I am trying to test my presenter and I need a mocked location, however, I get null or have default values such as 0.0 for lat, long, bearing and so on</p>

<p>I have already tried creating a new Location object and initializing all the fields I need.</p>

<pre><code>    val latitude = 37.422
    val longitude = -122.084

    val mockLocation = mock(Location::class.java)
    mockLocation.latitude = latitude
    mockLocation.longitude = longitude

    presenter.loadsAirpots(latitude, longitude)
    presenter.locationChanged(mockLocation)

    System.out.println(mockLocation.latitude)
</code></pre>

<p>I expect latitude to be 37.422 but the actual output is 0.0</p>
",https://stackoverflow.com/questions/56343940/android-unit-testing-location-not-mocked,"['android', 'unit-testing', 'kotlin', 'mockito', 'location']",1147,True,0,1
Symfony 4.2 unit testing wont works,"<p>I am doing unit testing / functional testing, but my code gives me an error. Kindly have a look on my code and suggest a solution.</p>

<p>Codes On Controller</p>

<pre><code>    &lt;?php

namespace App\Controller;


use App\Entity\Organization;
use App\Entity\User;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Psr\Log\LoggerInterface;
use Swift_Mailer;
use Swift_Message;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class RegisterController extends AbstractController
{

    protected $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this-&gt;logger = $logger;
    }

    /**
     * Validate the data
     * Encodes the password
     * Creates new organization if evaplyId does not exists
     * Create user and send verification email.
     * return status
     *
     * @param Request $request
     * @param UserPasswordEncoderInterface $userPasswordEncoder
     * @param ValidatorInterface $validator
     * @param Swift_Mailer $mailer
     * @return Response
     */
    public function register(Request $request, UserPasswordEncoderInterface $userPasswordEncoder, ValidatorInterface $validator, Swift_Mailer $mailer)
    {
        try {
            $form = $request-&gt;getContent();
            $form = json_decode($form);
            $entityManager = $this-&gt;getDoctrine()-&gt;getManager(); //doctrine manager for entity managing
            $user = new User();
            $user-&gt;setEmail($form-&gt;email);
            if (!$this-&gt;checkEmail($form-&gt;email)) {
                return new JsonResponse(['status' =&gt; false, 'message' =&gt; 'Email already exists']);
            }
            $user-&gt;setFirstName($form-&gt;first_name);
            $user-&gt;setLastName($form-&gt;last_name);
            $user-&gt;setPassword($form-&gt;plain_password);
            if (!$form-&gt;evaply_id) {
                if(!$form-&gt;organization_name)
                    return new JsonResponse(['status' =&gt; false, 'message' =&gt; 'Missing field Organization']);
                $organization = new Organization();
                $organization-&gt;setName($form-&gt;organization_name);
                $startGuideStatus['status'] = false;
                $startGuideStatus['add_company'] = false;
                $startGuideStatus['first_connection'] = false;
                $startGuideStatus['first_scorecard'] = false;
                $startGuideStatus['first_order'] = false;
                $organization-&gt;setStartGuideStatus(($startGuideStatus));
                $organization-&gt;setCustOrSupplier($form-&gt;cust_or_supplier);
                $evaply_id = $this-&gt;generateEvaplyId($form-&gt;organization_name);
                $organization-&gt;setEvaplyId($evaply_id);
                $entityManager-&gt;persist($organization);
                $entityManager-&gt;flush();
            } else {
                $organization = $this-&gt;getDoctrine()-&gt;getRepository(Organization::class)-&gt;findOneBy(array('evaplyId' =&gt; $form-&gt;evaply_id));
                if (!$organization) {
                    return new JsonResponse(['status' =&gt; false, 'message' =&gt; 'Invalid Evaply ID']);
                }
            }
            $user-&gt;setOrganization($organization);
            $user-&gt;setUuid($this-&gt;generateUUID());
            $user-&gt;setRoles(['Admin']);
            $error = $validator-&gt;validate($user);
            if (count($error) &gt; 0) {
                return new JsonResponse(['status' =&gt; false, 'message' =&gt; 'Validation error']);
            }
            if ($form-&gt;plain_password != $form-&gt;confirm_password) {
                return new JsonResponse(['status' =&gt; false, 'message' =&gt; 'Password miss match']);
            }
            $user-&gt;setPassword(
                $userPasswordEncoder-&gt;encodePassword(
                    $user,
                    $form-&gt;plain_password
                )
            );
            $token = $this-&gt;generateVerificationToken($user);
            $this-&gt;logger-&gt;info($token);
            $verificationUrl = $this-&gt;getParameter('app_url') . ""account/verify/"" . $token;
            $entityManager = $this-&gt;getDoctrine()-&gt;getManager();
            $entityManager-&gt;persist($user);
            $entityManager-&gt;flush();
            $this-&gt;sendUserRegisteredMail($user, $verificationUrl, $mailer);

            return new JsonResponse(['status' =&gt; true, 'message' =&gt; ""Successfully registered""]);
        } catch (\Exception $e) {
            $this-&gt;logger-&gt;error($e-&gt;getMessage());
            return new Response($e-&gt;getMessage());
        }
    }

    /**
     * Check email duplication in database
     *
     * @param $email
     * @return bool
     */
    public function checkEmail($email)
    {
        $user = $this-&gt;getDoctrine()-&gt;getRepository(User::class)-&gt;findOneBy(array('email' =&gt; $email));
        if ($user)
            return false;
        else
            return true;
    }

    /**
     * Generate a unique id using organization name and timestamp
     *
     * @param $orgName
     * @return string
     */
    public function generateEvaplyId($orgName)
    {
        $org = strtoupper(substr($orgName, 0, 3));
        $dateTime = time();
        $evaply_id = $org . $dateTime;
        return $evaply_id;
    }

    /**
     * Generate unique uuid for user
     * Recursive function
     *
     * @return int
     */
    public function generateUUID()
    {
        $uuid = rand(1000000000, 9999999999);
        $user = $this-&gt;getDoctrine()-&gt;getRepository(User::class)-&gt;findOneBy(array('uuid' =&gt; $uuid));
        if ($user) {
            return $this-&gt;generateUUID();
        } else {
            return $uuid;
        }
    }

    /**
     * Send email to user after a successfull registartion.
     *
     * @param User $user
     * @param Swift_Mailer $mailer
     * @return int
     */
    public function sendUserRegisteredMail(User $user, $verificationUrl, Swift_Mailer $mailer)
    {
        $message = (new Swift_Message(""Successfully Registered""))
            -&gt;setFrom('admin@evaply.com')
            -&gt;setTo($user-&gt;getEmail())
            -&gt;setBody(
                $this-&gt;renderView(
                    'emails/registration.html.twig',
                    array('firstName' =&gt; $user-&gt;getFirstName(), 'lastName' =&gt; $user-&gt;getLastName(), 'verificationUrl' =&gt; $verificationUrl)
                ),
                'text/html'
            );
        return $mailer-&gt;send($message);
    }

    /**
     * Generates a verification token using aes-128-gcm encryption
     * encrypts email and uuid
     * encode ciphertext with base64 encoder
     *
     * @param User $user
     * @return string
     */
    public function generateVerificationToken(User $user)
    {
        $data = array();
        $data['email'] = $user-&gt;getEmail();
        $data['uuid'] = $user-&gt;getUuid();
        $plaintext = json_encode($data);
        $cipher = $this-&gt;getParameter('cipher');
        if (in_array($cipher, openssl_get_cipher_methods())) {

            $this-&gt;logger-&gt;info(""inside cipher"");
            //$ivlen = openssl_cipher_iv_length($cipher);
            $iv = $this-&gt;getParameter('secretIV');
            $key = $this-&gt;getParameter('cipher_key');
            //$tag = $this-&gt;getParameter('tagg');
            $ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options = 0, $iv);
            $original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options = 0, $iv);
            return $token = base64_encode($ciphertext);
        }
    }
}
</code></pre>

<p>Codes On Tests/Controller Folder</p>

<pre><code>   &lt;?php
/**
 * Created by PhpStorm.
 * User: xavier-phases
 * Date: 22/1/19
 * Time: 5:09 PM
 */

namespace App\Tests\Controller;
use App\Controller\RegisterController;
use PHPUnit\Framework\TestCase;

class EvaplyTest extends TestCase
{

    public function testGenerate_evaply_clid(LoggerInterface $logger)
    {
        $id= new RegisterController();
        $org_name=$id-&gt;generateEvaplyId('Tset');
        $org = strtoupper(substr($org_name, 0, 3));
        $dateTime = time();
        $evaply_id = $org . $dateTime;
        return $evaply_id;
    }
}`
</code></pre>

<p>I am calling the <code>generateEvaplyId()</code> method from the register controller. I have installed all test packages. It gives me the following error:</p>

<pre><code>""ArgumentCountError: Too few arguments to function App\Tests\Controller\EvaplyTest::testGenerate_evaply_clid(), 0 passed and exactly 1 expected"".  KIndly have a look and suggest me a solution.
</code></pre>
",https://stackoverflow.com/questions/54320076/symfony-4-2-unit-testing-wont-works,"['php', 'unit-testing', 'symfony', 'functional-testing']",1008,True,-2,1
Unit testing with aws-cdk typescript,"<p>I am very new to aws-cdk and have created a stack to which consists of a kinesis firehose , elastic search , lambda , S3 bucket and a few roles as per requirement. Now I want to test my code locally. I was able to get a few samples but they don't have clearly mentioned how to run the unit test cases</p>

<pre><code>module.exports = {
    'default bucket'(test) {
        const stack = new cdk.Stack();
        new s3.Bucket(stack, 'MyBucket');
        assert_1.expect(stack).toMatch({
            ""Resources"": {
                ""MyBucketF68F3FF0"": {
                    ""Type"": ""AWS::S3::Bucket"",
                    ""DeletionPolicy"": ""Retain"",
                    ""UpdateReplacePolicy"": ""Retain"",
                }
            }
        });
        test.done();
    }
};
</code></pre>

<p>It would be great if I could get a proper example of how to run a unit test using aws-cdk</p>
",https://stackoverflow.com/questions/57477206/unit-testing-with-aws-cdk-typescript,"['typescript', 'unit-testing', 'aws-cdk']",2230,True,0,1
Unit Testing failing with kotlin IllegalStateException,"<p>I'm trying to verify that when I call my createUser interactor in my presenter, a user is created into Firebase. </p>

<p>To do this I simply implemented this test case</p>

<h2>RegisterTest.class</h2>

<pre><code>    @Captor
    var callbackCaptor: ArgumentCaptor&lt;RegisterInteractor.RegisterCallBack&gt;? = null

    @Mock
    lateinit var view: RegisterContract.View

    @Mock
    lateinit var interactor: RegisterInteractor
    lateinit var presenter: RegisterPresenter


    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
        presenter = RegisterPresenter(interactor)
        presenter.attachView(view)
    }

    @Test
        fun should_SignUpUser(){
            //give
            presenter.signUp(""testUser"",""testEmail@gmail.com"",""123456"")
            //when
            verify(interactor).createUserWithEmailAndPassword(""testUser"",""testEmail@gmail.com"",""123456"", callbackCaptor!!.capture())
            callbackCaptor?.value?.onRegistrationSucces()
            //then
            verify(view).navigateToMain()
        }
</code></pre>

<h2>RegisterInteractor Callback</h2>

<pre><code>interface RegisterInteractor {

    interface RegisterCallBack {
        fun onRegistrationSucces()
        fun onRegistrationFailure(errorMsg:String)
    }

    fun createUserWithEmailAndPassword(fullName:String,email:String,password:String,listener:RegisterCallBack)
}
</code></pre>

<h2>RegisterPresenter</h2>

<p>Here is where I call the signUp method to test</p>

<pre><code> override fun signUp(fullName:String, email: String, password: String) {
        view?.showProgress()
        registerInteractor?.createUserWithEmailAndPassword(fullName,email, password, object : RegisterInteractor.RegisterCallBack {

                override fun onRegistrationSucces() {
                    if(isViewAttached()){
                        view?.navigateToLogin()
                        view?.hideProgress()
                    }
                }

                override fun onRegistrationFailure(errorMsg:String) {
                    if(isViewAttached()){
                        view?.showError(errorMsg)
                        view?.hideProgress()
                    }
                }

            })
    }
</code></pre>

<h2>RegisterInteractorImpl</h2>

<pre><code>  override fun createUserWithEmailAndPassword(fullName:String,email:String,password:String,listener: RegisterInteractor.RegisterCallBack){
        FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener { task -&gt;
                if (task.isSuccessful) {
                    // Sign in success, set full name and navigate to main.
                    val user = FirebaseAuth.getInstance().currentUser
                    val profileUpdates = UserProfileChangeRequest.Builder()
                        .setDisplayName(fullName)
                        .build()

                    // Checks if the user is already in the database, if not, it will write it and go to the main activity
                    user?.updateProfile(profileUpdates)
                        ?.addOnCompleteListener { updateTask -&gt;
                            if (updateTask.isSuccessful) {
                                userRepository.createUser(fullName,email,object : UserRepository.UserRepositoryCallback{

                                    override fun onRemoteSuccess() {
                                        listener.onRegistrationSucces()
                                    }

                                    override fun onRemoteFailure(errormsg:String) {
                                        // Since the task is the one who decides if an user is created or not by checking if the email is not duplicated, this callback has no effect on saving a call to Firestore
                                    }
                                })

                            }
                        }

                } else {
                    listener.onRegistrationFailure(task.exception?.message!!)
                }
            }
    }
</code></pre>

<p>And I'm getting a <strong>IllegalStateException</strong> when executing my test, this is the following message I receive</p>

<blockquote>
  <p>java.lang.IllegalStateException: callbackCaptor!!.capture() must not
  be null</p>
  
  <p>at
  com.logintest.presentation.register.presenter.RegisterPresenterTest.should_SignUpUser(RegisterPresenterTest.kt:123)
    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.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)</p>
</blockquote>

<p>And the line it refers the error is on the test</p>

<pre><code>verify(interactor).createUserWithEmailAndPassword(""userTest"",""userEmail@gmail.com"",""123456"", callbackCaptor!!.capture())
</code></pre>

<p>Where is this error coming from ?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/55908353/unit-testing-failing-with-kotlin-illegalstateexception,"['android', 'unit-testing', 'kotlin']",576,False,0,0
DB unit testing for View object?,"<p>Is the possible or is it in practice to create db unit test cases for View objects?</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/55469426/db-unit-testing-for-view-object,"['sql', 'sql-server', 'unit-testing', 'msdn']",42,False,0,1
Scheduler works incorrect in unit testing,"<p>I need to collect data from a public API. I want to collect it daily or twice a day.</p>

<pre class=""lang-java prettyprint-override""><code>public class AlphavantageStockRequestDispatcher {
    public static void startAlphavantageStockScraper(int timeInterval) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        Runnable getStockList =
                new Runnable() {
                    @Override
                    public void run() {
                        List&lt;AlphavantageStock&gt; stocks = AlphavantageStockRequest.getStockPrices(); //Method contains requests

                        StockDao&lt;AlphavantageStock&gt; dao = new JpaAlphavantageStockDao();

                        for (AlphavantageStock stock : stocks) {
                            dao.save(stock);
                        }
                    }
                };

        scheduler.scheduleAtFixedRate(getStockList, 0, timeInterval, TimeUnit.HOURS);
    }
}
</code></pre>

<p>The problem is when I start it from the same class (just added main method and invoked <code>startAlphavantageStockScraper(1);</code> it works fine. But when I want to test it via JUnit it's not working (test class is in symmetric package name but <code>test</code> subfolder):</p>

<pre class=""lang-java prettyprint-override""><code>public class AlphavantageStockRequestDispatcherTest {
    @Test
    public void startDispatcher_TwoFullCycles_WithOneHourIntervalBetween() {
        AlphavantageStockRequestDispatcher.startAlphavantageStockScraper(1);
    }
}
</code></pre>

<p>While debugging I found out that in unit test execution a program reaches <code>public void run()</code> line then skips it. So there's no error. Program ends up correctly but does nothing useful.</p>

<p>Any help will be appreciated.</p>
",https://stackoverflow.com/questions/58901086/scheduler-works-incorrect-in-unit-testing,"['java', 'multithreading', 'junit', 'scheduled-tasks', 'runnable']",254,True,0,1
ts-jest trouble with unit testing,"<p>Trying to unit test firebase cloud functions using <code>ts-jest</code>, but having trouble with a simple test. </p>

<p>I've installed jest for typescript, typings, and ts-jest config but I'm getting an error that says <code>@types/jest</code> isn't installed.</p>

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

<pre><code>/// &lt;reference types=""jest"" /&gt;

import { database } from '../src/firestore';

test('Firestore is initialized', () =&gt; {
    expect(database).toBeDefined();
});
</code></pre>

<p><strong>error message:</strong> Cannot find name 'test'. Do you need to install type definitions for a test runner? Try <code>npm i @types/jest</code> or <code>npm i @types/mocha</code>.ts(2582)</p>

<p><strong>version:</strong> <code>@types/jest@24.0.19</code></p>
",https://stackoverflow.com/questions/58540931/ts-jest-trouble-with-unit-testing,"['typescript', 'ionic-framework', 'google-cloud-functions', 'ts-jest']",4865,False,0,1
unit testing for Controller&#39;s index function,"<p>This is my function :</p>

<pre><code>public function index(Request $request)
{
    $data = User::all();
    return view('data.index',[
        'data' =&gt; $data
    ]);
}
</code></pre>

<p>I write a test for this</p>

<pre><code>public function testIndex()
{
   $response = $this-&gt;call('GET', '/data');

   $this-&gt;assertEquals(200, $response-&gt;status());
}
</code></pre>

<p>but not works. Show redirection</p>

<pre><code>Response status code [302] is not a successful status code.
Failed asserting that false is true.
</code></pre>

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

<pre><code>Route::group(['prefix' =&gt; 'data'], function() {
    Route::get('/', ['as' =&gt; 'data.index', 'uses' =&gt; 'DataController@index']);
});
</code></pre>

<p>I tried everything but still showing the same thing.</p>
",https://stackoverflow.com/questions/55487749/unit-testing-for-controllers-index-function,['laravel'],201,False,0,1
Unit testing and factories for mocks,"<p>Suppose I have a class C that I need to test. Part of it's job is to create a number of other non-trivial class objects (each of which have their own business logic) and call various methods on these new objects. I want to be able to test class C without testing the implementation of those other objects that C creates. Is the only real solution to create a factory which creates those non-trivial objects, and then pass in a mocked factory instance into the test? I don't want to have a single factory to create those other non-trivial objects, but on the other hand I don't want to have a factory per non-trivial class.</p>

<p>Any other suggestions?</p>

<p>Edit: added some pseudo code as requested</p>

<pre><code>public B doIt()
{
  List&lt;A&gt; as = getListOfAsFromDatabase();
  AParser AParser = new AParser();
  boolean foo = aParser.parse(as); // may modify the list of A's
  B b = new B();
  return b.add(foo, as);
}
</code></pre>
",https://stackoverflow.com/questions/58884484/unit-testing-and-factories-for-mocks,"['java', 'unit-testing', 'mocking']",158,False,0,1
Unit testing XSLT files in pycharm,"<p>I wrote several xslt files. Within each file, I have multiple templates to modify strings, so I am trying to find a way to create unit tests for these templates. Is there is a way to test xslt files in PyCharm with pytest?</p>
",https://stackoverflow.com/questions/58737917/unit-testing-xslt-files-in-pycharm,"['python', 'unit-testing', 'xslt', 'pycharm', 'pytest']",84,True,0,1
Unit testing: toString method. Possible override?,"<p>My professor gave us this homework exercise and has created a project with a bunch of unit tests. Our goal is to make sure we can pass those unit tests. We have two classes. A class called Building, that has a name, a minimum floor and a max floor and a class Room, that has a building, a name and a floor. I do not understand one of the test cases and how to make sure my program passes it.</p>

<p>I have already created the class building and room with its getters and setters. </p>

<p>This is the test our professor is gives</p>

<pre class=""lang-java prettyprint-override""><code>
    @Test
    public void testToString() throws Exception {
        Building b = new Building(""B"", -1, 4);
        Room b104 = new Room(b, ""104"", 1);
        assertEquals(""Building(B)"", b + """");
        assertEquals(""Room(B,104)"", b104 + """");
}
</code></pre>

<p>This is what junit tells: </p>

<pre><code>org.junit.ComparisonFailure: 
Expected :Building(B)
Actual   :Building@4e718207

org.junit.ComparisonFailure: 
Expected :Room(B,104)
Actual   :Room@4e718207
</code></pre>
",https://stackoverflow.com/questions/55312482/unit-testing-tostring-method-possible-override,['java'],849,True,0,1
AndroidX pure unit testing - no instrumentation,"<p>I'm trying to write purely unit tests that do not in any way instantiate or run the rest of the app, but every single of my tests seem to call <code>MyApplication</code>'s <code>onCreate</code>. How do i avoid this? I want my test to only run the code i explicitly tell it to.</p>

<p>I have these dependencies for my tests:</p>

<pre><code>testImplementation 'android.arch.core:core-testing:1.1.1'
testImplementation 'androidx.test.ext:junit:1.1.1'
testImplementation 'androidx.test:core:1.2.0'
testImplementation 'androidx.test:runner:1.2.0'
testImplementation 'androidx.test:rules:1.2.0'
testImplementation 'org.robolectric:robolectric:4.3'
def mockito_version = ""2.27.0""
testImplementation ""org.mockito:mockito-core:$mockito_version""
testImplementation ""org.mockito:mockito-inline:$mockito_version""
</code></pre>

<p>Additionally, I also have specified the test runner in my build.gradle:</p>

<pre><code>testInstrumentationRunner ""androidx.test.runner.AndroidJUnitRunner""
</code></pre>

<p>I've tried a couple of different annotations for my tests:</p>

<pre><code>@RunWith(RobolectricTestRunner::class)
class MyTests {
    // ...
}

@RunWith(AndroidJUnit4::class)
class MyTests {
    // ...
}
</code></pre>

<p>Both of these seem to instantiate <code>MyApplication</code> which I do not want. If i remove the annotation completely, it seems to work correctly except for when using <code>ApplicationProvider</code> to get a <code>Context</code> instance:</p>

<pre><code>IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.
</code></pre>

<p>Is it possible to do raw unit tests in Android using the AndroidX test libraries? If so, how?</p>

<p>Edit: Comments asked for an example of what i want to test:</p>

<pre><code>public class MyClass {
    public static String getAdditionString(Context context, int a, int b) {
        int result = a + b;
        return result + context.getString(R.string.mystring);
    }
}
</code></pre>

<p>I would like to verify that this method returns the expected result, without spinning up the rest of the app</p>

<p>Edit2: Ok so apparently <code>testOptions.unitTests.includeAndroidResources = true</code> seems to cause the runner to instantiate and run my entire app, instead of just making the resources available. Interesting behavior. I guess that changes my question to: How do i use my apps resources in a unittest without this setting?</p>
",https://stackoverflow.com/questions/57854819/androidx-pure-unit-testing-no-instrumentation,"['android', 'android-studio', 'junit', 'android-testing', 'androidx']",121,False,0,0
Angular Unit Testing using Mock Models,"<p>I am trying to unit test a component. I need to set a variable on that component to an instance of PolicyMock, which is a mock I created from a model. </p>

<p>Example of Policy (real model)</p>

<pre><code>export class Policy {

    businessArea: BusinessArea;
    statusCode: number;
    submittedStatus: SubmittedStatus;
    // ...
}
</code></pre>

<p>Example of the model I made, PolicyMock:</p>

<pre><code>export class PolicyMock extends Policy {
    businessArea: 2;
    statusCode: -1;
    submittedStatus: 1;
    // ...
}
</code></pre>

<p>Now, I am not used to this heavy Object Oriented programming, I come from Javascript and React mainly. So it is likely some lack of understanding on my part, but when I try to set the variable in the component to an instance of my Mock model and console out those results I get this instead of the actual values within the class: </p>

<pre><code>[PolicyMock{}]
</code></pre>

<p>Here is how I am trying to get set the variable (it's a private method so I am using the escape hatch syntax)</p>

<pre><code>let cp: DataTableComponent&lt;Policy&gt;;
cp = new DataTableComponent&lt;Policy&gt;(sanitize, ref);
cp['data'] = [new PolicyMock()];
console.log(cp['data']);
</code></pre>

<p>I've also tried setting cp['data'] as an empty array intially and pushing the instance to it but that yielded the same result.</p>

<p>Any help would be appreciated!</p>
",https://stackoverflow.com/questions/56603655/angular-unit-testing-using-mock-models,"['angular', 'unit-testing', 'karma-jasmine']",1348,False,0,0
Sinon unit testing for asynchronous call,"<p>I want to test a function that loads some data and check whether the list is empty or not.</p>
<p>I get some <code>errors</code> like below</p>
<blockquote>
<p>Network fetch error</p>
<p>.map is not a function</p>
<p>stub is called 0 times</p>
</blockquote>
<p>I am new to javascript any help will be appreciated.</p>
<pre><code>loadmythings = async () =&gt; {
  const list = await getmythings();
  const finalvalues = []
  list.map(item =&gt; values.push({ value: item.name }))
  return value
}
</code></pre>
<p><code>api.js</code></p>
<pre><code>export function getmythings(arg1, arg2) {
  url = &quot;/someurl&quot;
  returns fetch(url).then(response =&gt; response.json())
    .then(json =&gt; json)
    .catch(error =&gt; error)
}
</code></pre>
<p>the code that I tried is :
import * as api1 from ../api/..api.js</p>
<pre><code>describe('testing', () =&gt; {
  it('check list', async () =&gt; {
    const apptest = new loadmythings_1()
    const mockdata = [{ name: &quot;my_name&quot; }]
    const stub = sinon.stub(api1, 'getmythings').returns(mockdata);
    const finalList = await apptest.loadmythings();
    sinon.assert.calledOnce(stub);
    expect(finalList).to.equal(mockdata)
  });
});
</code></pre>
",https://stackoverflow.com/questions/57970016/sinon-unit-testing-for-asynchronous-call,"['javascript', 'unit-testing', 'sinon', 'chai']",254,False,0,1
Unit Testing - Prism - Xamarin.Forms - INavigationService issue,"<p>I recently started working on a Xamarin.Forms app for iOS and Android. I added a unit testing project with xUnit packages. </p>

<p>As of right now, The app has one view and one viewmodel. I wanted to wire everything up. so the viewmodel only has one property. the property is initialized to string.empty. So I am just checking to make sure it's not null. The viewmodel does a dependency on NagivationService.</p>

<p>in my App.xaml.cs - the view and viewmodel are registered for navigation.</p>

<pre><code>protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterForNavigation&lt;NavigationPage&gt;();
    containerRegistry.RegisterForNavigation&lt;ViewAPage, ViewAPageViewModel&gt;();
}
</code></pre>

<p>I created a mock of the App</p>

<pre><code>public class AppMock : App
{
    public AppMock(IPlatformInitializer initializer)
        : base(initializer) {}

    // Added as a work around
    public new INavigationService NavigationService =&gt; base.NavigationService;

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        base.RegisterTypes(containerRegistry);
        containerRegistry.Register&lt;ILoggerFacade, XunitTestOutputLogger&gt;();
    }
}
</code></pre>

<p>The Test Fixture</p>

<pre><code>public class ViewAViewModelFixture : FixtureBase, IDisposable
{
    public ViewAViewModelFixture(ITestOutputHelper testOutputHelper)
        : base(testOutputHelper) {
    }

    private AppMock CreateApp()
    {
        var initializer = new XunitPlatformInitializer(_testOutputHelper);
        return new AppMock(initializer);
    }

    protected AppMock App
    {
        get
        {
            if ( app == null )
            {
                this.App = CreateApp();
            }
            return this.app;
        }
        set
        {
            this.app = value;
        }
    }
    private AppMock app;

    [Fact]
    public void Email_IsEmpty()
    {            
        ViewAViewModel vm = (ViewAViewModel)this.App.Container.Resolve(typeof(ViewAViewModel));

        string email = vm.Email;

        Assert.Equal(expected: string.Empty, actual: email);
    }

    public void Dispose()
    {
        PageNavigationRegistry.ClearRegistrationCache();
    }
}
</code></pre>

<p>When I attempt to run the above test I am getting the following error:</p>

<pre><code>Message: Unity.Exceptions.ResolutionFailedException : Resolution of the dependency failed, type = 'App.ViewModels.ViewAViewModel', name = '(none)'.
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Prism.Navigation.INavigationService, is an interface and cannot be constructed. Are you missing a type mapping?
</code></pre>

<p>I am not sure what I am missing. When I run the app locally in an Android Emulator or iOS simulator it works fine. so I tried the following: </p>

<pre><code>[Fact]
public void Email_IsEmpty()
{
    var app = this.App;
    var NavService = app.NavigationService;

    NavService.NavigateAsync(""/ViewA"");

    ViewA view = (ViewA)this.App.MainPage;

    Assert.IsType&lt;ViewAViewModel&gt;(view.BindingContext);
    ViewAViewModel vm = view.BindingContext as ViewAViewModel;

    string email = vm.Email;

    Assert.Equal(expected: string.Empty, actual: email);
}
</code></pre>

<p>this test passes, while the other one obviously fails. </p>

<p>Anyone see what I am missing?</p>
",https://stackoverflow.com/questions/54395369/unit-testing-prism-xamarin-forms-inavigationservice-issue,"['unit-testing', 'xamarin.forms', 'prism']",532,False,0,0
Vue.js – Unit Testing multi file components,"<p>As mentioned in the title, I am using multi file components with Vue.js i.e. I've got a separate html, javascript and scss file. Thus my vue file looks like this:</p>
<pre><code>&lt;template src=&quot;./my-component.html&quot;&gt;&lt;/template&gt;
&lt;script src=&quot;./my-component.js&quot;&gt;&lt;/script&gt;
&lt;style src=&quot;./my-component.scss&quot; lang=&quot;scss&quot;&gt;&lt;/style&gt;
</code></pre>
<p>The vue Unit Testing guide</p>
<p><a href=""https://v2.vuejs.org/v2/guide/unit-testing.html"" rel=""nofollow noreferrer"">https://v2.vuejs.org/v2/guide/unit-testing.html</a></p>
<p>only covers single file components.</p>
<p>Most likely I need to invoke webpack to build a single file component in order to be able to test it.</p>
<p>Could anyone point me in the right direction?</p>
",https://stackoverflow.com/questions/59303168/vue-js-unit-testing-multi-file-components,"['unit-testing', 'vue.js']",252,False,0,0
Unit testing the views in laravel?,"<p>How to do unit testing of the controller's function which returns a view. Here, is my controller function </p>

<pre><code>public function index(Request $request)
{
   $data = Data::all();
   return view('index',[
       'data' =&gt; $data
   ]);
}
</code></pre>

<p>Here is test code</p>

<pre><code>public function testIndex()
{
   $response = $this-&gt;withoutMiddleware();

   $response = $this-&gt;get('/user');

   $response-&gt;assertSuccessful();
}
</code></pre>

<p>I tried this</p>

<pre><code>public function testIndex()
{
   $response = $this-&gt;withoutMiddleware();

   $response = $this-&gt;get('/user');

   $response = $this-&gt;assertContains('data', $response-&gt;content());

   $response-&gt;assertSuccessful();
}
</code></pre>

<p>which shows error of</p>

<blockquote>
  <p>Error: Call to a member function assertSuccessful() on null</p>
</blockquote>

<p>Any idea, How to write a test case for my index controller function?</p>
",https://stackoverflow.com/questions/55509287/unit-testing-the-views-in-laravel,"['php', 'laravel', 'phpunit']",4118,True,0,3
Unit testing exception in async method,"<p>I am trying to unit test an async method below using VSTest. However, the test passes for <code>AsyncMathsStatic.Divide(4, 0)</code> as well as <code>AsyncMathsStatic.Divide(4, 1))</code> even though an exception is thrown in the first case only.</p>

<pre><code>[TestClass]
public class UnitTest1
{
    [TestMethod]

    public void DivideTest1()
    {
        // Func&lt;Task&gt; action = async()=&gt; {  AsyncMathsStatic.Divide(4, 0); };
        //action.Should().Throw&lt;DivideByZeroException&gt;();

        Assert.ThrowsExceptionAsync&lt;DivideByZeroException&gt;(async () =&gt; 
        AsyncMathsStatic.Divide(4, 0));
    }
}

public class AsyncMathsStatic
{
    public static async void Divide(int v1, int v2)
    {
        try
        {
            if (v1/v2 &gt; 1)
            {
                // do something time consuming
            }   
        }
        catch (DivideByZeroException ex)
        {
            throw;
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/59366763/unit-testing-exception-in-async-method,"['c#', 'exception', 'async-await', 'vstest']",1256,True,0,3
Unit testing model relationships in Laravel,"<p>In my app I have a many-to-many relationship between users and organisations, </p>

<p><strong>User</strong></p>

<pre><code>public function organisations()
{
    return $this-&gt;belongsToMany('App\Organisation')-&gt;withPivot(['owner']);
}
</code></pre>

<p><strong>Organisation</strong></p>

<pre><code>public function users()
{
    return $this-&gt;belongsToMany('App\User')-&gt;withPivot(['owner']);
}
</code></pre>

<p>There is a pivot column on this relationship to state whether the user is an owner of the organisation or not. </p>

<p>I am struggling to test the relationship though, my test returns, </p>

<blockquote>
  <p>Failed asserting that null matches expected 1.
  Expected :1
  Actual   :null</p>
</blockquote>

<p>Here is my test function, </p>

<pre><code>public function testUserHasOwnershipOfOrganisations()
{
    $userRow = factory(User::class)-&gt;create();
    $organisation = factory(Organisation::class)-&gt;create();
    $userRow-&gt;organisations()-&gt;attach($organisation-&gt;id, ['owner' =&gt; true]);
    $user = User::first();
    $ownOrganisations = $user-&gt;organisations()-&gt;wherePivot('owner', true);
    $this-&gt;assertEquals($organisation-&gt;id, $ownOrganisations-&gt;first()-&gt;organisation_id);
}
</code></pre>

<p>The thought process of the above is make a user, make an organisation, create the relationship. Query the first user in the table, get their organisations and make sure the organisation in the organisation relationship as the same ID as the one I just created. </p>

<p>Can anyone tell me why this is not working as I would expect it too?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/57336754/unit-testing-model-relationships-in-laravel,"['php', 'laravel', 'unit-testing', 'phpunit', 'eloquent-relationship']",905,False,0,1
Laravel 6 Unit Testing Responses 401,"<p>I am using Token based operations. The request for the Edit operation in Project works well in Postman. </p>

<pre><code>public function update(Request $request, $id)
    {
        $project = Project::find($id);
        $project-&gt;project_name = request('project_name');
        $project-&gt;project_description = request('project_description');
        $project-&gt;save();
        return response()-&gt;json([
            'message' =&gt;  ""Project Updated Successfully"",
            'updatedId' =&gt; $project-&gt;id
            ], 200);
    }
</code></pre>

<p>But in Unit Testing Not getting Proper Responses</p>

<pre><code> public function testBasicExample()
    {
        $response = $this-&gt;withHeaders([
            'Accept' =&gt; 'application/json',
            'Authorization' =&gt; 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi......'
        ])-&gt;json('POST', '/api/updateProject/1',
                ['project_name' =&gt; 'Sally'],
                ['project_description' =&gt; 'testing the api']
                );

                $response-&gt;assertStatus(200);
                $response-&gt;assertJson(['status' =&gt; true]);
    }
</code></pre>

<p>Error Shows </p>

<pre><code>PS D:\XMAPP\htdocs\minidmsapi&gt; ./vendor/bin/phpunit
PHPUnit 8.4.1 by Sebastian Bergmann and contributors.

..F.                                                                4 / 4 (100%)

Time: 516 ms, Memory: 18.00 MB

There was 1 failure:

1) Modules\Projects\Tests\Unit\ProjectTest::testupdate
Expected status code 200 but received 401.
Failed asserting that false is true.

D:\XMAPP\htdocs\minidmsapi\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestResponse.php:166
D:\XMAPP\htdocs\minidmsapi\Modules\Projects\Tests\Unit\ProjectTest.php:35

FAILURES!
Tests: 4, Assertions: 4, Failures: 1.
</code></pre>

<p>Why Unit Testing having Error Response 401 ?</p>

<p>Kindly anyone, please explain to me What is the actual error in unit testing and solution for that.</p>
",https://stackoverflow.com/questions/58447741/laravel-6-unit-testing-responses-401,"['api', 'unit-testing', 'testing', 'laravel-6']",1051,False,0,1
Unit Testing with Mock and InvocationOnMock,"<p>I'm new with Java Spring, I need a guidance with Mockito.</p>

<p>I tried to test my Service Layer but it keeps failing to verify the mock username and email address.</p>

<p>I'm currently really confused on how should I do it properly.</p>

<p>Thanks you!</p>

<blockquote>
  <p>UserService.java</p>
</blockquote>

<pre><code>package com.example.newproject.newproject.service;

import com.example.newproject.newproject.entity.User;

import java.util.List;

public interface UserService {
    boolean addUser(String username,String email);
    List&lt;User&gt; viewAllUsers();
}
</code></pre>

<blockquote>
  <p>UserServiceImpl.java</p>
</blockquote>

<pre><code>package com.example.newproject.newproject.service.impl;

import com.example.newproject.newproject.entity.User;
import com.example.newproject.newproject.repository.UserRepository;
import com.example.newproject.newproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;


    @Override
    public boolean addUser(String username, String email) {
        if(userRepository.findByUsernameAndEmail(username, email) == null)
        {
            User user = new User();
            user.setUsername(username);
            user.setEmail(email);
            userRepository.save(user);
            return false;

        }else{
            return true;
        }

    }

    @Override
    public List&lt;User&gt; viewAllUsers() {
        return userRepository.findAll();
    }
}
</code></pre>

<blockquote>
  <p>My Mock</p>
</blockquote>

<pre><code>@Test
public void testAddUser(){
    Mockito.when(userRepository.findByUsernameAndEmail(""Google"",""google@google.com"")).then(invocationOnMock -&gt;  {

        User user = new User();
        return user;
    });

    boolean result =  userService.addUser(""Google"",""google@google.com"");
    Assert.assertFalse(result);

    Mockito.verify(userRepository, Mockito.times(1)).save(userArgumentCaptor.capture());
    User user = userArgumentCaptor.getValue();
    Assert.assertEquals(""Google"", user.getUsername());
    Assert.assertEquals(""google@google.com"", user.getEmail());
}
</code></pre>

<p>The error I get is</p>

<pre><code>  java.lang.AssertionError
</code></pre>

<p>during run</p>
",https://stackoverflow.com/questions/54290224/unit-testing-with-mock-and-invocationonmock,"['java', 'spring-boot']",356,False,0,0
Rest API Unit Testing Using Moq,"<p>How to test Rest API..?</p>

<p>In my project we have mocked data access layer. In unit test via end point will hit business layer and it returns the same value which has been mocked.</p>

<p>Since, our unit test will always pass as we have mocked then what is the use of unit testing..?</p>

<p>Let me know if there are any better ways of testing rest end points.</p>
",https://stackoverflow.com/questions/55063626/rest-api-unit-testing-using-moq,"['rest', 'unit-testing', 'moq']",111,False,0,1
Unit testing Hosted Services in .NET Core,"<p>I have a background task implemented by <a href=""https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2&amp;tabs=visual-studio"" rel=""noreferrer"">hosted services</a> in .NET Core. There is very little logic in this class:</p>

<pre><code>public class IndexingService : IHostedService, IDisposable
{
    private readonly int indexingFrequency;

    private readonly IIndexService indexService;

    private readonly ILogger logger;

    private bool isRunning;

    private Timer timer;

    public IndexingService(ILogger&lt;IndexingService&gt; logger, IIndexService indexService, IndexingSettings indexingSettings)
    {
        this.logger = logger;
        this.indexService = indexService;

        this.indexingFrequency = indexingSettings.IndexingFrequency;
    }

    public void Dispose()
    {
        this.timer?.Dispose();
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        this.timer = new Timer(this.DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(this.indexingFrequency));
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        this.timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        if (this.isRunning)
        {
            // Log
            return;
        }

        try
        {
            this.isRunning = true;
            this.indexService.IndexAll();
        }
        catch (Exception e)
        {
            // Log, The background task should never throw.
        }
        finally
        {
            this.isRunning = false;
        }
    }
}
</code></pre>

<p>and my <code>Startup</code> looks like:</p>

<pre><code>public void ConfigureServices(IServiceCollection services)
{
    services.AddHostedService&lt;IndexingService&gt;();
    services.AddTransient&lt;IIndexService, IndexService&gt;();
    // 'IndexingSettings' is read from appsetting and registered as singleton
}
</code></pre>

<p>How can I unit test the logic in <code>DoWork</code> method? The problem is that the hosted services are managed by the framework, and I don't know how to isolate this class.</p>
",https://stackoverflow.com/questions/57774619/unit-testing-hosted-services-in-net-core,"['c#', 'unit-testing', '.net-core', 'asp.net-core-hosted-services']",7585,True,5,3
Unit-testing with cats-effect&#39;s IO monad,"<h1>The Scenario</h1>
<p>In an application I am currently writing I am using cats-effect's <a href=""https://github.com/typelevel/cats-effect"" rel=""nofollow noreferrer"">IO monad</a> in an <a href=""https://typelevel.org/cats-effect/datatypes/ioapp.html"" rel=""nofollow noreferrer"">IOApp</a>.</p>
<p>If started with a command line argument 'debug', I am delegeting my program flow into a debug loop that waits for user input and executes all kinds of debugging-relevant methods. As soon as the developer presses <code>enter</code> without any input, the application will exit the debug loop and exit the main method, thus closing the application.</p>
<p>The main method of this application looks roughly like this:</p>
<pre class=""lang-scala prettyprint-override""><code>import scala.concurrent.{ExecutionContext, ExecutionContextExecutor}
import cats.effect.{ExitCode, IO, IOApp}
import cats.implicits._

object Main extends IOApp {

    val BlockingFileIO: ExecutionContextExecutor = ExecutionContext.fromExecutor(blockingIOCachedThreadPool)

    def run(args: List[String]): IO[ExitCode] = for {
        _ &lt;- IO { println (&quot;Running with args: &quot; + args.mkString(&quot;,&quot;))}
        debug = args.contains(&quot;debug&quot;)
        // do all kinds of other stuff like initializing a webserver, file IO etc.
        // ...
        _ &lt;- if(debug) debugLoop else IO.unit
    } yield ExitCode.Success

    def debugLoop: IO[Unit] = for {
      _     &lt;- IO(println(&quot;Debug mode: exit application be pressing ENTER.&quot;))
      _     &lt;- IO.shift(BlockingFileIO) // readLine might block for a long time so we shift to another thread
      input &lt;- IO(StdIn.readLine())     // let it run until user presses return
      _     &lt;- IO.shift(ExecutionContext.global) // shift back to main thread
      _     &lt;- if(input == &quot;b&quot;) {
                  // do some debug relevant stuff
                  IO(Unit) &gt;&gt; debugLoop
               } else {
                  shutDown()
               }
    } yield Unit

    // shuts down everything
    def shutDown(): IO[Unit] = ??? 
}
</code></pre>
<p>Now, I want to test if e.g. my <code>run</code> method behaves like expected in my <code>ScalaTest</code>s:</p>
<pre class=""lang-scala prettyprint-override""><code>import org.scalatest.FlatSpec

class MainSpec extends FlatSpec{

  &quot;Main&quot; should &quot;enter the debug loop if args contain 'debug'&quot; in {
    val program: IO[ExitCode] = Main.run(&quot;debug&quot; :: Nil)
    // is there some way I can 'search through the IO monad' and determine if my program contains the statements from the debug loop?
  }
}
</code></pre>
<hr />
<h1>My Question</h1>
<p>Can I somehow 'search/iterate through the IO monad' and determine if my program contains the statements from the debug loop? Do I have to call <code>program.unsafeRunSync()</code> on it to check that?</p>
",https://stackoverflow.com/questions/54767360/unit-testing-with-cats-effects-io-monad,"['scala', 'unit-testing', 'scala-cats']",4219,True,5,2
Unit Testing for Extension method using moq,"<p>I’m writing a unit test for function uploaddocuments() for azuresearch .  </p>

<blockquote>
<pre><code>Unsupported expression: ... =&gt;
....Index(It.IsAny&lt;IndexBatch&lt;Document&gt;&gt;(),
It.IsAny&lt;SearchRequestOptions&gt;()) Extension methods (here:
DocumentsOperationsExtensions.Index) may not be used in setup /
verification expressions.
</code></pre>
</blockquote>

<p>Not sure why it's not working.</p>

<p>code:</p>

<pre><code>    private static async Task uploaddocuments(ISearchIndexClient indexClient)
    {

    var actions = new IndexAction&lt;Hotel&gt;[]
    {

      IndexAction.Upload(
       new Hotel()
       {
           HotelId = ""1"",
                HotelName = ""Secret Point Motel"",
                Description = ""The hotel is ,

                Rating = 3.6,
                Address = new Address()
                {
                    StreetAddress = ""677 5th Ave"",
                    City = ""New York"",
                    StateProvince = ""NY"",
                    PostalCode = ""10022"",
                    Country = ""USA""
                }

         }
       )
    }
    var batch = IndexBatch.New(actions);
    try
    {
           indexClient.Documents.Index(batch);
    }
    catch (IndexBatchException e)
    {
          console.log(e);
    }
}
</code></pre>

<p>Test:</p>

<pre><code>var testMock = new Mock(IDocumentsOperations)();

docOperationsMock.Setup(() =&gt; Index(It.IsAny(IndexBatch&lt;Document))(), It.IsAny&lt;SearchRequestOptions)())).Returns(new DocumentIndexResult());


  var mock = new Mock&lt;ISearchIndexClient&gt;()

            .Setup(x =&gt; x).Returns(It.IsAny(SearchIndexClient)());

             .SetupGet(a =&gt; a.Documents).Returns(It.IsAny(""IDocumentsOperations"")())

             .Callback(() =&gt; IndexBatch.Upload(It.IsAny(IEnumerable(dynamic))()));

            .Returns(testMock.Object);
</code></pre>
",https://stackoverflow.com/questions/58671929/unit-testing-for-extension-method-using-moq,"['c#', 'azure', 'unit-testing', 'moq']",9559,True,6,1
Unit testing sqlmock failing with sql update,"<p>We've been using sqlmock testing func() that are using select - no problems there.</p>

<p>It's not working with updates.</p>

<p>The func we want to test is:</p>

<pre><code>func PutTag(tag *Tag) error {
...
    err = db.DB.Where(""id=?"", tag.Id).Save(tag).Error
...
}
</code></pre>

<p>We've defined the test func like this:</p>

<pre><code>func (s *Suite) TestPutTag() {
    tag := Tag{Id: 2, Name: ""Test Tag 2""}
    s.mock.ExpectBegin()
    s.mock.ExpectQuery(""UPDATE `tags` SET `name` = ?  WHERE `tags`.`id` = ? AND ((id=?))"").
        WithArgs(tag.Name, tag.Id, tag.Id)
    s.mock.ExpectCommit()
    err := PutTag(&amp;tag)
    require.NoError(s.T(), err)
}
</code></pre>

<p>This is returning..</p>

<pre><code>[2019-08-30 14:36:36]  call to ExecQuery 'UPDATE `tags` SET `name` = ?  WHERE `tags`.`id` = ? AND ((id=?))' with args [{Name: Ordinal:1 Value:Test Tag 2} {Name: Ordinal:2 Value:2} {Name: Ordinal:3 Value:2}], was not expected, next expectation is: ExpectedQuery =&gt; expecting Query, QueryContext or QueryRow which:
  - matches sql: 'UPDATE `tags` SET `name` = ?  WHERE `tags`.`id` = ? AND ((id=?))'
  - is with arguments:
    0 - Test Tag 2
    1 - 2
    2 - 2
</code></pre>

<p>The sql statements seem the same to me.</p>
",https://stackoverflow.com/questions/57724935/unit-testing-sqlmock-failing-with-sql-update,"['mysql', 'unit-testing', 'go', 'go-gorm', 'go-sqlmock']",1592,False,5,0
Ununderstandable unit testing effects error using Jest,"<p>I'm working on two nearly identical test cases where I should assert expect that two NgRx effects return a stream of booleans.
Everything works as expected in the first test case, and although doing the same for the second test case I can't make it to work as expected. Whatever I do, the received value is always an empty array:</p>

<pre><code>expect(received).toEqual(expected) // deep equality
    - Expected
    + Received

    - Array [
    -   Object {
    -     ""frame"": 10,
    -     ""notification"": Notification {
    -       ""error"": undefined,
    -       ""hasValue"": true,
    -       ""kind"": ""N"",
    -       ""value"": true,
    -     },
    -   },
    - ]
    + Array []
</code></pre>

<h2>Working test</h2>

<p><strong>logger.effects.spec.ts:</strong></p>

<pre class=""lang-js prettyprint-override""><code>describe('LoggerEffects', () =&gt; {
    let actions$: Observable&lt;ApiFailure&gt;;
    let effects: LoggerEffects;
    const serviceMock = &lt;AppLoggerServiceI&gt;{ failure: ({ body, title }) =&gt; of(true) };
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [StoreModule.forRoot({})],
            providers: [
                LoggerEffects,
                provideMockActions(() =&gt; actions$),
                {
                    provide: 'appLoggerService',
                    useValue: serviceMock
                }
            ]
        });
        effects = TestBed.get(LoggerEffects);
    });
    const failure = new HttpErrorResponse({ error: 'HttpErrorResponse' });
    describe('logApiFailure$', () =&gt; {
        it('should return a stream of boolean if the dispatched action is ApiActions.searchFailure', () =&gt; {
            const action = ApiActions.searchFailure({ failure });
            actions$ = hot('-a--', { a: action });
            const expected = cold('-b--', { b: true });
            expect(effects.logApiFailure$).toBeObservable(expected);
        });
    });
});
</code></pre>

<p><strong>logger.effects.ts:</strong></p>

<pre class=""lang-js prettyprint-override""><code>logApiFailure$ = createEffect(
        () =&gt;
            this.actions$.pipe(
                ofType(ApiActions.searchFailure),
                exhaustMap(({ failure: { body, title } }) =&gt;
                    this.appLoggerService.failure({
                        body,
                        title
                    })
                )
            ),
        { dispatch: false }
    );
</code></pre>

<h2>Failed test</h2>

<p><strong>router.effects.spec.ts:</strong></p>

<pre class=""lang-js prettyprint-override""><code>describe('RouterEffects', () =&gt; {
    let actions$: Observable&lt;boolean&gt;;
    let effects: RouterEffects;

    const routerMock = &lt;Partial&lt;Router&gt;&gt;{ navigate: (commands: any[]) =&gt; Promise.resolve(true) };

    let router: Router;
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [StoreModule.forRoot({})],
            providers: [
                RouterEffects,
                provideMockActions(() =&gt; actions$),
                {
                    provide: Router,
                    useValue: routerMock
                }
            ]
        });
        effects = TestBed.get(RouterEffects);
    });
    describe('navigateTo$', () =&gt; {
        it('should return a stream of boolean if the dispatched action is RouterActions.navigateTo', () =&gt; {
            const action = RouterActions.navigateTo();
            actions$ = hot('-a--', { a: action });
            const expected = cold('-b--', { b: true });
            console.log('toto', effects.navigateTo$);
            expect(effects.navigateTo$).toBeObservable(expected);
        });
    });
});
</code></pre>

<p><strong>router.effects.ts:</strong></p>

<pre class=""lang-js prettyprint-override""><code>navigateTo$ = createEffect(
    () =&gt;
        this.actions$.pipe(
            ofType(RouterActions.navigateTo),
            exhaustMap(() =&gt; this.router.navigate(['my-route', {}]))
        ),
    { dispatch: false }
);
</code></pre>

<p>At this point, I'm assuming there's something wrong with the Hot Observable in router.effects.spec.ts which prevents the effect to dispatch the navigateTo action. Do you have any thoughts about it? </p>

<h3>The project's dependencies</h3>

<pre class=""lang-js prettyprint-override""><code>{
    ""dependencies"": {
        ""@angular/animations"": ""^8.0.0"",
        ""@angular/cdk"": ""^8.0.0"",
        ""@angular/common"": ""^8.0.0"",
        ""@angular/compiler"": ""^8.0.0"",
        ""@angular/core"": ""^8.0.0"",
        ""@angular/forms"": ""^8.0.0"",
        ""@angular/material"": ""^8.0.0"",
        ""@angular/material-moment-adapter"": ""^8.0.0"",
        ""@angular/platform-browser"": ""^8.0.0"",
        ""@angular/platform-browser-dynamic"": ""^8.0.0"",
        ""@angular/router"": ""^8.0.0"",
        ""@ngrx/effects"": ""^8.0.0"",
        ""@ngrx/router-store"": ""^8.0.0"",
        ""@ngrx/store"": ""^8.0.0"",
        ""core-js"": ""^2.5.4"",
        ""hammerjs"": ""^2.0.8"",
        ""moment"": ""^2.24.0"",
        ""rxjs"": ""^6.5.0"",
        ""tslib"": ""^1.9.0"",
        ""zone.js"": ""^0.9.1""
    },
    ""devDependencies"": {
        ""jest-preset-angular"": ""7.0.0"",
        ""@angular-devkit/build-angular"": ""^0.800.0"",
        ""@angular-devkit/build-ng-packagr"": ""~0.800.0"",
        ""@angular-devkit/core"": ""^8.0.2"",
        ""@angular-devkit/schematics"": ""^8.0.2"",
        ""@angular/cli"": ""8.0.0"",
        ""@angular/compiler-cli"": ""^8.0.0"",
        ""@angular/language-service"": ""^8.0.0"",
        ""@ngrx/schematics"": ""^8.0.0"",
        ""@ngrx/store-devtools"": ""^8.0.0"",
        ""@nrwl/cypress"": ""8.1.0"",
        ""@nrwl/jest"": ""8.1.0"",
        ""@nrwl/workspace"": ""8.1.0"",
        ""@nrwl/schematics"": ""8.1.0"",
        ""@types/jest"": ""24.0.9"",
        ""@types/node"": ""^12.0.7"",
        ""codelyzer"": ""~5.0.1"",
        ""cypress"": ""~3.3.1"",
        ""dotenv"": ""6.2.0"",
        ""jest"": ""24.1.0"",
        ""ng-packagr"": ""^5.1.0"",
        ""prettier"": ""1.16.4"",
        ""ts-jest"": ""24.0.0"",
        ""ts-node"": ""^8.2.0"",
        ""tsickle"": ""^0.35.0"",
        ""tslib"": ""^1.9.0"",
        ""tslint"": ""~5.11.0"",
        ""typescript"": ""~3.4.5""
    }
}
</code></pre>
",https://stackoverflow.com/questions/56663924/ununderstandable-unit-testing-effects-error-using-jest,"['angular', 'jestjs', 'ngrx', 'ngrx-effects']",1163,False,5,1
Unit testing Spring Boot application Service layer,"<p>I'm a bit confused about the test capabilities and utilities provided by Spring Boot.</p>

<p>I'm using <code>spring-boot-starter-test</code> in my project and I'd like to unit test my services without the database connection </p>

<p>At the moment I'm using <code>@WebMvcTest</code> for contoller test suites and <code>@SpringBootTest</code> for all the other test classes.</p>

<p>But I read somewhere that <code>@SpringBootTest</code> is meant to be used only in integration tests...</p>

<p>Reading <a href=""https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests"" rel=""nofollow noreferrer"">documentation</a> I didn't understood what's the suggested approach for services. Should I only test them in integration with repos?</p>

<p><strong>UPDATE</strong></p>

<p>That's an excerpt of a test class for one of my services:</p>

<pre><code>@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
internal class SignupServiceTest(
        @Autowired val signupService: SignupService
) {
    @MockkBean
    lateinit var userRepository: UserRepository

    @Test
    fun `should return exception if username already used`() {
        every { userRepository.findByUsername(""registered-user"") } returns fakeUser(username = ""registered-user"")

        assertThatThrownBy {
            signupService.createNewAccount(fakeSignupForm(username = ""registered-user""))
        }.isExactlyInstanceOf(UsernameNotAvailableException::class.java)
    }

    // ... other tests

}
</code></pre>
",https://stackoverflow.com/questions/58373639/unit-testing-spring-boot-application-service-layer,"['spring-boot', 'unit-testing', 'kotlin']",2570,True,4,4
Unit testing MessageSender for Azure Functions V2,"<p>I am trying to find the best approach for using MessageSender in my Azure function as the connection to ServiceBus, in order to unit test it. I have been unable to find the best way to write my code to unit test it.</p>

<p><strong>Code</strong></p>

<pre><code>public static class SomeFunction
{        
    [FunctionName(""SomeFunction"")]
    public static async Task Run(
          [ServiceBusTrigger(""someQueue"", Connection = ConnectionString)]Message message
        , [ServiceBus(""someQueue"", Connection = ConnectionString"")]MessageSender messagesQueue
        , MessageReceiver receiver
        , string lockToken)
    {
        ...some code
    }
}          
</code></pre>

<p>I tried to change the <code>MessageSender</code> to <code>IMessageSender</code> but got the following binding error</p>

<p><strong><em>Binding Error</em></strong></p>

<pre><code>System.InvalidOperationException: ""Can't bind ServiceBus to type 'Microsoft.Azure.ServiceBus.Core.IMessageSender.""
</code></pre>

<p>Then switched it back to the <code>MessageSender</code> and tried mocking it and once I ran my test I got the error below.</p>

<p><strong>Unit Test Example</strong></p>

<pre><code>[TestMethod]
public async Task Run_ValidMessage_Expect_Run_Succesfully()
{
    var sbBuilder = new ServiceBusConnectionStringBuilder(ActualSbConnectionString);
    Mock&lt;MessageSender&gt;sender = new Mock&lt;MessageSender&gt;(sbBuilder, RetryPolicy.Default);
    SomeFunction.Run(_sender.Object);
}
</code></pre>

<pre><code>Error: 
threw exception: 
    System.ArgumentException: The argument  is null or white space.
  Stack Trace: 
    at MessageSender.ctor(String entityPath, String transferDestinationPath, Nullable`1 entityType, ServiceBusConnection serviceBusConnection, ICbsTokenProvider cbsTokenProvider, RetryPolicy retryPolicy)
    at MessageSender.ctor(String connectionString, String entityPath, RetryPolicy retryPolicy)
</code></pre>

<p>I have been unable to write the code with a working unit test and function. any pointers would be helpful.</p>

<p>Edit: included omitted args</p>
",https://stackoverflow.com/questions/57930974/unit-testing-messagesender-for-azure-functions-v2,"['c#', 'azure', 'unit-testing', 'moq', 'azureservicebus']",2101,True,4,2
Fake file drop event for unit testing,"<p>I'm trying to simulate a file <code>Drop</code> event for testing an angular directive but I cannot manage to create the <code>DragEvent</code>.</p>

<pre><code>it('should output file drop when file droped', () =&gt; {
    const file = new File([''], 'dummy.txt'); // got my file right there, want to drop it on ""des""
    des.dispatchEvent(new DragEvent('drop', { dataTransfer: { items: [ new DataTransferItem(file)] } }));
    // ...
});
</code></pre>

<p>I'm unsure what to do with the second parameter to have my file in there..</p>
",https://stackoverflow.com/questions/57080760/fake-file-drop-event-for-unit-testing,"['javascript', 'angular', 'jasmine', 'angular-unit-test']",4770,True,3,2
Angular 7 Unit testing Observable subscribe call,"<p>I've a <code>GeoLocationService</code> in my angular application like this.</p>

<pre><code>import { Injectable } from ""@angular/core"";
import { Observable } from ""rxjs/Observable"";

@Injectable()
export class GeoLocationService {
  coordinates: any;

  constructor() {}

  public getPosition(): Observable&lt;Position&gt; {
    return Observable.create(observer =&gt; {
      navigator.geolocation.watchPosition((pos: Position) =&gt; {
        observer.next(pos);
      }),
        () =&gt; {
          console.log(""Position is not available"");
        },
        {
          enableHighAccuracy: true
        };
    });
  }
}
</code></pre>

<p>I want to unit test this service to ensure that the <code>getPosition()</code> function returns me a working <code>Observable</code>. Here's how my test looks like.</p>

<pre><code>import { TestBed, fakeAsync } from ""@angular/core/testing"";

import { GeoLocationService } from ""./geo-location.service"";
import { take } from ""rxjs/operators"";

describe(""GeoLocationService"", () =&gt; {
  let service: GeoLocationService;
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [GeoLocationService]
    });
    service = TestBed.get(GeoLocationService);
  });


  it(""should get observable value"", fakeAsync((done: DoneFn) =&gt; {
    service
      .getPosition()
      .subscribe(value =&gt; {
        expect(value.coords).not.toBeUndefined();
        expect(value.coords).not.toBeNaN();
        expect(value.coords).not.toBeNull();
        done();
      });
  }));
});
</code></pre>

<p>What happens here is that once I run the test the test is successful ( this is because the <code>subscribe</code> block inside the test is not run yet). On the <code>chrome browser window</code> that opens ( for viewing test results in karma ), I select <code>Allow</code> for the application to find my location, it is at this moment the <code>subscribe</code> block runs but by that time the <code>it</code> spec has already finished due to this reason I get a <code>console error</code> saying.</p>

<p><code>Uncaught Error: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out</code>.</p>

<p>I don't know what is the recommended way to perform this test. </p>
",https://stackoverflow.com/questions/56849566/angular-7-unit-testing-observable-subscribe-call,"['angular', 'unit-testing', 'karma-jasmine']",7799,True,3,2
Jest unit testing: block all outgoing traffic,"<p>I would like to somehow block all outgoing traffic when running unit tests with jest. Ideally you mock all the modules (or functions that send http requests) including 3rd party ones, but when you are in the process of development you may not be able to mock everything from the start and may accidentally send some data.</p>

<p>If that's not possible with jest, what would then be the best practice to do so? iptables maybe?</p>
",https://stackoverflow.com/questions/56760324/jest-unit-testing-block-all-outgoing-traffic,"['unit-testing', 'jestjs', 'blocking', 'traffic']",2886,True,3,1
Laravel Unit Testing - add cookie to request?,"<p>I want to send a cookie with json POST:</p>

<pre><code>public function testAccessCookie()
{
    $response = $this-&gt;json('POST', route('publications'))-&gt;withCookie(Cookie::create('test'));
    //some asserts
}
</code></pre>

<p>publications route has some middleware:</p>

<pre><code>public function handle($request, Closure $next)
{
    Log::debug('cookie', [$request-&gt;cookies]);

    //cookie validation

    return $next($request);
}
</code></pre>

<p>But while running <code>testAccessCookie()</code>, there is <code>[null]</code> inside log. No cookies attached.</p>

<p>What's wrong?</p>

<p>There is no such problem with real (in-browser) requests.</p>
",https://stackoverflow.com/questions/54064280/laravel-unit-testing-add-cookie-to-request,"['phpunit', 'laravel-5.7']",5626,True,3,3
Micronaut unit testing : need clarification on @MicronautTest,"<p>I am trying my hands on micronaut, I am facing some difficulty in understanding how to do unit tests.  </p>

<p>I have a simple application with only one controller(which returns hello).<br>
Now I want to test this endpoint. Coming from springboot I was expecting that micronaut has some runner class like <code>SpringRunner</code>, I could not find any. <strong>Is there a runner class in micronaut for running tests?</strong>  </p>

<p>From the documentation <a href=""https://docs.micronaut.io/snapshot/guide/index.html#creatingClient"" rel=""nofollow noreferrer"">here</a> I see that I can test my rest endpoints using HTTPClient. I tried both the  </p>

<ol>
<li>Low level HttpClient  </li>
<li>CompileTime HttpClient</li>
</ol>

<p>Here is a snippet of the test classes I have  </p>

<pre><code>@MicronautTest
class HelloControllerSpec {
    @Inject
    EmbeddedServer server; 

    @Inject
    @Client(""/"")
    HttpClient client; 

    @Test
    void testHelloWorldResponse() {
          //client and server are null
           .........
    }
}  
</code></pre>

<p>And  </p>

<pre><code>@MicronautTest 
public class HelloClientSpec  {

    @Inject
    HelloClient client; 

    @Test
    public void testHelloWorldResponse(){
        //client is null
   }
}
</code></pre>

<p>From what I observed, the annotation <code>@MicronautTest</code> doesn't seem to do anything. Its the same case with <code>@Inject</code> and <code>@Client</code>, all the fields are null when I run the test.  So I am wondering <strong>what exactly does <code>@MicronautTest</code> do?</strong></p>

<p>The only way I could get it work is to start the server explicitly(<code>@Inject</code> on <code>EmbeddedServer</code> doesn't do anything) like this  </p>

<pre><code>server = ApplicationContext.run(EmbeddedServer.class);
helloClient = server.getApplicationContext().getBean(HelloClient.class);
</code></pre>

<p>Even with this, it starts a server instance. Which in not what I wanted. Because I do not want to start server for unit tests. Also I do not want to get the beans this way from application Contexts. <strong>Whay doesn't <code>@Inject</code>, <code>@Client</code>, <code>@EmbeddedServer</code> work in my case, am I missing something here?</strong></p>

<p>In case of springboot, I could test only the weblayer separately(using mockmvc and springboottest), not starting the whole application context. <strong>is there an equivalent in micronaut?</strong>  </p>

<p>I am using micronaut 1.0.2</p>
",https://stackoverflow.com/questions/58301944/micronaut-unit-testing-need-clarification-on-micronauttest,"['java', 'unit-testing', 'micronaut']",3060,True,3,1
Problems with unit testing fire base storage,"<p>I need to write unit tests for my new function that connects to firebase storage. However i cannot find any documentation anywhere online for how to even mock the database.</p>

<p>Does this work the same way that realtime database testing works?</p>

<p>is it similar to: <code>var MockFirebase = require(""firebase-mock"").MockFirebase;</code></p>

<p>i need to be able to mock the storage bucket of the database, any help will be appreciated.</p>
",https://stackoverflow.com/questions/55593115/problems-with-unit-testing-fire-base-storage,"['angularjs', 'unit-testing', 'jasmine', 'firebase-storage']",227,False,3,0
moq unit testing in c# web api,"<p>I am tring to test one web api method in asp.net core 2.</p>

<p>Web api</p>

<p>method:</p>

<pre class=""lang-cs prettyprint-override""><code>public IActionResult Delete(int id)
{
    try
    {
        var success = sportsService.DeleteSport(id);

        if (!success)
        {
            return new NotFoundResult();
        }
        return new OkResult();
    }
    catch (Exception e)
    {
        return new StatusCodeResult(400);
    }
}
</code></pre>

<p>Unit testing part: </p>

<pre class=""lang-cs prettyprint-override""><code>private Mock&lt;ISportsService&gt; mockService;

[SetUp]
public void Setup()
{
    mockService.SetupSequence(x =&gt; x.DeleteSport(It.IsAny&lt;int&gt;())).
        Returns(true). // OkResult();
        Returns(false). // NotFoundResult()
        Throws(new Exception()); //Exception
}
</code></pre>

<p>Test method looks like this. What I am not clear about with this method is, what the right approach to testing the method is?</p>

<pre class=""lang-cs prettyprint-override""><code>[Test]
public void TestStrategyControllerWithDelete()
{
    var result = controller.Delete(STRAT_ID);
    var okResult = result as ObjectResult;
    Assert.AreEqual(HttpStatusCode.NotFound, okResult.StatusCode);
    Assert.AreEqual(HttpStatusCode.OK, okResult.StatusCode);
    Assert.AreEqual(400, okResult.StatusCode);
}
</code></pre>

<p>and i am okresult as null ! <strong>and not able to get okResult.StatusCode</strong></p>
",https://stackoverflow.com/questions/58992517/moq-unit-testing-in-c-web-api,"['c#', 'unit-testing', 'moq']",3823,True,2,3
Django Reverse Not Found When Unit-Testing,"<p>I am writing unit-tests for a Django app. The app works as expected. However, one of the new tests fails because the system is not able to find a reverse match for a view name. What am I missing?</p>

<blockquote>
  <p>django.urls.exceptions.NoReverseMatch: Reverse for
  'video_uploader.list_videos' not found. 'video_uploader.list_videos'
  is not a valid view function or pattern name.</p>
</blockquote>

<p><strong>app/tests.py</strong></p>

<pre><code>from django.test import TestCase
from .models import Video
from .views import *
from django.db import models
from django.utils import timezone
from django.urls import reverse

class VideoTest(TestCase):

    def create_video(self, name=""Test Video"", creation_date=timezone.now, videofile=""/video/""):
        return Video.objects.create(name=name, videofile=videofile)

    def test_video_creation(self):
        video = self.create_video()
        self.assertTrue(isinstance(video, Video))
        self.assertEqual(video.__str__(), video.name + "": "" + str(video.videofile))

    def test_videos_list_view(self):
        video = self.create_video()
        url = reverse(""video_uploader.list_videos"")
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertIn(video.name, response.content)
</code></pre>

<p><strong>app/urls.py</strong></p>

<pre><code>from django.urls import path

from . import views

app_name = 'video_uploader'
urlpatterns = [
    path('upload', views.upload_video, name='upload_video'),
    path('', views.list_videos, name='list_videos'),
]
</code></pre>
",https://stackoverflow.com/questions/58735105/django-reverse-not-found-when-unit-testing,"['python', 'django', 'django-views']",2184,True,2,1
Unit testing class with own coroutine scope,"<p>I have a class that looks something like</p>

<pre><code>class Foo {
  private val scope = Job() + Dispatchers.IO
  val emissions = PublishSubject.create&lt;Bar&gt;()

  fun doSomething() {
    scope.launch {
      // Do a whole bunch of work...
      withContext(Dispatchers.Main) emissions.onNext(bar)
    }
  }
}
</code></pre>

<p>And I'm trying to come up with a way to unit test it. I've tried making the scope injectable and writing something like</p>

<pre><code>@Test fun testFoo() = runBlockingTest {
  Dispatchers.setMain(TestCoroutineDispatcher())
  val foo = Foo(this)
  foo.doSomething()
  foo.emissions.assertStuff()
}
</code></pre>

<p>but that doesn't seem to work. The assertion happens before the coroutine inside <code>doSomething()</code> has finished.</p>

<p>I've also tried making this dispatchers injectable, providing <code>Dispatchers.Unconfined</code>, but that didn't help either. Is there something wrong with this approach?</p>
",https://stackoverflow.com/questions/58262804/unit-testing-class-with-own-coroutine-scope,"['kotlin', 'kotlin-coroutines']",646,False,2,2
Good practices for unit-testing class hierarchies,"<p>What are common/widely accepted practices for unit testing class hierarchies? </p>

<p>I've tried to look for different questions that are related to this problem, but couldn't find comprehensive one.</p>

<p>Let's suppose there is a hierarchy under test.</p>

<pre><code>class Base 
{
        int base_internal() { return 10;}                

    public:
        int virtual do_f() { return 0; }

        int execute() {
            return do_f()*base_internal();
        }
};

class DerrivedA : public Base
{
        int a_specefic() { return 4; }

    public:
        int virtual do_f()  { return a_specefic(); }
};


class DerrivedB : public Base
{
        int b_specefic() { return 8; }

    public:
        int virtual do_f()  { return b_specefic(); }
};

</code></pre>

<p>Now for unit testing infrastructure I am thinking about two strategies here.</p>

<p><strong>Strategy 1.</strong>  Have ""tester"" class for each type, derive from appropriate class and do the testing</p>

<pre><code>class TestForBase : public Base {...};
class TestForDerrivedA : public DerrivedA {...};
class TestForDerrivedB : public DerrivedB {....};
</code></pre>

<p><strong>Strategy 2.</strong> Use ""concertized"" version of visitor design pattern, (which will have single TestVisitor), than modify each class under test with accept() method,  and do the testing inside visit() of Tester class</p>

<pre><code>class Base 
{
        void accept(Tester&amp; t);
        int base_internal();

    public:
        int virtual do_f();
        int execute();
};


class Derrived : public Base
{
        void accept(Tester&amp; t);
        int a_specefic();

    public:
        int virtual do_f();
};

struct Tester
{
        void visit(Base* b)  { ... };
        void visit(Derrived* d) { ... } ;
};

</code></pre>

<p>What are the other options?</p>
",https://stackoverflow.com/questions/55635830/good-practices-for-unit-testing-class-hierarchies,"['c++', 'unit-testing', 'testing', 'class-hierarchy']",394,False,2,0
Unit testing of a class using nose,"<p>Define a nose test class 'TestingCircleCreation' which tests the behavior of '<strong>init</strong>' method with below specified four tests.</p>

<ol>
<li><p>Define a nose test method 'test_creating_circle_with_numeric_radius', which creates a circle with radius 2.5 and check if it's radius matches to value 2.5</p></li>
<li><p>Define a nose test method 'test_creating_circle_with_negative_radius', which checks if ValueError exception is raised with the error message ""radius must be between 0 and 1000 inclusive"", while creating circle of radius -2.5 . </p></li>
</ol>

<p>3.Define a nose test method 'test_creating_circle_with_greaterthan_radius', which checks if ValueError exception is raised with the error message ""radius must be between 0 and 1000 inclusive"" , while creating circle of radius 1000.1</p>

<ol start=""4"">
<li>Define a nose test method 'test_creating_circle_with_nonnumeric_radius', which checks if TypeError exception is raised with the error message ""radius must be a number"", while creating circle of radius 'hello' . </li>
</ol>

<p>i am not getting the expected output.
Please suggest</p>

<p>Code used:</p>

<p>class TestCircleCreation(unittest.TestCase):</p>

<pre><code>def test_creating_circle_with_numeric_radius(self):

    c1=Circle(2.5)
    self.assert_equal(c1.radius,2.5)


def test_creating_circle_with_negative_radius(self):

    c1=Circle(2.5)
    self.assert_equal(c1.radius,2.5)
    self.assert_raises(ValueError, Circle, -2.5)


def test_creating_circle_with_greaterthan_radius(self):

    c1=Circle(2.5)
    self.assert_equal(c1.radius,2.5) 
    self.assert_raises(ValueError, Circle, 1000.1)     


def test_creating_circle_with_nonnumeric_radius(self):

    c1=Circle(2.5)
    self.assert_equal(c1.radius,2.5)
    self.assert_raises(TypeError, Circle, 'hello') 
</code></pre>
",https://stackoverflow.com/questions/55494586/unit-testing-of-a-class-using-nose,"['python', 'python-3.x', 'nose']",11943,True,2,3
"Unit Testing RxJava onComplete, onNext and onError","<p>I am unable to find a way to unit test the onComplete, onNext and onError cases for RxJava in android. </p>

<p>TestSubscriber seems to solve the problem, but being new to RXJava, I am still not finding how to do so.</p>

<pre class=""lang-java prettyprint-override""><code>MyApi.method()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(object : Observer&lt;SettleCodeResponse&gt; {
        override fun onCompleted() {
        }

        override fun onError(e: Throwable) {
            view.hideProgress()
            Logger.logError(TAG, e.message)
        }

        override fun onNext(response: SettleCodeResponse) {
            view.hideProgress()
            process(response)
        }
    })
</code></pre>
",https://stackoverflow.com/questions/57520077/unit-testing-rxjava-oncomplete-onnext-and-onerror,"['java', 'android', 'unit-testing', 'kotlin', 'rx-java']",1591,True,2,2
Unit-testing of custom NLog filter class,"<p>While implementing custom NLog filter <a href=""https://github.com/NLog/NLog/wiki/Filtering-log-messages#fully-dynamic-filtering"" rel=""nofollow noreferrer"">https://github.com/NLog/NLog/wiki/Filtering-log-messages#fully-dynamic-filtering</a> I tried to rely on <code>WhenMethodFilter</code>, which accepts lambda callback <code>ShouldLogEvent</code>. However to unit test that callback lambda I need to make it public in the class that generates the config, which is not ideal - I hate making methods public just for the sake of testing.</p>

<pre><code>    private void ReconfigureNlog(object state)
    {
        var nlogConfig = ConstructNlogConfiguration();
        foreach (var rule in nlogConfig.LoggingRules)
        {
            rule.Filters.Add(new WhenMethodFilter(ShouldLogEvent));
        }

        // TODO: maybe no need to reconfigure every time but just modify filter reference?
        NLog.Web.NLogBuilder.ConfigureNLog(nlogConfig);
    }
</code></pre>

<p>Another approach would be to inherit <code>Filter</code> base class and try to cover it with unit tests. But the issue that it does not have a public interface :</p>

<pre><code>internal FilterResult GetFilterResult(LogEventInfo logEvent)
protected abstract FilterResult Check(LogEventInfo logEvent);
</code></pre>

<p>which makes it also not testable unless I make my own methods public. As much as this seems to be a small issue, I'm curious if there is a better way. From my perspective, making <code>GetFilterResult</code> internal is absolutely unnecessary, although it kinda following best design practices. Thoughts?</p>

<p>Update 1. Code of the class to be tested:</p>

<pre><code>public class TenancyLogFilter: Filter
{
    private readonly ITenancyLoggingConfiguration _loggingConfigurationConfig;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public TenancyLogFilter(ITenancyLoggingConfiguration loggingConfigurationConfig, IHttpContextAccessor httpContextAccessor)
    {
        _loggingConfigurationConfig = loggingConfigurationConfig;
        _httpContextAccessor = httpContextAccessor;
    }

    protected override FilterResult Check(LogEventInfo logEvent)
    {
        var result = FilterResult.Neutral;

        if (CanEmitEvent(logEvent.Level))
        {
            result = FilterResult.Log;
        }

        return result;
    }

    private LogLevel GetMinLogLevel()
    {
        var level = LogLevel.Trace;
        if (!_loggingConfigurationConfig.TenantMinLoggingLevel.Any())
            return level;
        var context = _httpContextAccessor?.HttpContext;

        if (context == null)
            return level;


        if (context.Request.Headers.TryGetValue(CustomHeaders.TenantId, out var tenantIdHeaders))
        {
            var currentTenant = tenantIdHeaders.First();
            if (_loggingConfigurationConfig.TenantMinLoggingLevel.ContainsKey(currentTenant))
            {
                level = _loggingConfigurationConfig.TenantMinLoggingLevel[currentTenant];
            }
        }

        return level;
    }

    private bool CanEmitEvent(LogLevel currentLogLevel)
    {
        return currentLogLevel &gt;= GetMinLogLevel();
    }
}
</code></pre>
",https://stackoverflow.com/questions/58667155/unit-testing-of-custom-nlog-filter-class,"['c#', 'testing', 'nlog']",200,True,2,2
Unit testing of &quot;renaming files&quot; in Python,"<p>Suppose I have the following function and I need to unit test it:</p>

<pre><code>def move_files_to(files, path):
for file in files:
    os.rename(file, path + ""/"" + file)
</code></pre>

<p>my thoughts on this topic:</p>

<p>Mocking os.rename would lead to no outcome, on the other hand, having files and renaming them would be ""doing I/O"" which should be avoided in unit tests. Please correct me, if I am wrong. Does testing make sense here?</p>
",https://stackoverflow.com/questions/56760486/unit-testing-of-renaming-files-in-python,"['python', 'python-3.x', 'unit-testing']",1606,True,2,3
Best Practices for Unit Testing Builder Objects?,"<p>There is great debate about whether or not setters/getters should be unit tested.</p>

<p>Example
<a href=""https://stackoverflow.com/questions/6197370/should-unit-tests-be-written-for-getter-and-setters"">Should unit tests be written for getter and setters?</a></p>

<p>I believe that builder objects fall within the same conversation. I want to know best practices for unit testing a builder object. Here are my thoughts.</p>

<p>i. confirm that builder object can be created</p>

<p>ii. confirm that output reflects input</p>

<p>iii. confirm that omitted constructs will throw exception (if they are required)</p>

<p>Additionally, if the builder object is required for instantiating another object, does it make sense to also create a test to confirm that the second object instantiates with given builder? Any critiques on what I am missing or should omit is appreciated.</p>

<pre><code>@RunWith(AndroidJUnit4.class)
public class MyBuilderTest {

    private Context mContext;
    private ApiClient mApiClient;
    private Profile mProfileBuilder;
    private ProfilePojo mProfileSampleResponse;

    @Before
    public void setUp() {
        mContext = InstrumentationRegistry.getTargetContext();
        mProfileSampleResponse= new Gson().fromJson(Utils.getLocalJsonFile(mContext,
                R.raw.profile_info), ProfilePojo.class);
    }

    @Test
    public void checkLocalProfileResponse() {
        assertNotNull(mProfileSampleResponse);
    }

    @Test
    public void checkProfileBuilder() {
        mProfileBuilder  = new Profile.ProfileBuilder()
                .setFirstName(mProfileSampleResponse.firstName)
                .setLastName(mProfileSampleResponse.lastName)
                .isVerified(mProfileSampleResponse.isVerified)
                .create();

        assertNotNull(mProfileBuilder);
        assertNotNull(mProfileBuilder.getFirstName());
        assertNotNull(mProfileBuilder.getLastName());

        assertEquals(mProfileSampleResponse.isVerified, mProfileBuilder.getIsVerified);
        assertEquals(mProfileSampleResponse.firstName, mProfileBuilder.getFirstName);
        assertEquals(mProfileSampleResponse.lastName, mProfileBuilder.getLastName);
    }

    @Test
    public void checkApiClientBuilder() {
        mApiClient= new ApiClient(mContext, mProfileBuilder);

        assertNotNull(mApiClient);
    }

}
</code></pre>

<p>In my case, I also need to test request and responses. The profile information I build with the ProfileBuilder can be passed into the ApiClient and the ApiClient will make request for me. Should all of this be inside of one test class?</p>
",https://stackoverflow.com/questions/56658417/best-practices-for-unit-testing-builder-objects,"['java', 'android', 'unit-testing', 'junit']",208,False,2,0
Unit Testing IHttpActionResult without casting return type,"<p>I have a web API controller with a method like (truncated non-relevant bits):</p>

<pre class=""lang-cs prettyprint-override""><code>[HttpGet]
public IHttpActionResult Order(int orderId) {
    // ...
    var response = new OrderResponse {
        Data = orderData,
        Message = message,
    };
    return Json(response);
}
</code></pre>

<p>I have a test that makes an assertion about the value of the expected <code>JsonResult&lt;OrderResponse&gt;.Content</code>.</p>

<p>Since the interface <code>IHttpActionResult</code> does not declare <code>Content</code>, I am currently casting the result in the unit test to a <code>JsonResult</code>.  However, this requires my test to know how the return is implemented in my controller, and I'd like to achieve looser coupling, if possible, so that my tests don't break if the response implementation changes.</p>

<pre class=""lang-cs prettyprint-override""><code>[TestCase(-1, ""The requested order (-1) was not found."")]
public void Test_Returns_NotFound_For_NonExistent_OrderId(int orderId, string expected) {
    var sut = new OrderController()
    // ...
    var result = sut.Order(orderId);

    // I am doing this to get access to `Content`:
    var materializedResult = result as JsonResult&lt;OrderResponse&gt;;

    expected.Should().BeEquivalentTo(materializedResult.Content.Message)
}
</code></pre>
",https://stackoverflow.com/questions/56242027/unit-testing-ihttpactionresult-without-casting-return-type,"['c#', 'asp.net', 'asp.net-mvc', 'unit-testing']",980,True,2,2
Unit testing: getText is not a function,"<p>I'm new to unit testing and I'm trying to select an ID to select its text and check if it equals 'Inbox'. I'm getting a</p>

<blockquote>
  <p>TypeError in ""User visits Quick Add Task starts with a blank task"" elem.getText is not a function</p>
</blockquote>

<p>and I don't understand why.
Test source code <a href=""https://pastebin.com/77qUEnpB"" rel=""nofollow noreferrer"">here</a>.</p>

<pre><code>describe('User visits Quick Add Task', () =&gt; {
    it('starts with a blank task', () =&gt; {
        browser.url('http://localhost:8080/');

        const elem = $('#inbox-clickable');
        console.log(elem.getText());

        assert.equal(elem.getText(), 'Inbox');

    })
});
</code></pre>
",https://stackoverflow.com/questions/57541520/unit-testing-gettext-is-not-a-function,"['mocha.js', 'chai', 'webdriver-io']",4000,True,2,1
Unit testing ember-concurrency tasks and yields,"<p>We have a lot of code in our project that isn't covered because of ember concurrency tasks.</p>

<p>Is there a straightforward way of unit testing an controller that contains something like the following:</p>

<pre><code>export default Controller.extend({
    updateProject: task(function* () {
        this.model.project.set('title', this.newTitle);
        try {
            yield this.model.project.save();
            this.growl.success('success');
        } catch (error) {
            this.growl.alert(error.message);
        }
    })
});```
</code></pre>
",https://stackoverflow.com/questions/58452244/unit-testing-ember-concurrency-tasks-and-yields,"['javascript', 'unit-testing', 'ember.js', 'ember-testing', 'ember-concurrency']",695,True,2,1
Azure Functions unit-testing errors (TimerTrigger. HttpFunction),"<p>I am currently following this guide (<a href=""https://learn.microsoft.com/en-us/azure/azure-functions/functions-test-a-function"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/azure/azure-functions/functions-test-a-function</a>) for adding testing to my Azure Functions application.</p>

<p>Currently I have built out 8 Azure Functions which all work well, I have also added a Functions.Tests project and referenced the Azure Functions project within it. </p>

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

<p>Here is what the Functions.Tests currently look like.</p>

<pre><code>using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Xunit;

namespace Functions.Tests
{
public class FunctionsTests
{
    private readonly ILogger logger = TestFactory.CreateLogger();

    [Fact]
    public async void Http_trigger_should_return_known_string()
    {
        var request = TestFactory.CreateHttpRequest(""name"", ""Bill"");
        var response = (OkObjectResult)await HttpFunction.Run(request, logger);
        Assert.Equal(""Hello, Bill"", response.Value);
    }

    [Theory]
    [MemberData(nameof(TestFactory.Data), MemberType = typeof(TestFactory))]
    public async void Http_trigger_should_return_known_string_from_member_data(string queryStringKey, string queryStringValue)
    {
        var request = TestFactory.CreateHttpRequest(queryStringKey, queryStringValue);
        var response = (OkObjectResult)await HttpFunction.Run(request, logger);
        Assert.Equal($""Hello, {queryStringValue}"", response.Value);
    }

    [Fact]
    public void Timer_should_log_message()
    {
        var logger = (ListLogger)TestFactory.CreateLogger(LoggerTypes.List);
        TimerTrigger.Run(null, logger);
        var msg = logger.Logs[0];
        Assert.Contains(""C# Timer trigger function executed at"", msg);
    }
}
}
</code></pre>

<p>However I am getting the following errors within FunctionsTests.cs</p>

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

<p>I have tried all the suggested fixes from Visual Studio and checked resources online but with no luck. Perhaps I am missing a reference? I'm not sure as I have followed the guide word for word.</p>

<p>Example Azure Function used:</p>

<pre><code>using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace Exemplar
{
public static class getCase
{
    [FunctionName(""getCase"")]
    public static async Task&lt;IActionResult&gt; Run(
        [HttpTrigger(AuthorizationLevel.Function, ""get"", Route = ""v1/case/caseId"")] HttpRequest req,
        ILogger log)
    {
        log.LogInformation(""C# HTTP trigger function processed a request."");

        string name = req.Query[""name""];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        return name != null
            ? (ActionResult)new OkObjectResult($""Hello, {name}"")
            : new BadRequestObjectResult(""Please pass a name on the query string or in the request body"");
    }
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/58879231/azure-functions-unit-testing-errors-timertrigger-httpfunction,"['c#', 'azure', 'unit-testing', 'testing', 'azure-functions']",1224,True,1,2
Differences in mounting components in unit testing,"<p>So I've seen multiple approaches to rendering components for unit tests over the time, the testing framework in question is not relevant..
I'm wandering <strong>is there any advantages or disadvantages to any of the following approaches?</strong></p>

<p>for example, is there any chance of memory leaks in any of the following approaches?</p>

<p>1st approach, using a shared variable between all tests and mounting before each. (main problem I can think of overriding the default component props can be tricky)</p>

<pre><code>describe('some describe', () =&gt; {
    let component
    const baseProps = {}

    beforeEach(() =&gt; {
        component = shallow(&lt;MyComponent {...baseProps} /&gt;)
    })

    it('test 1', () =&gt; {
        expect(component).to.something
    })

    it('test 2', () =&gt; {
        expect(component).to.something
    })
})
</code></pre>

<p>2nd approach, calling renderComponent in the beginning of each test but still using a shared variable</p>

<pre><code>describe('some describe', () =&gt; {
    let component;

    function renderComponent(props = {}) {
        const baseProps = {}
        component = shallow(&lt;MyComponent {...baseProps} {...props} /&gt;)
    }

    it('test 1', () =&gt; {
        const props = {}
        renderComponent(props)
        expect(component).to.something
    })

    it('test 2', () =&gt; {
        renderComponent()
        expect(component).to.something.else
    })
})
</code></pre>

<p>3rd approach, mounting the component in each test</p>

<pre><code>describe('some describe', () =&gt; {
    const baseProps = {}

    it('test 1', () =&gt; {
        const props = {}
        const component = shallow(&lt;MyComponent {...baseProps} {...props} /&gt;)
        expect(component).to.something
    })

    it('test 2', () =&gt; {
        const props = {}
        const component = shallow(&lt;MyComponent {...baseProps} {...props} /&gt;)
        expect(component).to.something.else
    })
})
</code></pre>

<p>4th approach, using a helper function that returns an instance for the test</p>

<pre><code>describe('some describe', () =&gt; {
    function renderComponent(props = {}) {
        const baseProps = {}
        return shallow(&lt;MyComponent {...baseProps} {...props} /&gt;)
    }

    it('test 1', () =&gt; {
        const component = renderComponent()
        expect(component).to.something
    })

    it('test 2', () =&gt; {
        const component = renderComponent()
        expect(component).to.something.else
    })
})
</code></pre>
",https://stackoverflow.com/questions/55899033/differences-in-mounting-components-in-unit-testing,"['javascript', 'unit-testing', 'mocha.js', 'jestjs', 'enzyme']",42,True,1,1
Unit testing using spock for Amazon Dynamodb,"<p>I am new in using dynamodb, and I tried to do uniting testing on one of the method. </p>

<p>When I try to mock </p>

<pre><code>DeleteItemSpec deleteItemSpec = new DeleteItemSpec().withPrimaryKey(new PrimaryKey(""id"", id, ""date"", date).withConditionExpression(""id = :id"")
</code></pre>

<p>It returns <code>NPE</code>. How can I mock this with many properties?</p>

<p>Sorry for such a dumb question, but tried whole night for solution.</p>

<pre class=""lang-java prettyprint-override""><code>public void delete(String id) {
    Item item = null;
    Iterator&lt;Item&gt; iterator = getId(id);
    while (iterator.hasNext()) {
        item = iterator.next();
        DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
            //get null pointer on below line
            .withPrimaryKey(new PrimaryKey(""id"", id, ""date"", item.getString(""date"")))
            .withConditionExpression(""id = :id"")
            .withValueMap(new ValueMap()
            .withString("":id"", id))
            .withReturnValues(ReturnValue.ALL_OLD);

        try {
            table.deleteItem(deleteItemSpec);
        } catch (Exception e) {e.getLocalizedMessage(), e);
            throw new dynamoDBException(""..."")
        }
    }
}

</code></pre>
",https://stackoverflow.com/questions/57648425/unit-testing-using-spock-for-amazon-dynamodb,"['java', 'unit-testing', 'nullpointerexception', 'spock']",269,False,1,0
Coroutine Unit Testing Fails for the Class,"<p>I am facing a weird issue while unit testing Coroutines. There are two tests on the class, when run individually, they both pass and when <em>I run the complete test class, one fails with assertion error</em>.
I am using <code>MainCoroutineRule</code> to use the <code>TestCoroutineScope</code> and relying on the latest Coroutine Testing Library
Here is the test :</p>

<pre><code>    @Test
    fun testHomeIsLoadedWithShowsAndFavorites() {
        runBlocking {
            // Stubbing network and repository calls
            whenever(tvMazeApi.getCurrentSchedule(""US"", currentDate))
                .thenReturn(getFakeEpisodeList())
            whenever(favoriteShowsRepository.allFavoriteShowIds())
                .thenReturn(arrayListOf(1, 2))
        }

        mainCoroutineRule.runBlockingTest {
            // call home viewmodel
            homeViewModel.onScreenCreated()
            // Check if loader is shown
            assertThat(LiveDataTestUtil.getValue(homeViewModel.getHomeViewState())).isEqualTo(Loading)
            // Observe on home view state live data
            val homeViewState = LiveDataTestUtil.getValue(homeViewModel.getHomeViewState())
            // Check for success data
            assertThat(homeViewState is Success).isTrue()
            val homeViewData = (homeViewState as Success).homeViewData
            assertThat(homeViewData.episodes).isNotEmpty()
            // compare the response with fake list
            assertThat(homeViewData.episodes).hasSize(getFakeEpisodeList().size)
            // compare the data and also order
            assertThat(homeViewData.episodes).containsExactlyElementsIn(getFakeEpisodeViewDataList(true)).inOrder()
        }
    }
</code></pre>

<p>The other test is almost similar which tests for Shows without favorites. I am trying to test <code>HomeViewModel</code> method as:</p>

<pre><code>        homeViewStateLiveData.value = Loading
        val coroutineExceptionHandler = CoroutineExceptionHandler { _, exception -&gt;
            onError(exception)
        }

        viewModelScope.launch(coroutineExceptionHandler) {
            // Get shows from network and favorites from room db on background thread
            val favoriteShowsWithFavorites = withContext(Dispatchers.IO) {
                val favoriteShowIds = favoriteShowsRepository.allFavoriteShowIds()
                val episodes = tvMazeApi.getCurrentSchedule(COUNTRY_US, currentDate)
                getShowsWithFavorites(episodes, favoriteShowIds)
            }
            // Return the combined result on main thread
            withContext(Dispatchers.Main) {
                onSuccess(favoriteShowsWithFavorites)
            }
        }
    }
</code></pre>

<p>I cannot find the actual cause of why the tests if run separately are passing and when the complete class is tested, one of them is failing. Pls help if I am missing something</p>
",https://stackoverflow.com/questions/57239510/coroutine-unit-testing-fails-for-the-class,"['android', 'unit-testing', 'kotlin-coroutines']",677,True,1,1
Unit testing DAO layer with H2 database,"<p>After a lot of reading in internet, i found out that it seems to be a good practice to use a in-memory DB like H2 to unit test the DAO layer. The idea behind is to avoid working with the production DB. </p>

<p>Fine, so I set up a H2 DB and activated the H2 PostgreSQL Compatibility Mode, since my production DB is on Postgres. The problem I'm now facing: when I run on H2 the original SQL queries in order to build the test DB, this query is not accepted as valid by H2: </p>

<pre class=""lang-sql prettyprint-override""><code>ALTER SEQUENCE MYERP.ecriture_comptable_id_seq OWNED BY MYERP.ecriture_comptable.id;
</code></pre>

<p>I guess that using the PostgreSQL Compatibility Mode is not a guarantee that all the Postgres specific syntax will be accepted by H2. And probably this would also happen with other DB such as MySQL. </p>

<p>So what's the point in using a h2 database in this case?
Did I miss something?</p>
",https://stackoverflow.com/questions/56891415/unit-testing-dao-layer-with-h2-database,"['java', 'postgresql', 'unit-testing', 'h2', 'dao']",971,True,1,1
How to mock AWS sqs call for unit testing,"<p>I'm using AWS SQS queue in a Node application and I have to write the unit test cases for the same. For that, I want to mock the SQS function call <code>sendMessage()</code> in the test files so, what should I do?</p>

<p>I have tried using <code>aws-sdk-mock</code> but while making the call to the <code>sendMessage()</code>, the function is trying to connect to the Queue URL.</p>

<p><strong>Test File</strong></p>

<pre><code>import AWSMock from 'aws-sdk-mock'
import sendMessage from '../api/sqs/producer'

describe.only('Test case for SQS SendMessage', () =&gt; {
  it('should return the UserEvent', async () =&gt; {
    AWSMock.mock('SQS', 'sendMessage', () =&gt; Promise.resolve('Success'))
    const res = await sendMessage('testURL', 'data')
    console.log('RES', res.response.data)
  })
})
</code></pre>

<p><strong>Producer File</strong></p>

<pre><code>const AWS = require('aws-sdk')

const sqs = new AWS.SQS({
  region: 'us-east-1'
})

const sendMessage = async (msg, queueUrl) =&gt; {
  try {
    const params = {
      MessageBody: JSON.stringify(msg),
      QueueUrl: queueUrl
    }
    const res = await sqs.sendMessage(params).promise()
    return res
  } catch (err) {
    console.log('Error:', `failed to send message ${err}`)
    throw new Error(err)
  }
}

export { sendMessage as default }
</code></pre>

<p>In above code, I'm expecting the <code>Success</code> as a return value in <strong>res</strong></p>

<p><strong>Output</strong></p>

<pre class=""lang-sh prettyprint-override""><code> FAIL  tests/sendMessage.test.js
  ● Console

    console.log api/sqs/producer/index.js:16
      Error: failed to send message UnknownEndpoint: Inaccessible host: `testurl'. This service may not b
e available in the `us-east-1' region.

  ● Test case for SQS SendMessage › should return the UserEvent

    UnknownEndpoint: Inaccessible host: `testurl'. This service may not be available in the `us-east-1' r
egion.
</code></pre>
",https://stackoverflow.com/questions/57585620/how-to-mock-aws-sqs-call-for-unit-testing,"['javascript', 'node.js', 'unit-testing', 'jestjs', 'aws-sdk']",32875,True,15,4
code not throwing exception in unit testing,"<p>The following code should throw an exception in case of unexpected situation</p>

<pre><code>     def remove(loginInfo: LoginInfo): Future[Unit] = Future{
        println(""In PasswordRepository, removing password"")//TODOM - any print statements should not reveal confidential information
        val bucketId = utilities.bucketIDFromEmail(loginInfo.providerKey)
        val userFutureOption = userRepo.findOne(UserKeys(bucketId,loginInfo.providerKey,loginInfo))
        userFutureOption.flatMap(userOption =&gt;{ userOption match {
          case Some(user) =&gt; {
            println(""setting password info to None"") //TODOM - need to check that passwordInfo isn't empty

val updatedUser = User(user.id,
              UserProfile(Some(InternalUserProfile(user.profile.internalProfileDetails.get.loginInfo,
                bucketId,
                user.profile.internalProfileDetails.get.confirmed,
                None)),ExternalUserProfile(user.profile.externalProfileDetails.email,
                user.profile.externalProfileDetails.firstName,
                user.profile.externalProfileDetails.lastName,
                user.profile.externalProfileDetails.password))) //don't need to store password explicitly. It is in PasswordInfo field already
            println(""updated user ""+updatedUser)
            val userFutureOption = userRepo.update(updatedUser)
            userFutureOption.map(userOption =&gt; {
              userOption match {//do nothing in Some as the function returns Unit
                case Some(user) =&gt; {
                  Unit
                }
                case None =&gt; {
                  println(""error in deleting password info of the user"")
                  //TODOM - funtion is not throwing the Exception. Need to check
                  throw new Exception(messagesApi(""error.passwordDeleteError"")(langs.availables(0))) 
                }
              }
            })
          }
          case None =&gt; {
            println(""user not found. Can't remove password info. This shouldn't have happened"")
            throw new Exception(messagesApi(""error.passwordDeleteError"")(langs.availables(0)))
          }
        }
        })
      }
</code></pre>

<p>When I unit-test the code, the code doesn't throw the exception. Why?</p>

<pre><code>  ""PasswordRepository Specs"" should {
    ""should return error if password cannot be deleted for an existing user"" in {

      val user = repoTestEnv.testEnv.user 
      when(repoTestEnv.mockUserRepository.findOne(ArgumentMatchers.any())).thenReturn(Future{Some(repoTestEnv.testEnv.user)})
      when(repoTestEnv.mockUserRepository.update(ArgumentMatchers.any())).thenReturn(Future{None}) //this should trigger the throw exception code
      val passwordRepository = new PasswordRepository(repoTestEnv.testEnv.mockHelperMethods,repoTestEnv.mockUserRepository,repoTestEnv.testEnv.messagesApi,repoTestEnv.testEnv.langs)
          val exception = intercept[java.lang.Exception]( await[Unit](passwordRepository.remove(repoTestEnv.testEnv.loginInfo))(Timeout(Duration(5000,""millis""))))
      println(s""exception is ${exception}"")
      exception.getMessage() mustBe repoTestEnv.testEnv.messagesApi(""error.passwordDeleteError"")(repoTestEnv.testEnv.langs.availables(0))

    }
  }
</code></pre>

<p>I get the error</p>

<pre><code>=== starting new test case execution ====
In PasswordRepository, removing password
setting password info to None
updated user User(11111111-1111-1111-1111-111111111111,UserProfile(Some(InternalUserProfile(LoginInfo(credentials,test@test.com),1,true,None)),ExternalUserProfile(test@test.com,fn,ln,Some(somePassword))))
error in deleting password info of the user
=== ending test case execution ====

Expected exception java.lang.Exception to be thrown, but no exception was thrown
</code></pre>

<p>Update
The behavior is peculiar because the unit tests work for <code>add</code> method which is very similar to the <code>remove</code> method.</p>

<pre><code> def add(loginInfo: LoginInfo, authInfo: PasswordInfo): Future[PasswordInfo] = {
    println(s""in PasswordRepository add ${loginInfo.providerID}, ${loginInfo.providerKey}, ${authInfo.hasher}, ${authInfo.password},${authInfo.salt}"")
    val bucketId = utilities.bucketIDFromEmail(loginInfo.providerKey)
    val userFutureOption = userRepo.findOne(UserKeys(bucketId,loginInfo.providerKey,loginInfo))
    userFutureOption.flatMap(userOption =&gt;{ userOption match {
      case Some(user) =&gt; {
        println(""adding password info ""+ authInfo+ ""to user ""+user) //TODOM - need to check that passwordInfo isn't empty
        val updatedUser = User(user.id,
          UserProfile(Some(InternalUserProfile(user.profile.internalProfileDetails.get.loginInfo,
            bucketId,
            user.profile.internalProfileDetails.get.confirmed,
            Some(authInfo))),ExternalUserProfile(user.profile.externalProfileDetails.email,
            user.profile.externalProfileDetails.firstName,
            user.profile.externalProfileDetails.lastName,
            user.profile.externalProfileDetails.password))) //don't need to store password explicitly. It is in PasswordInfo field already
        println(""updated user ""+updatedUser)
        //TODOM is there a risk if email id gets updated. Then it should be updated in both email and loginInfo
        val userUpdateFutureOption = userRepo.update(updatedUser)
        userUpdateFutureOption.map(userOption =&gt; {
          userOption match {
          case Some(user) =&gt; {
            //TODOM - should not access PasswordInfo directly
            println(""returning PassswordInfo ""+user.profile.internalProfileDetails.get.passwordInfo)
            //TODOM - check for empty for both internalProfileDetails and passwordInfo in Functional way
            user.profile.internalProfileDetails.get.passwordInfo.get
          }
          case None =&gt; {
            println(""error in updating password info of the user"")
            //authInfo //TODOM - I should throw an exception from this Future.
            throw new Exception(messagesApi(""error.passwordConfigureError"")(langs.availables(0)))
          }
        }
        })
      }
      case None =&gt; {
        println(""user not found. Can't set password info. This shouldn't have happened"")
        throw new Exception(messagesApi(""error.passwordConfigureError"")(langs.availables(0)))
      }
    }
    })
  }
</code></pre>

<p>The following test case passes for <code>add</code></p>

<pre><code>  ""PasswordRepository Specs"" should {
    ""should return error if password cannot be updated for an existing user when adding a password"" in {

      val newPassword = PasswordInfo(""newHasher"",""newPassword"",Some(""newSalt""))
      val user = repoTestEnv.testEnv.user

      when(repoTestEnv.mockUserRepository.findOne(ArgumentMatchers.any())).thenReturn(Future{Some(repoTestEnv.testEnv.user)})
      when(repoTestEnv.mockUserRepository.update(ArgumentMatchers.any())).thenReturn(Future{None})
      val passwordRepository = new PasswordRepository(repoTestEnv.testEnv.mockHelperMethods,repoTestEnv.mockUserRepository,repoTestEnv.testEnv.messagesApi,repoTestEnv.testEnv.langs)

      println(s""adding password ${newPassword}"")
      val exception = intercept[java.lang.Exception]( await[PasswordInfo](passwordRepository.add(repoTestEnv.testEnv.loginInfo,newPassword))(Timeout(Duration(5000,""millis""))))
      println(s""exception is ${exception}"")
      exception.getMessage() mustBe repoTestEnv.testEnv.messagesApi(""error.passwordConfigureError"")(repoTestEnv.testEnv.langs.availables(0))

    }
  }
</code></pre>

<p>It seems the function is not throwing any Exceptions at all because doing this doesn't work either</p>

<pre><code>val userUpdateFutureOption = userRepo.update(updatedUser)
        throw new Exception(messagesApi(""error.passwordDeleteError"")(langs.availables(0)))

        userUpdateFutureOption.map(userOption =&gt; {...}
</code></pre>

<p>but if I throw the exception at the very beginning of the code then the test passes</p>

<pre><code>val userFutureOption = userRepo.findOne(UserKeys(bucketId,loginInfo.providerKey,loginInfo))
    throw new Exception(messagesApi(""error.passwordDeleteError"")(langs.availables(0)))...
</code></pre>
",https://stackoverflow.com/questions/57101290/code-not-throwing-exception-in-unit-testing,"['scala', 'scalatest', 'playframework-2.6']",285,False,1,2
Jest AJAX unit testing not returning data,"<p>I am trying to test the following AJAX call using Jest (using <a href=""https://jestjs.io/docs/en/asynchronous.html"" rel=""nofollow noreferrer"">https://jestjs.io/docs/en/asynchronous.html</a> as a reference). The AJAX call should post to my web service and return JSON data, but the test fails with an error. The test is in main.test.js, and I am running it in the Package Manager Console (in Visual Studio) using: <code>npm test</code>. </p>

<p>I have tried implementing the AJAX request using XMLHttpRequest but the test still fails with the same error and I do not get any data back. I have also tried setting the parameter async: false, but this causes the test to hang without completing. </p>

<pre><code>//main.js
function getData(handleData) {
     $.ajax({
        type: ""POST"",
        data: '{choice:""'+option+'""}',
        dataType: ""json"",
        url: ""WebServiceGrid.asmx/WebserviceFunction"",
        contentType: ""application/json; charset=utf-8"",
        success: function (response) {                                     
            handleData(response);            
        },       
        error: function (request, status, error) {
            alert(request.responseText);
        },       
    });

    function handleData(response) {
        return response;
    }
}
</code></pre>

<pre><code>//main.test.js
test('verifies getData returns data', done =&gt; {
    function handleData(data) {
        expect(data).toBe(/*some JSON data*/); 
        done();
    }
    getData(handleData);
}
</code></pre>

<p><code>package.json (Jest setup)</code>:</p>

<pre><code>""devDependencies"": {
    ""jest"": ""^24.9.0"",
    ""jest-editor-support"": ""^25.0.1""
}
""jest"": {
    ""verbose"": true,
    ""setupFiles"": [
      ""./source/setup-jest.js""
    ],
},
""scripts"": {
    ""test"": ""jest --detectOpenHandles""
}
</code></pre>

<pre class=""lang-js prettyprint-override""><code>//I am including jQuery in my setup-jest.js file:
const $ = require('jquery'); global.$ = global.jQuery = $;
</code></pre>

<p>I expect to get JSON data back from my web service but I am seeing the Jest test fail with the following error: </p>

<blockquote>
  <p>Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout. </p>
</blockquote>

<p>I have also tried increasing the Jest timeout to more than 5000ms but this did not seem to help</p>
",https://stackoverflow.com/questions/57876247/jest-ajax-unit-testing-not-returning-data,"['javascript', 'jquery', 'ajax', 'jestjs']",456,False,1,0
Repository unit-testing on a library project,"<p>I am working on a multi module project using Spring Boot. I want to write some unit tests to check my repository, services, etc. 
The repositories codes is written on a common project which is used on other projects. This project doesn't contain any starter app. It's just composed of entities, repositories and services. </p>

<p>I saw this topic (<a href=""https://stackoverflow.com/questions/37615914/how-to-test-maven-module-project-with-spring-boot"">How to test Maven module project with Spring Boot</a>) about a similar issue but I don't manage to succeed to implement it for testing my repository.</p>

<p>The exception ""NoSuchBeanDefinitionException"" is raised for the EntityARepository (see the code below) when I launch the test : I understand that the tests can access to bean that I have created on the src/main/java folder. How can I resolve this ?</p>

<p>On the test folder (test/java) of this maven project, I create three files on several packages :</p>

<pre><code>package com.domain.test
@SpringBootApplication()
public class ProjectCommonsTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProjectCommonsTestApplication.class, args);
    }
}
</code></pre>

<pre><code>package com.domain.test.repository

@RunWith(SpringRunner.class)
@DataJpaTest
public class EntityARepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private EntityARepository entityARepository;

    @Test
    public void someUnitTest(){
        //given
        //when
        //then
    }
}

</code></pre>

<p>And the application.yml file, on the folder test/resources</p>

<pre><code>spring:
  application:
    name: Spring Boot - TEST instance
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    url: ""jdbc:h2:mem:test-api;INIT=CREATE SCHEMA IF NOT EXISTS dbo\\;CREATE SCHEMA IF NOT EXISTS definitions;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false;MODE=MSSQLServer""
    name:
    password:
    username:
    initialization-mode: never
    hikari:
      schema: dbo
  jpa:
    database: H2
    database-platform: org.hibernate.dialect.H2Dialect
    show-sql: true
    hibernate:
      ddl-auto: create-drop
  test:
    database:
      replace: none

</code></pre>

<p>Have you an idea of what is wrong on my code ? The repository is well anotated and written on src/main/java on a sub-package : com.domain.repository</p>

<p>Thanks in advance.</p>

<p>EDIT : 
The trace of the error :</p>

<pre><code>
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.domain.test.repository.EntityARepository': Unsatisfied dependency expressed through field 'entityARepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.domain.repository.EntityARepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1348) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:399) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118) ~[spring-test-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44) ~[spring-boot-test-autoconfigure-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) ~[spring-test-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.0.6.RELEASE.jar:5.0.6.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.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.0.6.RELEASE.jar:5.0.6.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.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.0.6.RELEASE.jar:5.0.6.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.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.domain.repositoryEntityARepository' 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:1509) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    ... 28 common frames omitted
</code></pre>

<p>EDIT 2 : 
When I add @ContextConfiguration with the right class to be autowired, the error changes : </p>

<pre><code>package com.domain.test.repository

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = EntityARepository.class)
@DataJpaTest
public class EntityARepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private EntityARepository entityARepository;

    @Test
    public void someUnitTest(){
        //given
        //when
        //then
    }
}
</code></pre>

<pre><code>java.lang.IllegalStateException: Unable to retrieve @EnableAutoConfiguration base packages
    at org.springframework.boot.autoconfigure.AutoConfigurationPackages.get(AutoConfigurationPackages.java:76) ~[spring-boot-autoconfigure-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport.getBasePackages(AbstractRepositoryConfigurationSourceSupport.java:79) ~[spring-boot-autoconfigure-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport$1.getBasePackages(AbstractRepositoryConfigurationSourceSupport.java:73) ~[spring-boot-autoconfigure-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.data.repository.config.RepositoryConfigurationSourceSupport.lambda$getCandidates$2(RepositoryConfigurationSourceSupport.java:77) ~[spring-data-commons-2.0.7.RELEASE.jar:2.0.7.RELEASE]
    at org.springframework.data.util.LazyStreamable.stream(LazyStreamable.java:50) ~[spring-data-commons-2.0.7.RELEASE.jar:2.0.7.RELEASE]
    at org.springframework.data.util.LazyStreamable.iterator(LazyStreamable.java:41) ~[spring-data-commons-2.0.7.RELEASE.jar:2.0.7.RELEASE]
    at org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport.getRepositoryConfigurations(RepositoryConfigurationExtensionSupport.java:87) ~[spring-data-commons-2.0.7.RELEASE.jar:2.0.7.RELEASE]
    at org.springframework.data.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn(RepositoryConfigurationDelegate.java:121) ~[spring-data-commons-2.0.7.RELEASE.jar:2.0.7.RELEASE]
    at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport.registerBeanDefinitions(AbstractRepositoryConfigurationSourceSupport.java:60) ~[spring-boot-autoconfigure-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.lambda$loadBeanDefinitionsFromRegistrars$1(ConfigurationClassBeanDefinitionReader.java:358) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at java.util.LinkedHashMap.forEach(LinkedHashMap.java:676) ~[na:1.8.0_91-3-redhat]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReader.java:357) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:145) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:117) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:328) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:233) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:93) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:694) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) ~[spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) ~[spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:139) [spring-boot-test-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) [spring-test-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117) [spring-test-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108) [spring-test-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.outputConditionEvaluationReport(SpringBootDependencyInjectionTestExecutionListener.java:54) [spring-boot-test-autoconfigure-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:47) [spring-boot-test-autoconfigure-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) [spring-test-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.0.6.RELEASE.jar:5.0.6.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.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.0.6.RELEASE.jar:5.0.6.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.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.0.6.RELEASE.jar:5.0.6.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.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]

</code></pre>
",https://stackoverflow.com/questions/55517610/repository-unit-testing-on-a-library-project,"['maven', 'unit-testing', 'spring-boot']",2725,True,1,1
Unit testing routes with Mock ActivatedRoute configuration,"<p>I am configuring test spec for my component which has routes, also I have defined my spec with dependencies as follows. And the ActivatedRoute has these properties, But I don't see its object/instance being created while debugging my test spec. Also I have referred different methods of mocking ActivatedRoute but nothing is helping me. Please correct me if I am doing anything wrong </p>

<pre class=""lang-js prettyprint-override""><code>class UserInfotypeDetailComponent implements OnInit, OnDestroy {
    constructor(
        private userInfotypeDetailService: UserInfotypeDetailService,
        private appLookupService: AppLookupService,
        private router: Router,
        private activatedRoute: ActivatedRoute
    ) {}

 performAction(event: { action: string; objectKey: string | null }) {
    let extras: any = { relativeTo: this.activatedRoute };
    if (event.objectKey) {
          extras.queryParams = { objectKey: event.objectKey };
    }

    switch (event.action) {
      case ""new"":
      case ""edit"":
      case ""copy"":
      case ""view"":
        this.router.navigate([event.action], extras);
        break;
      case ""delete"":
        this.deleteRecord(event.objectKey as string);
    }
  }

}
</code></pre>

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

<pre class=""lang-js prettyprint-override""><code>{
        path: ""infotype/:id"",
        component: UserInfotypeDetailComponent,
        outlet: ""slidein"",
        children: [
          {
            path: ""new"",
            component: UserRecordFormComponent,
            data: { actionId: ""A"", buttonDesc: ""Save"" }
          },
          {
            path: ""edit"",
            component: UserRecordFormComponent,
            data: { actionId: ""E"", buttonDesc: ""Update"" }
          },
          {
            path: ""copy"",
            component: UserRecordFormComponent,
            data: { actionId: ""C"", buttonDesc: ""Save"" }
          },
          {
            path: ""view"",
            component: UserRecordFormComponent,
            data: { actionId: ""V"", actionDesc: ""View"" }
          }
        ]
      }
</code></pre>

<p>And my test spec is as follows:</p>

<pre class=""lang-js prettyprint-override""><code>beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [
              RouterTestingModule.withRoutes([]),
                BrowserAnimationsModule,
                RouterModule
            ],
            declarations: [
                UserInfotypeDetailComponent
            ],
            providers: [
                { provide: ActivatedRoute, useValue: {
                                          outlet: ""slidein"",
                                          params: of({ 
                                              id: ""0009""
                                          })
                                      }
                },
                { provide: AppLookupService, useClass: AppLookupServiceStub },
                { provide: UserInfotypeDetailService, useClass: UserInfotypeDetailServiceStub },
                { provide: Router, useClass: AppRouterStub }
            ],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    class AppRouterStub {
        navigate() {}
    }
</code></pre>

<p>And test case:</p>

<pre class=""lang-js prettyprint-override""><code>it('make expect calls to router navigate', fakeAsync(() =&gt; {
      let router = TestBed.get(Router);
      let spy = spyOn(router, 'navigate');

      component.performAction(event);

      let extras: any = { relativeTo: ActivatedRoute };
      if (event.objectKey) {
        extras.queryParams = { objectKey: event.objectKey };
      }
      fixture.detectChanges();

      expect(spy).toHaveBeenCalledWith([event.action], extras);
    }))
</code></pre>

<p>The error that it throws is:</p>

<blockquote>
  <p>""spy navigate to have been called with [ [ 'edit' ], Object({ relativeTo: Function, queryParams: Object({ objectKey: '36353539363A393C3535353E352525252525253E3E3E3E363738363735363E35363536353535' }) }) ] but actual calls were [ [ 'edit' ], Object({ relativeTo: Object({ snapshot: Object({  }), parent: Object({ params: Subject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null }) }), params: Subject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null }), queryParams: Subject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null }), testParams: Object({ id: '0009' }) }), queryParams: Object({ objectKey: '36353539363A393C3535353E352525252525253E3E3E3E363738363735363E35363536353535' }) }) ].""</p>
</blockquote>
",https://stackoverflow.com/questions/56290140/unit-testing-routes-with-mock-activatedroute-configuration,"['angular', 'typescript', 'unit-testing', 'karma-jasmine']",1918,True,1,1
NUnit unit Testing with Moq in Xamarin,"<p>I am using two interfaces for logging(NLog) in my Xamarin App</p>

<p><strong>ILoggingService</strong></p>

<pre><code>public interface ILoggingService
{
    void Info(string message);
    void Info(string format, params object[] args);

    void Error(string message);
    void Error(string format, params object[] args);
    void Error(Exception e, string message);
    void Error(Exception e, string format, params object[] args);

    void Fatal(string message);
    void Fatal(string format, params object[] args);
    void Fatal(Exception e, string message);
    void Fatal(Exception e, string format, params object[] args);

    void Debug(string message);
    void Debug(string format, params object[] args);

    void Trace(string message);
    void Trace(string format, params object[] args);

    void Warn(string message);
    void Warn(string format, params object[] args);
}
</code></pre>

<p>And Another interface </p>

<p><strong>ILogManager</strong></p>

<pre><code>public interface ILogManager
{
      ILoggingService GetLog([System.Runtime.CompilerServices.CallerFilePath]string callerFilePath = """");
}
</code></pre>

<p>In my test project I have created the Setup file like this.</p>

<pre><code>[SetUpFixture]
public class Setup
{
    public static readonly Mock&lt;IDependencyService&gt; MockedService = new Mock&lt;IDependencyService&gt;(MockBehavior.Strict);
    readonly Mock&lt;ILogManager&gt; _logManager = new Mock&lt;ILogManager&gt;(MockBehavior.Strict);
    readonly Mock&lt;ILoggingService&gt; _loggingService = new Mock&lt;ILoggingService&gt;(MockBehavior.Strict);

    [OneTimeSetUp]
    public void OneTimeSetUp()
    {
        MockedService.Setup(p =&gt; p.Get&lt;ILogManager&gt;()).Returns(_logManager.Object);
        MockedService.Setup(p =&gt; p.Get&lt;ILoggingService&gt;()).Returns(_logManager.Object.GetLog());
    }

    [OneTimeTearDown]
    public void OneTimeTearDown()
    {

    }
}
</code></pre>

<p>I think I made some mistake during mocking the interface. Because of this, I am getting the GetLog() always null.</p>

<pre><code>logger = _serviceLocator.Get&lt;ILogManager&gt;().GetLog(); // Always return null
</code></pre>

<p>Can anyone guide me to resolve my issue.? Seems like some issue in creating the stub for the mentioned interface.</p>

<p>Please help</p>
",https://stackoverflow.com/questions/54106202/nunit-unit-testing-with-moq-in-xamarin,"['xamarin', 'xamarin.forms', 'mocking', 'nunit', 'moq']",130,True,1,1
Unit Testing an implicit operator with NUnit,"<p>I'm trying to figure out how to write a unit test around an implicit conversion with NUnit.</p>

<p>So far the only way I have been able to do it is to create a static function that takes the type the object will be converted to as a parameter and instantly returns it.</p>

<pre><code>public class Foo
{
    public Foo(string name)
    {
        Name = name;
    }
    public string Name { get; set; }
}
</code></pre>

<pre><code>public class Bar
{
    public Bar(string name)
    {
        Name = name;
    }
    public string Name { get; set; }

    public static implicit operator Foo(Bar bar)
    {
        return new Foo(bar.Name);
    }
}
</code></pre>

<pre><code>[Test]
public void BarToFooImplicitConversionTest()
{
    var bar = new Bar(""FooBar"");
    var foo = ConvertBarToFooImplicitly(bar);
    foo.Name.Should().Be(""FooBar"");
}
</code></pre>

<pre><code>private static Foo ConvertBarToFooImplicitly(Foo foo)
{
    return foo;
}
</code></pre>

<p>Is there something in NUnit I'm missing or is there a better way to do this?</p>
",https://stackoverflow.com/questions/55462561/unit-testing-an-implicit-operator-with-nunit,"['c#', 'nunit']",901,True,1,1
Unit testing method that raises and exception,"<p>I try to unit-test if method responsible for returning price of given product raises an exception if we pass bad <code>item_id</code> - <code>find_price_of_given_id</code>.</p>

<p>Test:</p>

<pre><code>import unittest
from Automat import Automat
from Bank import Bank
from Item import Item
from exceptions.NoItemException import NoItemException


class AutomatTest(unittest.TestCase):

    def test_checkPriceOfGivenID(self):
        bank = Bank()
        automat = Automat(bank)
        Cola = Item(2)
        automat.add_object(Cola)
        self.assertEqual(automat.find_price_of_given_id(30), 2)

    def test_checkPriceOfGivenIDWithInvalidID(self):
        bank = Bank()
        automat = Automat(bank)
        Cola = Item(2)
        automat.add_object(Cola)
        self.assertRaises(NoItemException, automat.find_price_of_given_id(31))
</code></pre>

<p>Automat class:</p>

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


from Item import Item
from exceptions.NoItemException import NoItemException
from exceptions.NoProperAmountException import NoProperAmountException
from Coin import Coin
from decimal import *
class Automat:

    def __init__(self, _bank, objects=None):
        self.item_id = 30
        self.bank = _bank
        if objects is None:
            objects = {}


        self.objects = objects
        self.purchaseItemBank = []

    def add_object(self, obj: Item):
        id_to_assign = self.item_id
        self.objects.update({id_to_assign: obj})
        self.item_id += 1
        return id_to_assign

    def find_price_of_given_id(self, item_id):
        if self.objects.get(item_id) is not None:
            return self.objects.get(item_id).get_price()
        else:
            raise NoItemException

    def find_amount_of_given_id(self, item_id):
        if self.objects.get(item_id) is not None:
            return self.objects.get(item_id).get_amount()
        else:
            raise NoItemException

    def checkIfAmountIsPositive(self, item_id):
        if self.objects.get(item_id) is not None:
            var = True if self.objects.get(item_id).get_amount() &gt; 0 else False
            return var
        else:
            raise NoItemException

    def withdrawItem(self, item_id):
        self.objects.get(item_id).decrease()

    def getAmountOfGivenNominal(self, coinValue):
        counter = 0
        for iterator in self.bank.bank:
            if iterator.getCoinValue() == coinValue:
                counter += 1
        return counter
</code></pre>

<p>Unfortunately I got </p>

<pre><code>Error
Traceback (most recent call last):
  File ""C:\ProgramData\Anaconda3\lib\unittest\case.py"", line 59, in testPartExecutor
    yield
  File ""C:\ProgramData\Anaconda3\lib\unittest\case.py"", line 615, in run
    testMethod()
  File ""C:\Users\Admin\PycharmProjects\vending-machine\AutomatTest.py"", line 22, in test_checkPriceOfGivenIDWithInvalidID
    self.assertRaises(NoItemException, automat.find_price_of_given_id(31))
  File ""C:\Users\Admin\PycharmProjects\vending-machine\Automat.py"", line 28, in find_price_of_given_id
    raise NoItemException
exceptions.NoItemException.NoItemException



Ran 1 test in 0.003s

FAILED (errors=1)

Process finished with exit code 1
</code></pre>

<p>Item class:</p>

<pre><code>class Item:
    def __init__(self, price, amount=5):
        self.amount = amount
        self.price = price

    def get_price(self):
        return self.price

    def get_amount(self):
        return self.amount

    def decrease(self):
        self.amount -= 1

    def __str__(self):
        return f""{self.amount} @ {self.price}""
</code></pre>
",https://stackoverflow.com/questions/55867900/unit-testing-method-that-raises-and-exception,"['python', 'unit-testing']",52,True,1,1
angular 6 unit testing Forkjoin service response,"<p>i have a function in service in which i have 3 http get calls and i return the response with forkJoin making an array, how will i test this service funtcion in spec.ts ?
this is the function in my registration component which is calling the service,</p>

<pre><code>this.register.registrationData()
  .subscribe(data =&gt; {
    this.types = data[0];
    this.modules = data[1];
    this.packages = data[2];
  });
</code></pre>

<p>and this is my registration service function, </p>

<pre><code>registrationData(): Observable&lt;any&gt; {
    const companyTypes =this.http.get(ConstantService.apiRoutes.companyTypes);
    const modules = this.http.get(ConstantService.apiRoutes.modules);
    const packages = this.http.get(ConstantService.apiRoutes.packages);
    return forkJoin([companyTypes, modules, packages]);
}
</code></pre>

<p>this is my spec file so far,</p>

<pre><code> it('Should require registration data', () =&gt; {
  loginRegService.registrationData().subscribe((data) =&gt; {
    expect(data).toEqual(regData);
  })
  const reqCompany = httpTestingController.expectOne(`${environment.apiUrl}/anonymous/companyTypes/`);
  const reqModule = httpTestingController.expectOne(`${environment.apiUrl}/anonymous/modules/`);
  const reqPackage = httpTestingController.expectOne(`${environment.apiUrl}/anonymous/packages/`);
  expect(reqCompany.request.method).toBe('GET');
  expect(reqModule.request.method).toBe('GET');
  expect(reqPackage.request.method).toBe('GET');
  const e1 = forkJoin([reqCompany, reqModule, reqPackage]);
  reqCompany.flush(companyType);
  reqModule.flush(modules);
  reqPackage.flush(packages);
});
</code></pre>
",https://stackoverflow.com/questions/54005374/angular-6-unit-testing-forkjoin-service-response,"['angular', 'unit-testing', 'angular6', 'karma-jasmine']",7386,False,1,1
Vue.js unit testing updating vuex store error,"<p>I am changing vuex state value using commit in my tests and then trying to see whether element that supposed to be rendered based on the change is present.
Something like this</p>

<pre><code>it('should render error state if no stores', () =&gt; {
    wrapper.store.commit('stores/updateLoadingStores', false);
    wrapper.store.commit('stores/updateStores', []);
    expect(wrapper.find('error-state-stub').exists()).toBe(true);
});
</code></pre>

<p>Instead I am getting next error
    ```
    StoresStep › should render error state if no stores</p>

<pre><code>TypeError: Cannot read property '_isDestroyed' of undefined

  31 |     const mutationName = `${prefix}${_upperFirst(name)}`;
  32 |     acc[mutationName] = (state, value) =&gt; {
&gt; 33 |       state[name] = value;
     |       ^
  34 |     };
  35 |     return acc;
  36 |   }, {});

  at destroy (node_modules/vue/dist/vue.runtime.common.dev.js:3151:28)
  at invokeDestroyHook (node_modules/vue/dist/vue.runtime.common.dev.js:6088:59)
 ...
```
</code></pre>

<p>The function it complains about is a wrapper to set value to specific module.
See actual error - <code>TypeError: Cannot read property '_isDestroyed' of undefined</code>
which is coming from <code>vue.runtime.common.dev.js</code></p>

<p>I thought it is Vue.$nextTick() related but seems like no.</p>

<p><code>wrapper.store</code> part is just util I wrote to be able to mount component and use everything related to it in one place.</p>

<p>Will appreciate any help.</p>
",https://stackoverflow.com/questions/57189442/vue-js-unit-testing-updating-vuex-store-error,"['vue.js', 'vuex', 'vue-test-utils']",948,True,1,1
Unit testing using unit test in Python3,"<p>I need to write test cases using unit test in Python for testing circle creation.</p>
<ul>
<li><p>Define a class <code>Circle</code> with method <code>__init__</code> which initializes a circle with attribute <code>radius</code>, having following restrictions:</p>
<ul>
<li><p><code>radius</code> must be numeric value, if not raise type error with error message &quot;radius must be number&quot;.</p>
</li>
<li><p><code>radius</code> must be between 0 to 1000 inclusive on both sides, if not raise the value error with error message &quot;radius must be between 0 and 1000 inclusive&quot;</p>
</li>
<li><p>Define a class method <code>area</code> and <code>circumference</code> which must return values rounded off to 2 decimals.</p>
</li>
</ul>
<p>Complete the definition of class <code>TestingCircleCreation</code> which tests the behavior of <code>__init__</code> method as specification below.</p>
</li>
<li><p>Define the test method of <code>test_creating_circle_with_numerical_radius</code> which creates circle with radius 2.5 and check if radius matches to value 2.5</p>
</li>
<li><p>Define the test method <code>test_creating_circle_with_negative_radius</code> which checks if value error exception is raised with the error message &quot;radius must be between 0 and 1000 inclusive&quot;, while creating circle of radius 2.5.</p>
</li>
<li><p>Define the test method <code>test_creating_circle_with_greaterthan_radius</code> which checks if <code>ValueError</code> exception is raised with error message &quot;radius must be between 0 and 1000 inclusive&quot;, while creating circle of radius 1000.1.</p>
</li>
<li><p>Define the test method <code>test_creating_circle_with_nonnumeric_radius</code>, which checks if <code>TypeError</code> exception is raised with error message &quot;radius must be number&quot; while creating circle of radius 'hello'.</p>
</li>
</ul>
<p>I tried below but it is failing with error as</p>
<pre><code>Traceback (most recent call last):
  File &quot;..\Playground\&quot;, line 86, in &lt;module&gt;
    pass_count = pass_count[0]
IndexError: list index out of range
</code></pre>
<p>The code:</p>
<pre><code>import inspect
import re
import unittest
import math

# Define below the class 'Circle' and it's methods with proper doctests.
class Circle:
    def __init__(self, radius):
        # Define the initialization method below
        try:
            if not isinstance(radius, (int, float)):
                raise TypeError 
            elif 1000 &gt;=radius&gt;=0:
                    self.radius=radius 
            else:
                raise ValueError        
        except ValueError:
            raise ValueError(&quot;radius must be between 0 and 1000 inclusive&quot;)
        except TypeError:
            raise TypeError(&quot;radius must be a number&quot;)
        
    def area(self):
        # Define the area functionality below
        y=math.pi*(self.radius**2)
        return round(y,2)
               
    def circumference(self):
        # Define the circumference functionality below
        x=math.pi*2*self.radius
        return round(x,2)
        
class TestCircleCreation(unittest.TestCase):
    def test_creating_circle_with_numeric_radius(self):
        # Define a circle 'c1' with radius 2.5 and check if 
        # the value of c1.radius equal to 2.5 or not
        c1=Circle(2.5)        
        self.assertEqual(c1.radius,2.5)

    def test_creating_circle_with_negative_radius(self):
        # Try Defining a circle 'c' with radius -2.5 and see 
        # if it raises a ValueError with the message
        # &quot;radius must be between 0 and 1000 inclusive&quot;
        c=Circle(-2.5)
        self.assertEqual(c.radius,-2.5)
        self.assertRaises(ValueError)      

    def test_creating_circle_with_greaterthan_radius(self):
        # Try Defining a circle 'c' with radius 1000.1 and see 
        # if it raises a ValueError with the message
        # &quot;radius must be between 0 and 1000 inclusive&quot;
        c=Circle(1000.1)        
        self.assertEqual(c.radius,1000.1)
        self.assertRaises(ValueError)        
        
    def test_creating_circle_with_nonnumeric_radius(self):
        # Try Defining a circle 'c' with radius 'hello' and see 
        # if it raises a TypeError with the message
        # &quot;radius must be a number&quot;
        c=Circle('hello')      
        self.assertEqual(c.radius,'hello')
        self.assertRaises(TypeError)        

if __name__ == '__main__':
    fptr = open('output.txt', 'w')
    
    runner = unittest.TextTestRunner(fptr)
    
    unittest.main(testRunner=runner, exit=False)
    
    fptr.close()
    
    with open('output.txt') as fp:
        output_lines = fp.readlines()
    
    pass_count = [ len(re.findall(r'\.', line)) for line in output_lines if line.startswith('.')
                     and line.endswith('.\n')]
    
    pass_count = pass_count[0]
    print(str(pass_count))
                       
    doc1 = inspect.getsource(TestCircleCreation.test_creating_circle_with_numeric_radius)
    doc2 = inspect.getsource(TestCircleCreation.test_creating_circle_with_negative_radius)
    doc3 = inspect.getsource(TestCircleCreation.test_creating_circle_with_greaterthan_radius)
    doc4 = inspect.getsource(TestCircleCreation.test_creating_circle_with_nonnumeric_radius)
    
    assert1_count = len(re.findall(r'assertEqual', doc1))
    print(str(assert1_count))
    
    assert1_count = len(re.findall(r'assertEqual', doc2))
    assert2_count = len(re.findall(r'assertRaises', doc2))
    print(str(assert1_count), str(assert2_count))
    
    assert1_count = len(re.findall(r'assertEqual', doc3))
    assert2_count = len(re.findall(r'assertRaises', doc3))
    print(str(assert1_count), str(assert2_count))
    
    assert1_count = len(re.findall(r'assertEqual', doc4))
    assert2_count = len(re.findall(r'assertRaises', doc4))
    print(str(assert1_count), str(assert2_count))
</code></pre>
",https://stackoverflow.com/questions/54616018/unit-testing-using-unit-test-in-python3,"['python', 'python-3.x', 'unit-testing']",22482,True,1,4
Unit testing &#39;pathlib.Path.is_file&#39; in Python 3.x,"<p>I am new to unit testing in Python and have problems to get my tests running. I want to implement the following test class as shown in here: <a href=""https://www.toptal.com/python/an-introduction-to-mocking-in-python"" rel=""nofollow noreferrer"">https://www.toptal.com/python/an-introduction-to-mocking-in-python</a>, but slightly 
modified. 
Instead of using <code>os.path.isfile</code> I want to use <code>pathlib.Path.is_file</code>.</p>

<p>This is the actual class to test:</p>

<pre><code>import os

from pathlib import Path

class FileUtils:

    @staticmethod
    def isFile(file):
        return Path(file).is_file()

    @staticmethod
    def deleteFile(file):
        if FileUtils.isFile(file):
            os.remove(file)
</code></pre>

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

<pre><code>import mock, unittest

class FileUtilsTest(unittest.TestCase):

    testFilename = ""filename""

    @mock.patch('FileUtils.Path')
    @mock.patch('FileUtils.os')
    def testDeleteFiles(self, osMock, pathMock):

        pathMock.is_file.return_value = False
        FileUtils.deleteFile(self.testFilename)
        self.assertFalse(osMock.remove.called, 'Failed to not remove the file if not present.')

        pathMock.is_file.return_value = True
        FileUtils.deleteFile(self.testFilename)
        osMock.remove.assert_called_with(self.testFilename)
</code></pre>

<p>This will lead to the following error message:</p>

<pre><code>Finding files... done.
Importing test modules ... done.

======================================================================
FAIL: testDeleteFile (FileUtilsTest.FileUtilsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""...\AppData\Local\Continuum\anaconda3\lib\site-packages\mock\mock.py"", line 1305, in patched
    return func(*args, **keywargs)
  File ""...\FileUtilsTest.py"", line 13, in testDeleteFile
    self.assertFalse(osMock.remove.called, 'Failed to not remove the file if not present.')
AssertionError: True is not false : Failed to not remove the file if not present.

----------------------------------------------------------------------
Ran 1 test in 0.003s

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

<p>How can I test the method <code>FileUtils.deleteFile</code> by using <code>@mock.patch</code> decorators?</p>
",https://stackoverflow.com/questions/56023351/unit-testing-pathlib-path-is-file-in-python-3-x,"['python', 'python-3.x', 'unit-testing', 'mocking']",2440,True,1,1
SQLAlchemy DetachedInstanceError when Unit testing with Flask app.test_client,"<p>My goal is to be able to test routes with the Flask app test_client using <code>self.client.post(url, ...</code>. The problem that I'm running into is any time I make a request using it, I hit a DetachedInstanceError from SQLAlchemy, saying that either refresh or lazy loading operations cannot occur.</p>

<p>Here's my setup:</p>

<pre><code>class BaseTestCase(unittest.TestCase):

   def setUp(self):
      self.postgresql = Postgresql()
      config = {
         'FLASK_ENV': 'test',
         'SQLALCHEMY_DATABASE_URI': self.postgresql.url()
      }
      with patch.dict('os.environ', config):
         self.app = create_app()
         self.client = self.app.test_client()
         ctx = self.app.app_context()
         ctx.push()
         db.create_all()
         self.assertEqual(app.testing, True)
      reset_fake_data()

   def tearDown(self):
      db.session.remove()
      self.postgresql.stop()

   def post(self, url, data={}, headers={}):
      headers = {'Content-Type': 'application/json', **headers}
      return self.client.post(url, headers=headers, data=json.dumps(data))

   def post_with_auth_token(self, url, data={}, headers={}):
      headers = {'Authorization': f'Bearer {self.auth_token}'}
      return self.post(url, headers=headers, data=data)
</code></pre>

<p>Then in another file, I'm calling this with <code>response = self.post('/api/users/register', data=data)</code> and getting the error:</p>

<pre><code>sqlalchemy.orm.exc.DetachedInstanceError: Parent instance &lt;User at 0x10ea43f98&gt; is not bound to a Session; lazy load operation of attribute 'courses' cannot proceed (Background on this error at: http://sqlalche.me/e/bhk3)
</code></pre>

<p>Below is the route. I create a user object and then attempt to add a course to it but apparently, when I try to do <code>user.courses.append</code>, it's unable to lazy load the courses. I've looked into disabling the <code>expire_on_commit</code> attribute, but I'm not sure how to do that only in the cases of testing, or if there's a better way to go about this.</p>

<p>I read that converting from lazy to eager loading could also fix it, but I'd rather keep things loading lazily and it didn't seem to fix it when I set the relationship to be <code>lazy='subquery'</code> anyways. </p>

<pre class=""lang-py prettyprint-override""><code>@users.route('/register', methods=['POST'])
def register():
   data = request.get_json()
   try:
      user = User.from_data(**data)
   except UnprocessableEntity:
      return jsonify(msg='Missing parameters'), 422
   except Conflict:
      return jsonify(msg='Email already exists'), 409
   except Unauthorized:
      return jsonify(msg='Unauthorized'), 401
   if data.get('invitation_token'):
      invite = CourseInvite.query.filter_by(token=data['invitation_token']).first_or_404('Invite not found')
      if invite.email and invite.email != user.email:
         return jsonify(msg='Email mismatch'), 401
      elif invite.used:
         return jsonify(msg='Invite already used'), 401
      user.courses.append(CourseEnrollment(course_id=invite.course.id))
      invite.used = True
   db.session.add(user)
   db.session.commit()
   return jsonify(msg='User successfully created'), 201
</code></pre>
",https://stackoverflow.com/questions/56623301/sqlalchemy-detachedinstanceerror-when-unit-testing-with-flask-app-test-client,"['python', 'flask', 'sqlalchemy', 'python-unittest']",931,False,7,1
Unit testing outside of a package in R,"<p>Often times we're using R in contexts where we want to have reproducibility in the face of modifications and where we have complex code bases but outside of writing a package. It seems like testthat and the other testing packages are geared towards unit testing for package code, which makes sense since that's the most common case where you need a lot of testing where you're not in full control of all the data, but I was wondering if there was a good package or method for unit testing in R outside of the context of writing a package. </p>

<p>For example, a lot of times in a package context you're testing something of the form: </p>

<pre class=""lang-r prettyprint-override""><code>foo &lt;- function(bar){
    # do something to bar
    return(bar.outcome)
}
</code></pre>

<p>and so then you're testing for expected output from the function, that things are the right type, that there is proper error handling. The way you do this is that you create a directory in your package for tests and write them there and then devtools can use <code>load_all</code> and <code>testthat</code> to run them and produce results. </p>

<p>One thing I would like to be able to do is run these same sort of tests outside of the context of a package, such as in a script. This is important because a lot of R code that is written in academia doesn't generalize a whole lot to different contexts or data without considerable difficulty, so that having a package doesn't make much sense, but at the same time unit testing would make it easier to extend the code in future packages. That's the easy case.</p>

<p>The harder case is actually something you rarely do in packages, which is test things about the shape, kind, and state of the data. So, for example, I often read R code written in academia with comments like </p>

<pre class=""lang-r prettyprint-override""><code>data &lt;- data %&gt;% doSomething() #1023 rows 

parameter_df &lt;- // read file 
print(parameter_df) # 5 columns 
data &lt;- data %&gt;% doSomething(param = parameter_df)

lapply(df, class) #should be char, char, char, numeric, Date

</code></pre>

<p>I like the idea that ""every time you want to write a print statement, write a test instead"", but I actually don't have a good framework for how this should be done in R. Especially in this harder case where you're not testing a function, you're testing to make sure that the data flowing through your program is correct. </p>

<p>The context here is that R is used in a lot of contexts where the point of a script is replication in the scientific sense, but where there is possibly great gain from people being able to easily extend other's scripts which are released as part of replication materials for new projects, which is much harder to do, especially in complex code, whenever there are no tests and code can be very fragile and fail in nontrivial and <em>silent</em> ways. </p>
",https://stackoverflow.com/questions/58002252/unit-testing-outside-of-a-package-in-r,"['r', 'unit-testing']",775,True,8,1
Unit testing Angular app for dynamic contents,"<p>I am running unit test on angular app for UI part, when try to get the DOM elements using fixture.debugElement.query(By.css('.someClass')), altough someClass is defined inside template.html debug Element returns null.</p>

<p>I also see that angular generates someClass dynamically, but I want to run on this to spyon some method call. How to test them?
Note: I am using JAsmine and Karma</p>
",https://stackoverflow.com/questions/55628336/unit-testing-angular-app-for-dynamic-contents,"['angular', 'unit-testing', 'angular-test']",258,False,1,0
FileManager.containerURL(forSecurityApplicationGroupIdentifier) returning nil in unit testing,"<p>During unit testing the following function returns nil meaning my group id is invalid. <code>fileManager.containerURL(forSecurityApplicationGroupIdentifier:""group.myGroupId"")</code>However if I run the same code on a sim or a device it works perfectly.</p>

<p>What am I missing in order to use app groups during unit testing?</p>
",https://stackoverflow.com/questions/57656644/filemanager-containerurlforsecurityapplicationgroupidentifier-returning-nil-in,"['swift', 'ios-app-group']",263,False,1,0
Flutter unit testing. error while running test,"<p>I am getting following error while running flutter unit test.</p>

<blockquote>
  <p>00:05 +1: ...
  /home/kazekage/Projects/flutter/flutter_woocommerce/test/model/util/Refund_test.dart
  Shell: [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: error:
  import of dart:mirrors with
  --enable-mirrors=false Shell: [ERROR:flutter/shell/common/engine.cc(175)] Could not prepare to run
  the isolate. Shell: [ERROR:flutter/shell/common/engine.cc(122)] Engine
  not prepare and launch isolate. Shell:
  [ERROR:flutter/shell/testing/tester_main.cc(199)] Could not launch the
  engine with configuration. 00:05 +1 -1: loading
  /home/kazekage/Projects/flutter/flutter_woocommerce/test/model/util/Refund_test.dart
  [E]   Failed to load
  ""/home/kazekage/Projects/flutter/flutter_woocommerce/test/model/util/Refund_test.dart"":
  Shell subprocess cleanly reported an error before connecting to test
  harness. Check the logs above for an error message.   Test:
  /home/kazekage/Projects/flutter/flutter_woocommerce/test/model/util/Refund_test.dart
  Shell:
  /home/kazekage/Developement/flutter_linux_v1.2.1-stable/flutter/bin/cache/artifacts/engine/linux-x64/flutter_tester
        Shell: [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: error: import of dart:mirrors with
  --enable-mirrors=false Shell: [ERROR:flutter/shell/common/engine.cc(175)] Could not prepare to run
  the isolate. Shell: [ERROR:flutter/shell/common/engine.cc(122)] Engine
  not prepare and launch isolate. Shell:
  [ERROR:flutter/shell/testing/tester_main.cc(199)] Could not launch the
  engine with configuration. 00:05 +1 -2: loading
  /home/kazekage/Projects/flutter/flutter_woocommerce/test/model/util/LineItem_test.dart
  [E]   Failed to load
  ""/home/kazekage/Projects/flutter/flutter_woocommerce/test/model/util/LineItem_test.dart"":
  Shell subprocess cleanly reported an error before connecting to test
  harness. Check the logs above for an error message.   Test:
  /home/kazekage/Projects/flutter/flutter_woocommerce/test/model/util/LineItem_test.dart
  Shell:
  /home/kazekage/Developement/flutter_linux_v1.2.1-stable/flutter/bin/cache/artifacts/engine/linux-x64/flutter_tester
        Shell: [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: error: import of dart:mirrors with
  --enable-mirrors=false Shell: [ERROR:flutter/shell/common/engine.cc(175)] Could not prepare to run
  the isolate. Shell: [ERROR:flutter/shell/common/engine.cc(122)] Engine
  not prepare and launch isolate. Shell:
  [ERROR:flutter/shell/testing/tester_main.cc(199)] Could not launch the
  engine with configuration. 00:06 +1 -3: loading
  /home/kazekage/Projects/flutter/flutter_woocommerce/test/model/util/ShippingLine_test.dart
  [E]   Failed to load
  ""/home/kazekage/Projects/flutter/flutter_woocommerce/test/model/util/ShippingLine_test.dart"":
  Shell subprocess cleanly reported an error before connecting to test
  harness. Check the logs above for an error message.   Test:
  /home/kazekage/Projects/flutter/flutter_woocommerce/test/model/util/ShippingLine_test.dart
  Shell:
  /home/kazekage/Developement/flutter_linux_v1.2.1-stable/flutter/bin/cache/artifacts/engine/linux-x64/flutter_tester</p>
</blockquote>

<p><strong>pubsec.yml</strong></p>

<pre><code>name: flutter_woocommerce
description: A new Flutter package project.
version: 0.0.1
author:
homepage:

environment:
  sdk: ""&gt;=2.1.0 &lt;3.0.0""

dependencies:
  flutter:
    sdk: flutter
  dio: ^2.1.6
  built_value: ^6.6.0
  built_value_generator: ^6.6.0
  built_collection: ^4.2.2

dev_dependencies:
  flutter_test:
    sdk: flutter
  mockito: ^4.0.0
  build_runner: ^1.5.0
  source_gen: ^0.9.4+2

# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # To add assets to your package, add an assets section, like this:
  # assets:
  #  - images/a_dot_burr.jpeg
  #  - images/a_dot_ham.jpeg
  #
  # For details regarding assets in packages, see
  # https://flutter.io/assets-and-images/#from-packages
  #
  # An image asset can refer to one or more resolution-specific ""variants"", see
  # https://flutter.io/assets-and-images/#resolution-aware.

  # To add custom fonts to your package, add a fonts section here,
  # in this ""flutter"" section. Each entry in this list should have a
  # ""family"" key with the font family name, and a ""fonts"" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts in packages, see
  # https://flutter.io/custom-fonts/#from-packages
</code></pre>

<p><strong>flutter doctor</strong></p>

<pre><code>[✓] Flutter (Channel stable, v1.5.4-hotfix.2, on Linux, locale en_US.UTF-8)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] Android Studio (version 3.4)
[!] IntelliJ IDEA Ultimate Edition (version 2018.3)
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
[✓] VS Code (version 1.35.0)
[!] Connected device
    ! No devices available

! Doctor found issues in 2 categories.
</code></pre>

<p><strong>Tag.dart</strong></p>

<pre><code>import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:flutter_woocommerce/model/util/Link.dart';

part 'Tag.g.dart';

abstract class Tag implements Built&lt;Tag, TagBuilder&gt; {
  static Serializer&lt;Tag&gt; get serializer =&gt; _$tagSerializer;

  int get id;

  String get name;

  String get slug;

  @nullable
  String get description;

  @nullable
  int get count;

  @nullable
  @BuiltValueField(wireName: '_links')
  Link get links;

  Tag._();

  factory Tag([updates(TagBuilder b)]) = _$Tag;
}
</code></pre>

<p><strong>Tag_test.dart</strong></p>

<pre><code>import 'package:flutter_test/flutter_test.dart';
import 'dart:convert';
import 'package:built_collection/built_collection.dart';
import 'package:flutter_woocommerce/test_strings.dart';
import 'package:flutter_woocommerce/model/Serializers.dart';
import 'package:flutter_woocommerce/model/Tag.dart';
import 'package:flutter_woocommerce/model/util/Link.dart';

void main() {

  final parsedJson = json.decode(TestStrings.TAG_JSON);
  Tag tag = serializers.deserializeWith(Tag.serializer, parsedJson);

  test('id', () {
    expect(tag.id, 32);
  });

  test('name', () {
    expect(tag.name, 'Telephone');
  });

  test('slug', () {
    expect(tag.slug, 'telephone');
  });

  test('description', () {
    expect(tag.description, '');
  });

  test('count', (){
    expect(tag.count, 0);
  });

  test('_links is Link Object', () {
    expect(tag.links, isInstanceOf&lt;Link&gt;());
  });

  test('_links &gt; self is href[]', () {
    expect(tag.links.self, isInstanceOf&lt;BuiltList&lt;Href&gt;&gt;());
  });

  test('_links &gt; collection is href[]', () {
    expect(tag.links.collection, isInstanceOf&lt;BuiltList&lt;Href&gt;&gt;());
  });

  test('_links &gt; collection &gt; href value', () {
    expect(tag.links.collection.first.href, 'http://paathsala-wp.test/wp-json/wc/v2/products/tags');
  });
}
</code></pre>
",https://stackoverflow.com/questions/56653158/flutter-unit-testing-error-while-running-test,"['unit-testing', 'flutter']",2393,True,1,2
Unit testing for circle using nose python,"<p>Define a nose test class 'TestCircleArea', which tests the behavior of the 'area' method, with the following tests:</p>

<ol>
<li>Define a nose test method 'test_circlearea_with_random_numeric_radius', which creates a circle 'c1' with radius 2.5, and check if its computed area is 19.63.</li>
<li>Define a nose test method 'test_circlearea_with_min_radius', which creates a circle 'c2' with radius 0, and check if its computed area is 0.</li>
<li>Define a nose test method 'test_circlearea_with_max_radius', which creates a circle 'c3' with radius 1000, and check if its computed area is 3141592.65.</li>
</ol>

<p>I have written the below nose test methods. But it isn't working. Please suggest.</p>

<p>class Circle:</p>

<pre><code>def __init__(self,radius):

    if not isinstance(radius,(int,float)):
        raise TypeError(""radius must be a number"")

    if not 1000&gt;=radius&gt;=0:
        raise ValueError(""radius must be between 0 and 1000 inclusive"")

    self.radius = radius


def area(self):
    return round(math.pi*self.radius**2,2)

def circumference(self):
    return round(2*math.pi*self.radius,2)
</code></pre>

<p>class TestCircleArea:</p>

<pre><code>def test_circlearea_with_random_numeric_radius(self):
    c1 = Circle(2.5)
    assert_equals(c1.area(),19.63)

def test_circlearea_with_min_radius(self):
    c2 = Circle(0)
    assert_equals(c2.area(),0)

def test_circlearea_with_max_radius(self):
    c3 = Circle(1000)
    assert_equals(c3.area(),3141592.65)
</code></pre>
",https://stackoverflow.com/questions/58112179/unit-testing-for-circle-using-nose-python,"['python-unittest', 'nose']",3069,False,0,1
Unit testing spring boot controller with Mockito,"<p>I have the following controller:</p>

<pre><code>@RestController
@RequestMapping(""cats"")
public class CatController {
    private IDatabaseCatDao databaseCatService;
    private DataValidator catDataValidator;

    public CatController(IDatabaseCatDao databaseCatService, DataValidator catDataValidator) {
        this.databaseCatService = databaseCatService;
        this.catDataValidator = catDataValidator;
    }

    @PostMapping
    public ResponseEntity addCat(@RequestBody Cat cat) {
        catDataValidator.validateCatAdding(cat, cats);
        databaseCatService.addCat(cat);
        URI location = ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(cat.getName()).toUri();
        return ResponseEntity.created(location).build();
    }
}    
</code></pre>

<p><em>catDataValidator</em> - check if data is correct<br>
<em>databaseCatService</em> - insert in database + caching locally </p>

<p>I need to test It using <strong><em>jUnit</em></strong> and <strong><em>Mockito</em></strong>. </p>

<p>My test class is following:</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(value = CatController.class, secure = false)
public class CatControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private IDatabaseCatDao databaseCatService;

    private String catExampleJson = ""..some json file.."";

   public void addCat() throws Exception {
        Mockito.doNothing().when(databaseCatService).addCat(Mockito.any(Cat.class));
        RequestBuilder requestBuilder = MockMvcRequestBuilders
                .post(""/cats"")
                .accept(MediaType.APPLICATION_JSON).content(catExampleJson)
                .contentType(MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc.perform(requestBuilder).andReturn();
        MockHttpServletResponse response = result.getResponse();
        assertEquals(HttpStatus.CREATED.value(), response.getStatus());
    }
}
</code></pre>

<p><em>Mockito.doNothing()</em> because service addCat() is void method.<br>
<em>Validation</em> I should better test separetely<br>
<em>Cats map</em> I don't use here  </p>

<p>java.lang.Exception: No runnable methods</p>

<pre><code>at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.&lt;init&gt;(SpringJUnit4ClassRunner.java:137)
    at org.springframework.test.context.junit4.SpringRunner.&lt;init&gt;(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.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code></pre>

<p>I have the following <strong><em>dependencies for the testing</em></strong>: </p>

<p>spring-boot-starter-test   </p>
",https://stackoverflow.com/questions/54677036/unit-testing-spring-boot-controller-with-mockito,"['java', 'testing', 'junit', 'mocking', 'mockito']",2352,True,0,1
Unit testing a filter component using Jasmine,"<p>I have created a component for filtering out a string passed to it. I am trying to write unit test for it and it throwing me an error related to constructor. Please help me.</p>

<pre><code>import angular from 'angular';
import filter from ""./format-string.filter""

angular
.module( ""filters.truncateString"", [] )
.filter( ""truncateString"", () =&gt; filter );

class TruncateString {
 filter(val){
    const accValue = val.split('YYYY');
    const firstValue= accValue[1].replace(/^(|-?\d+)$/, '');
    return `${accValue[0]} ${firstValue} AAA`;
 }
}

export default TruncateString .filter;`
</code></pre>

<p>Test I have written is</p>

<pre><code>import angular from 'angular';
import 'angular-mocks';
import TruncateString from './format-string.filter';
describe('TruncateString filter', () =&gt; {
let controller, filter;

beforeEach(angular.mock.module('filters.TruncateString'));
controller = new TruncateString();

beforeEach(inject(function(_$filter_){
    filter = _$filter_;
}));

it('Checking whether the function is returning formatted string', () =&gt; {
    const result = controller.filter('123YYY3213123');
    expect(result).toHaveBeenCalledWith('123 YYY ... 23');
});
});
</code></pre>
",https://stackoverflow.com/questions/55474231/unit-testing-a-filter-component-using-jasmine,"['javascript', 'angularjs', 'karma-jasmine']",3300,True,0,1
Appium support android unit testing or not?,"<p>Appium support android unit testing or not. If <strong>yes</strong> then how to perform these tests and if <strong>no</strong> then which tool or framework is support Appium for unit testing. Or I have to use another framework or tool for unit testing.</p>
",https://stackoverflow.com/questions/59084519/appium-support-android-unit-testing-or-not,"['android', 'unit-testing', 'appium-android']",437,False,0,2
How to inject Input() in unit testing?,"<p>So i try to do some unit testing on a component. But I have some problems with Input() parameter. And then especially a component in the component</p>

<p>SO I have this component:</p>

<pre><code>
export class EcheqDisplayComponent implements OnInit {
  echeq: EcheqSubmissionApi;


  constructor(
    private route: ActivatedRoute
  ) {
    this.echeq = this.route.snapshot.data['submission'];
  }

  ngOnInit() {
  }

  getAnswers(page: EcheqPageApi): any[] {
    return page.elements.map(element =&gt; this.echeq.answers[element.name]);
  }
}

</code></pre>

<p>and the template:</p>

<pre><code>
&lt;div class=""echeq-display"" *ngIf=""echeq""&gt;
  &lt;header class=""echeq-display-header header""&gt;
    &lt;div class=""echeq-display-info""&gt;
      &lt;h1 class=""heading echeq-display-heading""&gt;
        {{ echeq.definition.title }}
      &lt;/h1&gt;
      &lt;div class=""sub-heading echeq-display-subheading""&gt;
        &lt;span class=""echeq-display-creator""&gt;
          Toegekend door:
          {{ echeq.assignedByProfName ? echeq.assignedByProfName : 'Het Systeem' }}
        &lt;/span&gt;
        &lt;span class=""echeq-display-date""&gt;{{
          echeq.definition.createdOnUtc | date: 'dd MMM'
        }}&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;app-meta-box
      [metadata]=""{
        numPages: echeq.definition.numPages,
        vPoints: echeq.definition.awardedVPoints
      }""
    &gt;&lt;/app-meta-box&gt;
  &lt;/header&gt;
  &lt;main class=""echeq-display-questions body""&gt;
    &lt;app-echeq-question
      *ngFor=""let page of echeq.definition.pages; let i = index""
      [page]=""page""
      [readonly]=""true""
      [number]=""i + 1""
      [answers]=""getAnswers(page)""
    &gt;&lt;/app-echeq-question&gt;
  &lt;/main&gt;
&lt;/div&gt;


</code></pre>

<p>and the unit test:</p>

<pre><code>
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { EcheqDisplayComponent } from './echeq-display.component';
import { ParticipantEcheqModule } from '../../participant-echeq.module';
import { RouterModule, ActivatedRoute } from '@angular/router';
import { MockActivatedRoute } from 'src/app/shared/mocks/MockActivatedRoute';
import { MetaData } from '../meta-box/meta-box.component';

describe('EcheqDisplayComponent', () =&gt; {
  let component: EcheqDisplayComponent;
  let fixture: ComponentFixture&lt;EcheqDisplayComponent&gt;;
  const metaData: MetaData = new MetaData();
  // const metaDataInfo = fixture.debugElement.componentInstance;


  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ ],
      providers: [
        { provide: ActivatedRoute, useClass: MockActivatedRoute }
      ],
      imports:[
        ParticipantEcheqModule

      ]
    })
    .compileComponents();
  }));

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

  fit('should create component', () =&gt; {
    metaData.numPages = 20;
    expect(component).toBeTruthy();
  });
});



</code></pre>

<p>But it stay saying: </p>

<p>TypeError: Cannot read property 'numPages' of undefined.</p>

<p>So what I have to change that it is working?</p>

<p>Thank you</p>

<p>So the MetaData is from the app-meta-box component.it looks like this:</p>

<pre><code>
export class MetaData {
  numPages: number;
  vPoints: number;
}

@Component({
  selector: 'app-meta-box',
  templateUrl: './meta-box.component.html',
  styleUrls: ['./meta-box.component.scss']
})
export class MetaBoxComponent implements OnInit {
  @Input() metadata: MetaData;

  constructor() {}

  ngOnInit() {}

}


</code></pre>

<p>This is the mock class:</p>

<pre><code>export class MockActivatedRoute {
  public snapshot = {
      data: {
         submission: {
           answers: {}
         }
      }
  };
}
</code></pre>

<p>I have it now like this:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { EcheqDisplayComponent } from './echeq-display.component';
import { ParticipantEcheqModule } from '../../participant-echeq.module';
import { RouterModule, ActivatedRoute } from '@angular/router';
import { MockActivatedRoute } from 'src/app/shared/mocks/MockActivatedRoute';
import { MetaData } from '../meta-box/meta-box.component';

describe('EcheqDisplayComponent', () =&gt; {
  let component: EcheqDisplayComponent;
  let fixture: ComponentFixture&lt;EcheqDisplayComponent&gt;;
  const metaData: MetaData = new MetaData();
  // const metaDataInfo = fixture.debugElement.componentInstance;


  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ ],
      providers: [
        { provide: ActivatedRoute, useValue: new MockActivatedRoute().withData({submission:{ answers:{} } }) }
      ],
      imports:[
        ParticipantEcheqModule
      ]
    })
    .compileComponents();
  }));

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

  fit('should create component', () =&gt; {
    component.echeq = {
      definition: {
        title: 'test title',
        awardedVPoints: 0,
        numPages: 9
      }
   }
    expect(component).toBeTruthy();
  });
});

But then I get this error:


</code></pre>

<pre><code>Property 'answers' is missing in type '{ definition: { title: string; awardedVPoints: number; numPages: number; }; }' but required in type 'EcheqSubmissionApi'.ts(2741)
echeqSubmissionApi.ts(59, 5): 'answers' is declared here.
</code></pre>

<p>I have it now like this:</p>

<pre><code>fit('should create component', () =&gt; {
    component.echeq = {
      definition: {
        title: 'test title',
        awardedVPoints: 0,
        numPages:9
      }
    } as EcheqSubmissionApi;
    expect(component).toBeTruthy();
  });
</code></pre>

<pre><code>export interface EcheqSubmissionApi { 
    /**
     * Primary key of this submission (server set).
     */
    id?: string;
    definition?: EcheqDefinitionApi;
    /**
     * Id of the prof who assigned this eCheq (server set).
     */
    assignedByProfId?: string;
    /**
     * Name of the prof who assigned this eCheq (server set). Only set on get operations. May be null if assigned by the system.
     */
    assignedByProfName?: string;
    /**
     * Id of the organisation who assigned this eCheq (server set).
     */
    assignedByOrgId?: number;
    /**
     * Participant ID of the patient this eCheq is assigned to (server set).
     */
    assignedToId?: string;
    /**
     * When this submission was assigned (UTC, server set).
     */
    assignedOnUtc?: Date;
    /**
     * If set until when the eCheq can be submitted.
     */
    validUntilUtc?: Date;
    /**
     * Whether the eCheq has been started and whether it has been submitted (server set).
     */
    status?: EcheqSubmissionApi.StatusEnum;
    /**
     * When this submission was completed (UTC, server set).
     */
    submittedOnUtc?: Date;
    /**
     * Answers of form.  In the form of a json object with name and value of the questions  {      \""nameOfQuestion\"" : \""valueOfQuestion\""  }
     */
    answers: object;
    /**
     * initialValues of form.  In the form of a json object with name and value of variables  {      \""nameOfQuestion\"" : \""valueOfQuestion\""  }
     */
    initialValues?: object;
    /**
     * The page the participant is currently on
     */
    currentPage?: number;
    /**
     * The progress of the echeq in percentage
     */
    progress?: number;
}
export namespace EcheqSubmissionApi {
    export type StatusEnum = 'New' | 'Active' | 'Submitted';
    export const StatusEnum = {
        New: 'New' as StatusEnum,
        Active: 'Active' as StatusEnum,
        Submitted: 'Submitted' as StatusEnum
    };
}

</code></pre>

<p>But if I run the unit test, I still get this error:</p>

<pre><code>TypeError: Cannot read property 'numPages' of undefined
</code></pre>
",https://stackoverflow.com/questions/58792678/how-to-inject-input-in-unit-testing,"['javascript', 'angular', 'karma-jasmine']",241,False,0,3
kotlin - Room database error when unit testing,"<p>I am trying to write a unit test for my database, but I am getting the following error.
The error says that should not be a <code>null</code> value. 
Through the <code>Log.i</code>, I can know if variable <code>count</code> is a <code>null</code> value.
But I don't know why the variable <code>count</code> was worth <code>null</code>.</p>

<pre><code>I/Junit: createDb
I/Junit: createAndRetriveNotes: count= null  3
I/Junit: closeDb

    ----- begin exception -----
E/TestRunner: java.lang.AssertionError: expected:&lt;3&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.riluq.notesapp.DatabaseTest.createAndRetriveDatabase(DatabaseTest.kt:47)
        at java.lang.reflect.Method.invoke(Native Method)
        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 androidx.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
        at androidx.test.internal.runner.junit4.statement.RunAfters.evaluate(RunAfters.java:61)
        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 androidx.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:104)
        at org.junit.runners.Suite.runChild(Suite.java:128)
        at org.junit.runners.Suite.runChild(Suite.java:27)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
        at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
        at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:388)
        at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2090)
    ----- end exception -----

java.lang.AssertionError: expected:&lt;3&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.riluq.notesapp.DatabaseTest.createAndRetriveDatabase(DatabaseTest.kt:47)
at java.lang.reflect.Method.invoke(Native Method)
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 androidx.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
at androidx.test.internal.runner.junit4.statement.RunAfters.evaluate(RunAfters.java:61)
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 androidx.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:104)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:388)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2090)

</code></pre>

<p>I have checked my sql queries in NoteDao. kt, but it looks like the problem is not from there.</p>

<p>DatabaseTest.kt</p>

<pre><code>import android.content.Context
import android.util.Log
import androidx.room.Room
import androidx.test.InstrumentationRegistry
import androidx.test.runner.AndroidJUnit4
import com.riluq.notesapp.database.AppDatabase
import com.riluq.notesapp.database.NoteDao
import com.riluq.notesapp.util.getNotes
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

@RunWith(AndroidJUnit4::class)
class DatabaseTest {

    companion object{
        val TAG: String = ""Junit""
    }

    private var mDb: AppDatabase? = null
    private var mDao: NoteDao? = null

    @Before
    fun createDb() {
        val context: Context = InstrumentationRegistry.getTargetContext()
        mDb = Room.inMemoryDatabaseBuilder(context,
            AppDatabase::class.java).build()
        Log.i(TAG, ""createDb"")
    }

    @After
    fun closeDb() {
        mDb?.close()
        Log.i(TAG, ""closeDb"")
    }

    @Test
    fun createAndRetriveDatabase() {
        mDao?.insertNoteAll(getNotes())
        val count: Int? = mDao?.getCount()
        Log.i(TAG, ""createAndRetriveNotes: count= $count  "" + getNotes().size )
        assertEquals(getNotes().size, count)
    }

}
</code></pre>

<p>AppDatabase.kt</p>

<pre><code>import android.content.Context
import androidx.room.*

@Database(entities = [NoteEntity::class], version = 1, exportSchema = false)
@TypeConverters(DateConverter::class)
abstract class AppDatabase: RoomDatabase() {

    abstract fun noteDao(): NoteDao

    companion object {
        val DATABASE_NAME: String = ""AppDatabase.db""
        private var INSTANCE: AppDatabase? = null
        fun getInstance(context: Context): AppDatabase? {
            if (INSTANCE == null) {
                synchronized(AppDatabase::class) {
                    if (INSTANCE == null) {
                        INSTANCE = Room.databaseBuilder(context.applicationContext,
                            AppDatabase::class.java, DATABASE_NAME)
                            .build()
                    }
                }
            }
            return INSTANCE
        }

        fun destroyInstance() {
            INSTANCE = null
        }



    }


}
</code></pre>

<p>NoteDao.kt</p>

<pre><code>import androidx.lifecycle.LiveData
import androidx.room.*
import androidx.room.OnConflictStrategy.REPLACE

@Dao
interface NoteDao {

    @Insert(onConflict = REPLACE)
    fun insertNote(noteEntity: NoteEntity)

    @Insert(onConflict = REPLACE)
    fun insertNoteAll(notes: List&lt;NoteEntity&gt;)

    @Delete
    fun deleteNote(noteEntity: NoteEntity)

    @Query(""SELECT * FROM notes WHERE id = :id"")
    fun getNoteById(id: Int): NoteEntity

    @Query(""SELECT * FROM notes ORDER BY date DESC"")
    fun getAll(): LiveData&lt;List&lt;NoteEntity&gt;&gt;

    @Query(""DELETE FROM notes"")
    fun deleteAll(): Int

    @Query(""SELECT COUNT(*) FROM notes"")
    fun getCount(): Int


}
</code></pre>

<p>NoteEntity.kt</p>

<pre><code>import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.*

@Entity(tableName = ""notes"")
data class NoteEntity(
    @PrimaryKey(autoGenerate = true)
    var id: Int?,
    var date: Date?,
    var text: String
){
    constructor():this(null, null, """")
}
</code></pre>

<p>Why the variable <code>count</code> in <code>DatabaseTest.kt</code> value is <code>null</code>? and how do I solve it?</p>
",https://stackoverflow.com/questions/55787196/kotlin-room-database-error-when-unit-testing,"['android', 'unit-testing', 'kotlin', 'junit', 'android-room']",958,True,0,1
unit testing material ui components with jest,"<p>There is a grid component in material ui and I want it to be unit tested using jest in my React application. Please find my code below</p>

<p>For the above code, how we will write unit test?  I went through their testing guide <a href=""https://material-ui.com/guides/testing"" rel=""nofollow noreferrer"">https://material-ui.com/guides/testing</a>, but it is not clear.Any ideas/suggestions are really appreciated</p>

<pre><code>import React from ""react"";
import PropTypes from ""prop-types"";
import { withStyles } from ""@material-ui/core/styles"";
import Grid from ""@material-ui/core/Grid"";
import Paper from ""@material-ui/core/Paper"";

import ""./styles.scss"";

const styles = theme =&gt; ({
    root: {
      flexGrow: 1
    },
    paper: {
      height: 140,
      width: 100
    }
});

function Space({ classes }) {
  const x = [1, 2, 3];

  return (
    &lt;div className=""center""&gt;
      &lt;Grid container className={classes.root}&gt;
        &lt;Grid item xs={12}&gt;
          &lt;Grid container justify=""center"" spacing={Number(32)}&gt;
            {x.map(value =&gt; (
              &lt;Grid key={value} item&gt;
                &lt;Paper className={classes.paper} /&gt;
              &lt;/Grid&gt;
            ))}
          &lt;/Grid&gt;
        &lt;/Grid&gt;
      &lt;/Grid&gt;
    &lt;/div&gt;
  );
}
</code></pre>

<p>I should be able to unit test the above code using jest</p>
",https://stackoverflow.com/questions/54688913/unit-testing-material-ui-components-with-jest,"['reactjs', 'material-ui']",1834,False,-2,1
Angular 6 unit testing static mock response,"<p>I am testing an Angular component which calls a service method. Within the component, I modify some fields of the response before proceeding, like this:</p>

<pre><code>ngOnInit() {
    this.myService.myMethod(requestData).subscribe(response =&gt; {
      response.list.forEach(item =&gt; {
        item.someField = someValue;
      })
    });
    ...
}
</code></pre>

<p>For testing, I created a mock response like this:</p>

<pre><code>const mockServiceResponse = {
    list: [],
    ...
}

const myServiceSpy = jasmine.createSpyObj('MyService',['myMethod']);
myServiceSpy .myMethod.and.returnValue( of(mockServiceResponse ) );
</code></pre>

<p>The problem is; I have several test cases, and ngOnInit is called for each test case. As I modify the service response fields, at each run <strong>mockServiceResponse</strong> object is modified, and second test case gets the modified version of the response. This is not a problem for the componenet because I actually get a new response each time I call the method, but for testing it causes my test cases to fail. Any ideas on how can I get a fresh version of <strong>mockServiceResponse</strong> for each test case?</p>
",https://stackoverflow.com/questions/54928158/angular-6-unit-testing-static-mock-response,"['angular', 'unit-testing']",828,True,0,2
unit testing FaceDetector Google mobile vision java.lang.UnsupportedOperationException,"<p>i'm setting up unit test for class method that involve FaceDetector from google mobile vision library but i got java.lang.UnsupportedOperationException, but it's work when running on real android device. is it possible to test FaceDetector code? thx</p>

<pre><code>public class HeadDetector
{

    private Bitmap facePicture;

    private Context context;

    private RectF headRectangle=new RectF();

    public HeadDetector(Bitmap facePicture,Context context) {

        this.facePicture = facePicture;
        this.context = context;
    }


    public RectF generateHeadRectangle() {

        FaceDetector faceDetector = new
            FaceDetector.Builder(context).setTrackingEnabled(false)
            .build();

    Frame frame = new Frame.Builder().setBitmap(facePicture).build();
    // when unit test hit below code
    //java.lang.UnsupportedOperationException
    SparseArray&lt;Face&gt; faces = faceDetector.detect(frame);

    if(faces.size()&gt;0){

        Face face = faces.get(0);

        headRectangle = new RectF(0,0,face.getWidth(),face.getHeight());
    }

    return headRectangle;

  }

}

public class HeadDetectorTest  {

    @Test
    public void shouldGenerateHeadRectangle(){

    Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();

    HeadDetector headDetector = new HeadDetector( TestHelper.createBitmapTest(context), context);

    RectF rectF = headDetector.generateHeadRectangle();

    assertNotEquals(rectF.width(),0.0f);

    assertNotEquals(rectF.height(),0.0f);

    assertThat(rectF.height(),greaterThan(rectF.width()));

}

}
</code></pre>
",https://stackoverflow.com/questions/54475920/unit-testing-facedetector-google-mobile-vision-java-lang-unsupportedoperationexc,"['java', 'android', 'unit-testing', 'junit4', 'robolectric']",63,False,0,1
How to cover branches in unit testing,"<p>I have this function which needs to be unit tested,</p>

<p>I've wrote few specs which is working fine. But in the code-coverage it says <code>Else path not taken</code> for this line <code>if (text !== '') {}</code>.</p>

<p>I'm not sure how to test variable inside the function.</p>

<p>Below are few specs which I wrote.</p>

<pre><code>  it('should split the content correctly', inject([GenerateInlineTagsService], (service: GenerateInlineTagsService) =&gt; {
    const obj = service.getView(RANGES);
    expect(JSON.stringify(obj)).toEqual(JSON.stringify(inlineSplitContent));
  }));
</code></pre>
",https://stackoverflow.com/questions/57253117/how-to-cover-branches-in-unit-testing,"['angular', 'typescript', 'unit-testing', 'karma-jasmine', 'code-coverage']",4765,True,0,1
Mocha unit testing mock variables in javascript,"<p>I am writing test cases for Javascript using mocha. My code exactly looks like this <a href=""https://community.apigee.com/articles/3964/unit-testing-javascript-code-with-mocha-sinon-and.html"" rel=""nofollow noreferrer"">apigee</a></p>

<p>This javascript is deployed in apigee cloud. Where it has access to platform variables. This is myscript my-code.js </p>

<pre><code>    var responseCode = parseInt(context.getVariable(properties.source));

var log = {
    org: context.getVariable(organization.name),
    env: context.getVariable(environment.name),
    responseCode: responseCode,
    isError: (responseCode &gt;= 400)
};

if (log.isError) {
    log.errorMessage = context.getVariable(flow.error.message);
}

var logglyRequest = new Request(
        'https://loggly.com/aaa', 
        'POST', 
        {'Content-Type': 'application/json'}, 
        JSON.stringify(log)
);
httpClient.send(logglyRequest);
</code></pre>

<p>javascript code would have access to properties.source at run time. Apigee platform has its own internal way of how jc access those params. My question is if I am writing test case for this jc, how would I mock the values for properties.source. I am able to mock function call context.getVariable(). I am getting ReferenceError: properties is not defined. Test script in same in the apigee link given. </p>
",https://stackoverflow.com/questions/55521065/mocha-unit-testing-mock-variables-in-javascript,"['testing', 'mocha.js', 'sinon']",433,False,0,1
Angular unit testing &quot;If part not taken&quot;,"<pre><code> Dname = JSON.stringify(this.userDetails);
  Dpass = JSON.stringify({
    userName: 'test',
    password: 'test'
  });

  onSubmit() {
    this.userDetails = this.inputForm.value;
    this.submitted = true;
    if (this.Dname === this.Dpass) {
      this.router.navigate(['/page1']);
      console.log('ok');
    } else {
      console.log('not ok');
    }
  }
</code></pre>

<p><a href=""https://i.stack.imgur.com/ppMVX.png"" rel=""nofollow noreferrer""><strong>If path not taken --can someone help me to solve this issue in angular unit testing</strong></a></p>
",https://stackoverflow.com/questions/59072186/angular-unit-testing-if-part-not-taken,"['angular', 'unit-testing', 'karma-jasmine']",201,False,-1,2
Unit testing react which uses web components,"<p>I am trying to write unit test for react component where in I am using a web component inside my react component. Implementation of the component:</p>

<pre><code>import React, { Component } from ""react"";
import '@vaadin/vaadin-date-picker';

class AppForm extends Component {

   constructor(props) {
      super(props);
      this.state = { dob: '' };
      this.dobRef = React.createRef();
   }

   componentDidMount() {
      this.refs.dobRef.addEventListener('change', e=&gt; {
        console.log('componentDidMount', e.target.value);
      })
   }

render() {
    // const { classes } = this.props;
    return (
        &lt;form onSubmit={this.handleSubmit}&gt;
            &lt;div&gt;
                &lt;div&gt;
                    &lt;div &gt;
                    &lt;vaadin-date-picker label=""When were you born?"" ref=""dobRef""&gt;&lt;/vaadin-date-picker&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;div&gt;
                    &lt;input type=""submit"" value=""Submit"" /&gt;
                &lt;/div&gt;
            &lt;/div&gt;

        &lt;/form&gt;
    )
  }
}

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

<p>vaadin-date-picker is a web component which I am using in here. </p>

<p>The unit test implementation:</p>

<pre><code> import React from 'react';
 import ReactDOM from 'react-dom';
 import AppForm from './AppForm';
 import ShallowRenderer from 'react-test-renderer/shallow';

 it('renders without crashing', () =&gt; {
   const div = document.createElement('div');
   const renderer = new ShallowRenderer();
   renderer.render(&lt;AppForm /&gt;);
   const result = renderer.getRenderOutput();
   expect(result.type).toBe('div');
 });
</code></pre>

<p>I am getting this error:</p>

<pre><code>  SyntaxError: Unexpected string

  1 | import React, { Component } from ""react"";
&gt; 2 | import '@vaadin/vaadin-date-picker';
    | ^
  3 |
  4 | class AppForm extends Component {
  5 |

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.&lt;anonymous&gt; (src/AppForm.js:2:1)
</code></pre>

<p>I am guessing there should be some way to mock this but not sure what. Can someone help out?</p>
",https://stackoverflow.com/questions/54441285/unit-testing-react-which-uses-web-components,"['reactjs', 'unit-testing', 'jestjs', 'web-component']",276,False,0,0
unit testing of defined class using doctests,"<p>i wrote a docstring for doctests and i also wrote function correctly .
But when i run this on hacker rank then it shows Runtime error</p>

<p>I tried using docstring </p>

<pre><code>class Circle():

    def __init__(self, radius):
        # Define the doctests for __init__ method below
    """"""
    &gt;&gt;&gt;c1=Circle(2.5)
    &gt;&gt;&gt;c1.radius()
    2.5
    """"""
         self.radius = radius

    def area(self):
    # Define the doctests for area method below
    """"""
    &gt;&gt;&gt;c1 = Circle(2.5)
    &gt;&gt;&gt;c1.area()
    19.63
    """"""
    # Define the area functionality below
        return round(math.pi*(self.radius**2),2)



    def circumference(self):
    # Define the doctests for circumference method below
    """"""
    &gt;&gt;&gt;c1=Circle(2.5)
    &gt;&gt;&gt;c1.circumference()
    15.71
    """"""
    # Define the circumference functionality below
        return round(2*math.pi*self.radius)
</code></pre>

<p>Runtime error</p>
",https://stackoverflow.com/questions/57314089/unit-testing-of-defined-class-using-doctests,"['unit-testing', 'doctest']",2129,False,-2,3
Unit Testing Factory/Service Locator - Static class,"<p>Recently, I saw this code.  Since I am trying to learn few things at once, I am having issues with this code but dont know how to resolve.  I would like to be able to unit test this code</p>

<pre><code>public static class CarFactory
{
    private static readonly IDictionary&lt;string, Type&gt; CarsRegistry = new Dictionary&lt;string, Type&gt;();

    public static void Register&lt;TCar&gt;(string car) where TCar : CarBase, new()
    {
        if (!CarsRegistry.ContainsKey(car))
        {
            CarsRegistry.Add(car, typeof(TCar));
        }
    }

    public static ICar Create(string car)
    {
        if (CarsRegistry.ContainsKey(car))
        {
            CarBase newCar = (CarBase)Activator.CreateInstance(CarsRegistry[car]);
            return newCar;
        }

        throw new NotSupportedException($""Unknown '{car}'"");
    }
}
</code></pre>

<p>I have few problems with this code.</p>

<ol>
<li>Name is CarFactory but this does not look like a Factory Pattern to me.  It looks more like Locator Pattern</li>
<li>The class is static - and I heard static classes are bad for unit testing in frameworks like Moq and that they also hide dependencies.  Say a method in another regular class uses this, for unit test, there is no way to know that that method depend on this static class</li>
</ol>

<p>I would like to ensure this class is called properly and I think based on my reading that this is Locator Pattern.</p>

<p>I would also like to unit test this class and need help to make it unit testable using Moq.  </p>

<p>Thanks to @ErikPhillips explanation below, I now understand that other classes using this class will be not testable.  So, if I have a class like below:</p>

<pre><code>public class CarConsumer
{
   public void ICar GetRedCar()
   {
     var result = CarFactory.Create(""Tesla"");
     result.Color = Color.Red;
     return result;
   }
}
</code></pre>

<p>, GetRedCar() method will be difficult to test because it uses CarFactory static class and for a unit test or an outside client, there is nothing in GetRedCar() method API that suggest it is depending on this static class.</p>

<p><strong>I would like to refactor CarFactory class so other classes using it like in example above CarConsumer class can be tested properly.</strong>  </p>
",https://stackoverflow.com/questions/54545120/unit-testing-factory-service-locator-static-class,"['c#', 'unit-testing', 'moq', 'factory-pattern', 'service-locator']",346,True,0,1
Trouble with View Unit Testing in AngularJS,"<p>In doing some research on AngularJS component testing I've read about <strong>View Unit Testing</strong>, as described <a href=""https://medium.com/@carmelc_20450/testing-angular-components-you-dont-know-what-you-re-missing-149a1cae6668"" rel=""nofollow noreferrer"">here</a>. I've tried it this way: </p>

<h2>component</h2>

<pre><code>angular.module(""recipeDetail"").component(""recipeSummary"", {
  templateUrl:
    ""modules/recipe-detail/recipe-summary/recipe-summary.template.html"",
  bindings: { recipe: ""&lt;"" },
  controller: function RecipeSummaryController() {}
});
</code></pre>

<h2>template</h2>

<pre class=""lang-js prettyprint-override""><code>&lt;h1 id=""recipe-title""&gt;{{ $ctrl.recipe.title }}&lt;/h1&gt;
&lt;p&gt;
  Steps:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li ng-repeat=""step in $ctrl.recipe.steps"" class=""recipe-summary-step""&gt;
    {{ step.text }}
  &lt;/li&gt;
&lt;/ul&gt;
</code></pre>

<h2>test</h2>

<pre><code>describe(""recipeSummary ViewUnitTest"", () =&gt; {
  let scope;
  let $compile;
  beforeEach(module(""recipeDetail""));

  beforeEach(inject(($rootScope, _$compile_) =&gt; {
    scope = $rootScope.$new();
    $compile = _$compile_;
  }));

  it(""should display the steps"", () =&gt; {
    scope.recipe = recipe;
    let el = angular.element('&lt;recipe-summary recipe=""recipe""/&gt;');
    el = $compile(el)(scope);
    scope.$digest();
    expect(el[0].querySelectorAll(""p"").length).toBe(1); // to make sure this whole thing is working 
    expect(el[0].querySelectorAll("".recipe-summary-step"").length).toBe(3);
  });
});
</code></pre>

<p>Both assertions fail – both the first (<code>p</code>) that checks that I'm implementing the test correctly, and the second (<code>.recipe-summary-step</code>) which tests the actual function of the component.</p>

<h2>UPDATE</h2>

<p>Well don't I feel dumb. George pointed out that I didn't actually <em>call</em> <code>scope.$digest()</code>.</p>

<p>So after doing that I have a new error/failure:</p>

<pre><code>Chrome 74.0.3729 (Mac OS X 10.14.4) recipeSummary ViewUnitTest should display the steps FAILED
        Error: Unexpected request: GET modules/recipe-detail/recipe-summary/recipe-summary.template.html
        No more request expected
        error properties: Object({ $$passToExceptionHandler: true })
            at createFatalError (/Users/TuzsNewMacBook/Development/code/AngularJS/recipe-angular-from-phonecat/node_modules/angular-mocks/angular-mocks.js:1569:19)
            at $httpBackend (/Users/TuzsNewMacBook/Development/code/AngularJS/recipe-angular-from-phonecat/node_modules/angular-mocks/angular-mocks.js:1616:11)
            at sendReq (lib/angular/angular.js:13257:9)
            at serverRequest (lib/angular/angular.js:12998:16)
            at processQueue (lib/angular/angular.js:17914:37)
            at lib/angular/angular.js:17962:27
            at ChildScope.$digest (lib/angular/angular.js:19075:15)
            at UserContext.&lt;anonymous&gt; (modules/recipe-detail/recipe-summary/recipe-summary.component.spec.js:32:11)
            at &lt;Jasmine&gt;
</code></pre>

<p>Apparently a <code>templateUrl</code> is resolved with an actual <code>get</code> request and apparently that's a fatal error. So how do I use this technique? </p>
",https://stackoverflow.com/questions/56309030/trouble-with-view-unit-testing-in-angularjs,"['angularjs', 'unit-testing']",84,False,0,0
Error in software unit testing simple program?,"<p>Testcode.py</p>

<pre><code>import code
import unittest

class TestCode( unittest.TestCase ):
    def test_simple( self ):
        self.assertEqual( code.return_zero(),0 )
if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>code.py</p>

<pre><code>def return_zero ():
    return 0
</code></pre>

<p>expected ok result </p>

<p>but getting this below error</p>

<pre><code>-----------------------------
Traceback (most recent call last):
  File ""C:++++++/.spyder-py3/testcode.py"", line 6, in test_simple
    self.assertEqual( code.return_zero(),0 )
AttributeError: 'Testcode' object has no attribute 'assertnotEqual'

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

FAILED (errors=2)
</code></pre>
",https://stackoverflow.com/questions/58781833/error-in-software-unit-testing-simple-program,"['python-3.x', 'unit-testing']",18,False,0,1
Issues unit testing data dependent REST apis,"<p>I have been tasked to write unit tests for an authentication service, coded and maintained by my coworker.
I have been given a set of REST apis which allow me to use such service to authenticate a user and get a JWT token, to change a user's password and all the common things an authentication service does. I chose the xunit framework to write my test modules.
Now, each unit test should be completely isolated from the others and all tests should be able to pass regardless of the order of execution. I'm finding it very difficult to adhere to these practices though:</p>

<p>1) some of the REST apis I'm testing modify the DB and this may cause annoying side effects. E.G.: if i test the api to change a user's password and somehow I can't revert the change, I'm not able to have such test pass anymore unless I manually access the db to revert it.</p>

<p>2) I can't run all my tests in parallel and some of them are not so fast. Also, side effects again  E.G.: if I test that a user is blocked as a result of many wrong login attempts, I must make sure that I don't use the same user to test a normal login and that is becoming increasingly annoying as the amount of tests grows. Also, I have to wait until the lock period expires to check that the user is able to login again.</p>

<p>Many tests seem too coupled to each other and all seem to be too much dependent on the state of the DB. I don't even have access to the DB so I'm forced to ask the service's developer to modify the test DB in order to satisfy my needs.
The entire process feels so clunky. What are the best practices to structure unit test when I can't mock up the data layer and what I'm testing is highly dependent on data?</p>

<p>I have come to the conclusion that the right approach should have been the following: my coworker should have been writing unit tests directly against his backend modules, without passing through web api calls. That way he could have easily mocked up the data layer, effectively decoupling unit tests from the db. Only then, maybe I could have written some integration tests to test REST apis. Is my conclusion unreasonable?</p>
",https://stackoverflow.com/questions/58800890/issues-unit-testing-data-dependent-rest-apis,"['c#', 'unit-testing', 'web-applications', 'xunit', 'xunit.net']",93,False,0,0
Unit testing: Prevent creation of duplicate objects,"<p>My professor gave us this homework exercise and has created a project with
a bunch of unit tests.
Our goal is to make sure we can pass those unit tests.
We have three classes.
A class called Person with a name and an age,
a class Speaker that extends Person,
and a class Attendee that also extends Person.
I am struggling with making sure that there are no duplicate people. <code>generateRandomString()</code> was implemented by the professor and just returns a random string.</p>

<p>I already created the class,
it's constructor,
getters,
and setters.
I also overrode the method <code>equals()</code> in the class <code>Person</code></p>

<p>This is the test our professor gave us:</p>

<pre class=""lang-java prettyprint-override""><code>    @Test
    public void testNoDuplicatePerson() {
      HashSet&lt;Person&gt; people = new HashSet&lt;Person&gt;();
      String name = generateRandomString();
      Person p = new Speaker(name);
      people.add(p);
      assertEquals(1,people.size());
      p = new Attendee(name);
      people.add(p);
      assertEquals(1,people.size());
    }
</code></pre>

<p>How can I pass this test?</p>

<p>EDIT: I decided to post the code of the three classes:</p>

<pre><code>Person
 ```java
public abstract class Person {
    private String name;
    private int age;

    public Person(String name) {
        this.name = name;
        this.age = 0;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean equals(Object o) {
        if (o == null || !(o instanceof Person))
            return false;
        Person converted = (Person) o;
        if (this.getName().equals(converted.getName()) &amp;&amp; this.getAge() == converted.getAge())
            return true;
        return false;
    }
}

</code></pre>

<p>Speaker:</p>

<pre class=""lang-java prettyprint-override""><code>public class Speaker extends Person {

    private int fee;

    public Speaker(String name) {
        super(name);
        this.fee = 0;
    }

    public Speaker(String name, int age) {
        super(name, age);
        this.fee = 0;
    }

    public Speaker(String name, int age, int fee) {
        super(name, age);
        this.fee = fee;
    }

    public int getFee() {
        return fee;
    }

    public void setFee(int fee) {
        this.fee = fee;
    }

    public String toString() {
        return ""Speaker "" + this.getName() + "" as a fee value of "" + this.getFee() + ""."";
    }
}
</code></pre>

<p>Attendee:</p>

<pre class=""lang-java prettyprint-override""><code>public class Attendee extends Person {
    private boolean paid;

    public Attendee(String name) {
        super(name);
        this.paid=false;
    }

    public Attendee(String name, int age) {
        super(name, age);
        this.paid=false;
    }

    public boolean hasPaid(){
        if (this.paid==true)
            return true;
        return false;
    }
    public String toString(){
        return ""Attendee ""+this.getName()+(this.hasPaid() ? "" has"":"" hasn't"")+"" paid its registration."";
    }
}
</code></pre>
",https://stackoverflow.com/questions/55314608/unit-testing-prevent-creation-of-duplicate-objects,"['java', 'unit-testing']",183,True,0,1
Python unit testing for long running functions,"<p>I have a long running python method, this function will go inside folders and read all the documents and extract text. Number of output will not going to be a constant as it can change. This process might take from several hours to days. How to write a unit test for such a function, how to check whether its pass or fail as the number of output might change and it takes many hours</p>
",https://stackoverflow.com/questions/55204382/python-unit-testing-for-long-running-functions,"['python', 'unit-testing']",1076,True,0,1
Angular/NgRx Unit testing can&#39;t create TestBed,"<p>While developing a component that requires and NgRx store the testing suite fails and I get a message stating that...</p>

<p>'Can't resolve all parameters for NavComponent: (?).'</p>

<pre><code>  ● AppComponent › should create the app

    Can't resolve all parameters for NavComponent: (?).

      at syntaxError (../packages/compiler/src/util.ts:100:17)
      at CompileMetadataResolver._getDependenciesMetadata (../packages/compiler/src/metadata_resolver.ts:957:27)
      at CompileMetadataResolver._getTypeMetadata (../packages/compiler/src/metadata_resolver.ts:836:20)
      at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (../packages/compiler/src/metadata_resolver.ts:377:18)
      at CompileMetadataResolver.loadDirectiveMetadata (../packages/compiler/src/metadata_resolver.ts:224:11)
      at ../packages/compiler/src/jit/compiler.ts:135:36
          at Array.forEach (&lt;anonymous&gt;)
      at ../packages/compiler/src/jit/compiler.ts:133:65
          at Array.forEach (&lt;anonymous&gt;)
      at JitCompiler._loadModules (../packages/compiler/src/jit/compiler.ts:130:71)
      at JitCompiler._compileModuleAndAllComponents (../packages/compiler/src/jit/compiler.ts:115:32)
      at JitCompiler.compileModuleAndAllComponentsAsync (../packages/compiler/src/jit/compiler.ts:69:33)
      at CompilerImpl.compileModuleAndAllComponentsAsync (../packages/platform-browser-dynamic/src/compiler_factory.ts:69:27)
      at TestingCompilerImpl.compileModuleAndAllComponentsAsync (../../packages/platform-browser-dynamic/testing/src/compiler_factory.ts:57:27)
      at TestBedViewEngine.compileComponents (../../packages/core/testing/src/test_bed.ts:362:27)
      at Function.TestBedViewEngine.compileComponents (../../packages/core/testing/src/test_bed.ts:160:66)
      at src/app/app.component.spec.ts:32:8
      at ZoneDelegate.Object.&lt;anonymous&gt;.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:391:26)
      at ProxyZoneSpec.Object.&lt;anonymous&gt;.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:129:39)
      at ZoneDelegate.Object.&lt;anonymous&gt;.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:390:52)
      at Zone.Object.&lt;anonymous&gt;.Zone.run (node_modules/zone.js/dist/zone.js:150:43)
</code></pre>

<p>My test bed config</p>

<pre><code>describe('AppComponent', () =&gt; {
  let router: Router;
  let location: Location;
  let store: MockStore&lt;ApplicationState&gt;;
  const initialState: ApplicationState = {
    root: {
      user: null,
      tabs: null
    }
  };

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes(routes), MaterialsModule],
      declarations: [AppComponent, NavComponent],
      providers: [provideMockStore({ initialState })]
    }).compileComponents();
    router = TestBed.get(Router);
    location = TestBed.get(Location);
    store = TestBed.get&lt;Store&lt;ApplicationState&gt;&gt;(Store);

    router.initialNavigation();
  });
</code></pre>

<p>The Component</p>

<pre><code>@Component({
  selector: 'af3-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
  tabs$: Observable&lt;NavTab[]&gt;;
  constructor(private store: Store&lt;fromStore.ApplicationState&gt;) {}

  ngOnInit() {
    // this.tabs$ = this.store.pipe(select(fromStore.selectTabsForUserState));
  }
}
</code></pre>

<p>I have also tried to import StoreModule, but according to <a href=""https://ngrx.io/guide/store/testing"" rel=""nofollow noreferrer"">ngrx.io</a>, that isn't necessary as <code>provideMockStore()</code> setups up all the providers necessary with configuring the reducers.</p>

<p>The error and the stack trace aren't very helpful.</p>

<p>Thanks in advance for any help.</p>

<p>UPDATE: it turns out that the test bed can't inject ANY referenced services. I created a test service and tried to run the test, but received the same errors when running the tests.</p>

<p>UPDATE: NGRX is definitely not the issue. To add some more context I have been trying to track this issue down. Currently no providers can be resolved. I replace Jasmine with Jest and it looks like Jest may be the issue.</p>
",https://stackoverflow.com/questions/58736207/angular-ngrx-unit-testing-cant-create-testbed,"['angular', 'unit-testing', 'ngrx']",225,False,0,1
C Unit Testing - Mock (In Check Framework),"<p>I'm trying to ""mock"" some things in my unit testing of a C project.
I am using the Check framework for testing and I have a function that reads from a file on disk to verify the contents.</p>

<p>My function is: </p>

<pre><code>#include ""verifier.h""
#include &lt;stdio.h&gt;

int verify_content(char *path, char *verify_string) {
    File *fptr
    fptr = fopen(path, ""r"")
    // Do verification
    return 0
</code></pre>

<p>and my test is</p>

<pre><code>START_TEST (verify_content_test)
    {
        char *test_path = ""test_path"";
        char *test_string = ""unique_string_content_here"";
        ck_assert_str_eq(verify_content(test_path, test_string), 0);
    }
END_TEST
</code></pre>

<p>However, I don't want this to read from disk, because that would be slow, and I'd have to have multiple static files just for testing against.</p>

<p>Is there a way to ""mock""/""fake"" the fopen?</p>

<p>I'm still new to C development and super new to unit testing in C so if I should approach this problem differently, please point me in the right direction.</p>
",https://stackoverflow.com/questions/58174186/c-unit-testing-mock-in-check-framework,"['c', 'unit-testing', 'mocking']",253,False,0,1
if(!response.error) unit testing using Jest Enzyme,"<p>Have the following test using <strong>Jest</strong> and <strong>Enzyme</strong></p>

<pre><code>it('Test createAccount function ',async() =&gt; {
    wrapper.setProps({})
    wrapper.find('AccountForm').setState({});
    wrapper.update();
    await 
    expect(wrapper.find('AccountForm').instance().createAccount()).toBeDefined()
});
</code></pre>

<p>Here is the main file <strong>JS</strong></p>

<pre><code>async createAccount(){
    const { user, services } = this.props;
    let AccountBody = { //list of this.states }
    let response = await Models.postAccount({
        user,
        services,
        firmId: FirmId,
        body: AccountBody
    })
    if(!response.error) { 
        return true;
    } else {
        return false;
    }
}
</code></pre>

<p>Not really sure how to approach a unit test in order to test response and its return  </p>

<pre><code>let response = await Models.postAccount({
</code></pre>

<p>How could i call response in my test above to make sure the whole function gets tested correctly. I have done similar unit tests in the past but not too familiar when it comes to async/ await and response</p>

<p>I appreciate any help.</p>
",https://stackoverflow.com/questions/56549062/ifresponse-error-unit-testing-using-jest-enzyme,"['unit-testing', 'jestjs', 'response']",98,True,0,1
Unit testing methods containing AWSAPIGatewayResponse in swift,"<p>I have the following method and I'm trying to unit test this in iOS/Swift</p>

<pre><code>func apiResponseResults(response: AWSAPIGatewayResponse, sessionObject: Session) {
    if response.statusCode == 200 {
        // code
    } else {
        // code
    }
}
</code></pre>

<p>This method is called from my api <code>invoke</code> method when the response is received. I want to unit test this by creating a fake <code>AWSAPIGatewayResponse</code> object.
I am not able to create <code>AWSAPIGatewayResponse</code> object. Is there a way to initialize this object in my unit testing class. I just wanna create an <code>AWSAPIGatewayResponse</code> object with statusCode as <code>200</code> and <code>300</code>. Any help is appreciated.</p>
",https://stackoverflow.com/questions/55741506/unit-testing-methods-containing-awsapigatewayresponse-in-swift,"['ios', 'swift', 'amazon-web-services', 'unit-testing', 'aws-api-gateway']",41,False,0,1
"Unit testing Apollo, errorring on mutation mock","<p>I'm trying to mock out a graphql mutation for my unit tests. I'm using the MockedProvider but I'm getting the error: 'UnhandledPromiseRejectionWarning: Error: No more mocked responses for the query: mutation LoginMutation'</p>

<p>I've done a lot of googling, and copy pasted everything into one file so that there can be no issues with imports</p>

<pre><code>const LOGIN_MUTATION = gql`
    mutation LoginMutation($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      token
      user {
        name
      }
    }
  }
`;

const mocks = [
  {
    request: {
      query: LOGIN_MUTATION,
      variables: { email: 'test@test.com', password: 'password' },
    },
    result: {
      data: {
        login: {
          token: 'fakeToken',
          user: {
            name: 'Testy McTestface'
          }
        }
      }
    }
  }
]

describe('LoginForm', () =&gt; {
  let wrapper;
  let store;

  beforeEach(() =&gt; {
    store = mockStore(initialState);
  });

  it('triggers the doLogin action creator after the graphql call', () =&gt; {
    const mockDoLogin = jest.fn()
    let mockedWrapper = mount(
      &lt;MockedProvider mocks={mocks} addTypename={false}&gt;
        &lt;Provider store={store}&gt;
          &lt;LoginForm doLogin={mockDoLogin} /&gt;
        &lt;/Provider&gt;
      &lt;/MockedProvider&gt;,
    );
    mockedWrapper.find('#loginButton').simulate('click')
    expect(mockDoLogin).toHaveBeenCalledTimes(1)
  })
});
</code></pre>

<p>I expect this test to pass (the tag searched for on the wrapper is the correct one) but I get the error described above, so I'm assuming the issue is with my mock but it looks good to me?</p>

<p>Sorry if this is something ridiculously obvious but I've been staring at it for hours now.</p>
",https://stackoverflow.com/questions/54508474/unit-testing-apollo-errorring-on-mutation-mock,"['reactjs', 'testing', 'apollo']",2616,True,0,1
Python unit testing a request that fails,"<p>I'm trying to test a http call that is supposed to fail but I want to return a value. However the test I do doesn't pass in the coverage :</p>

<pre><code>    def callAPI(self, tokenURL:str):
    requestBuilder: RequestBuilder = RequestBuilder()

    try:
        response = requestBuilder.get(tokenURL)
        return response.json()
        # return ""content""
    except Exception as err:
        Logger.error(""An error occured while trying to call API ""+ err)
        return None
</code></pre>

<p>This is my test function :</p>

<pre><code>@responses.activate
def testCallDemFails():
  responses.add(
    responses.GET, 'http://calldem.com/api', json=""{'err'}"", status=500)

  with pytest.raises(Exception):
    demConfig = DemConfig()
    resp = demConfig.callAPI('http://callAPI.com/api/1/foobar')
    print(""testCallAPIFail"", resp)
    assert resp == None
</code></pre>

<p>The requestBuilder.get method just return a request.get function. When I execute the function, I don't even have the testAPI fail. Do you have any ideas ?</p>
",https://stackoverflow.com/questions/58628984/python-unit-testing-a-request-that-fails,"['python', 'pytest']",666,True,0,1
Laravel resources wrap twice when unit testing,"<p>When I run a test suit, my tests that return a <code>ResourceCollection</code> fails because the data is wrap twice but success when I run them individually.  </p>

<p><strong>I already know the cause</strong><br>
<code>ResourceCollection</code> use a <strong>static</strong> variable called <strong>wrap</strong> and between the tests, this variable keep his state.  </p>

<p><strong>Now I need to fix it</strong></p>

<p>Take theses two methods as starting point in the <strong>OrganizationsController</strong></p>

<pre><code>/**
 * @param Request $request
 * @return OrganizationsResource
 */
public function index(Request $request): OrganizationsResource
{
    return new OrganizationsResource(
        Organization::paginate()
    );
}

/**
 * @param Request $request
 * @param Organization $organization
 * @return OrganizationResource
 */
public function show(Request $request, Organization $organization): OrganizationResource
{
    OrganizationResource::withoutWrapping();
    return new OrganizationResource($organization);
}
</code></pre>

<p>The <strong>OrganizationsResource</strong></p>

<pre><code>&lt;?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;

class OrganizationsResource extends ResourceCollection
{

    /**
     * @param Request $request
     * @return array
     */
    public function toArray($request): array
    {
        return [
            'data' =&gt; OrganizationResource::collection($this-&gt;collection),
        ];
    }
}
</code></pre>

<p>And the <strong>OrganizationResource</strong></p>

<pre><code>&lt;?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class OrganizationResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {

        return [
            'id'         =&gt; $this-&gt;id,
            'type'       =&gt; 'organization',
            'attributes' =&gt; [
                'name' =&gt; $this-&gt;resource-&gt;name,
            ],
        ];
    }
}
</code></pre>

<p><strong>This works perfectly fine</strong> the response given for the <strong>index</strong> will be build like this:</p>

<pre><code>{
 ""data"": [
    {""id"": 1},{""id"": 2}, ....
 ],
 ""links"": {
    ""next"": ""http://..."",
    ....
 },
 ""meta"": {
    ""current_page"": 1,
    ....
 }
}
</code></pre>

<p>And as expected, the <strong>show</strong> will return</p>

<pre><code>{
    ""id"": 1,
    ""type"" ""organization"",
    ....
}
</code></pre>

<p><strong>However</strong>, when I run all my unit tests, my <strong>index(es)</strong> returns the the following json (notice <code>{""data"":{""data""...</code></p>

<pre><code>{
 ""data"": {
     ""data"": [
        {""id"": 1},{""id"": 2}, ....
     ],
     ""links"": {
        ""next"": ""http://..."",
        ....
     },
     ""meta"": {
        ""current_page"": 1,
        ....
     }
    }
}
</code></pre>

<p>Here's one of the test that succeed when running alone but fail after <code>withoutWrapping</code> as been called once in a test suit</p>

<pre><code>/** @test */
public function organizations_api_index_returns_valid_schema(): void
{
    factory(Organization::class, 2)-&gt;create(['name' =&gt; 'My-Company']);
    $this-&gt;json('get', '/organizations')-&gt;assertJsonSchema(base_path(""{$this-&gt;schema}/organizations.json""));
}
</code></pre>

<p>In case you wondering about <code>assertJsonSchema</code> this is from <a href=""https://github.com/sixlive/laravel-json-schema-assertions"" rel=""nofollow noreferrer"">sixlive/laravel-json-schema-assertions</a></p>

<h3>Temporary workaround</h3>

<p>I'm running my tests with <code>processIsolation</code> set to <code>true</code> in my <strong>phpunit.xml</strong> But it's extremely slow</p>
",https://stackoverflow.com/questions/55380058/laravel-resources-wrap-twice-when-unit-testing,"['php', 'laravel', 'phpunit', 'laravel-5.7']",798,True,0,1
Unit Testing non returning functions in Qt,"<p>you might remember me or running a kind of a 'Lightroom' panel, using C++ and Qt for GUI.
Today I was reading about implementing a unit testing for my main classes, but my question is, how can I test a function that does not return anything?</p>

<p>for example, I got that function:</p>

<pre><code>void ImgProcessing::processMaster(cv::Mat&amp; img, cv::Mat&amp; tmp, int brightness, int red, int green, int blue, double contrast){

for(int i = 0; i &lt; img.rows; i++)
    for(int j = 0; j &lt; img.cols; j++)
        for(int k = 0; k &lt; 3; k++){
            if(k == 0)  //_R
                tmp.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;((img.at&lt;cv::Vec3b&gt;(i,j)[k] + brightness + red )*(259 * (contrast + 255) / (255 * (259 - contrast))));
            if(k == 1)  //_G
                tmp.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;((img.at&lt;cv::Vec3b&gt;(i,j)[k] + brightness + green )*(259 * (contrast + 255) / (255 * (259 - contrast))));
            if(k == 2)  //_B
                tmp.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;((img.at&lt;cv::Vec3b&gt;(i,j)[k] + brightness + blue )*(259 * (contrast + 255) / (255 * (259 - contrast))));
        }            
</code></pre>

<p>this function just take the obj 'mat img', and modify the 'mat tmp' obj.
than I update the UI for display the modified image, by using another dedicated function in my gui class.</p>

<p>Has someone already encounter something like that?</p>
",https://stackoverflow.com/questions/56768238/unit-testing-non-returning-functions-in-qt,"['c++', 'qt', 'unit-testing', 'qt-creator']",196,True,0,1
Unit testing with mock [Symfony 4 api],"<p>I want to test my controller's functions with PHP unit using MOCK (in an API symfony 4) but i can't find a way to. 
In fact i have do several research and coudn't find a way to do it, I installed PHP unit and coded a test web case without mock and it's work it but not by mock. i want to use mocking because i don't want to touch the database. 
Anyone can help me please to achieve that .</p>

<p>This is my controller:</p>

<pre><code>&lt;?php

   namespace App\Controller;


   use App\Utils\MatchServiceInterface;
   use App\Utils\ModeServiceInterface;
   use App\Utils\PlayerServiceInterface;
   use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
   use Symfony\Component\HttpFoundation\JsonResponse;
   use Symfony\Component\HttpFoundation\Request;
   use Symfony\Component\Routing\Annotation\Route;


   /**
   * @Route(""/api/scouters/matchs"")
   * Manage entity Match
   * Class MatchController
   * @package App\Controller
   */
   class MatchController extends AbstractController
   {

private $playerService;
private $modeService;
private $matchService;

/**
 * ScouterController constructor.
 * @param PlayerServiceInterface $playerService
 * @param ModeServiceInterface $modeService
 * @param MatchServiceInterface $matchService
 */
public function __construct(PlayerServiceInterface  $playerService, ModeServiceInterface $modeService, MatchServiceInterface $matchService)
{
    $this-&gt;playerService = $playerService;
    $this-&gt;modeService = $modeService;
    $this-&gt;matchService = $matchService;
}

/**
 * @Route(""/create"", name=""create_match"", methods={""POST""})
 * @param Request $request
 * @return JsonResponse
 */
public function createMatch(Request $request): JsonResponse
{
    $content = json_decode($request-&gt;getContent(), true);
    $message = $this-&gt;playerService-&gt;assignPlayerToMatch($content);
    return new JsonResponse($message, JsonResponse::HTTP_OK);
}

/**
 * @Route(""/mode"", name=""mode_match"", methods={""POST""})
 * @param Request $request
 * @return JsonResponse
 * @return JsonResponse
 */
public function modeMatch(Request $request): JsonResponse
{
    $content = json_decode($request-&gt;getContent(), true);
    $message = $this-&gt;modeService-&gt;assignModeToMatch($content);
    return new JsonResponse($message, JsonResponse::HTTP_OK);
}

/**
 * @Route(""/features"", name=""feat_mode_match"", methods={""POST""})
 * @param Request $request
 * @return JsonResponse
 */
public function featMode(Request $request): JsonResponse
{
    $content = json_decode($request-&gt;getContent(), true);
    $this-&gt;matchService-&gt;modeFeature($content);
    $message = $this-&gt;matchService-&gt;modeFeature($content);
    return new JsonResponse($message, JsonResponse::HTTP_OK);
}
</code></pre>

<p>}</p>

<p>this is an example of test of my login function ,</p>

<pre><code>   /**
 * test ScouterController:login
 */
public function testLogin()
{
    $data = ['email' =&gt; 'meher.jaber@solixy.com', 'password' =&gt; 'FootStat@2019'];
    $client = static::createClient();
    $request = $client-&gt;request('POST', '/api/scouter/login', [], [], [], json_encode($data));
    $response = $client-&gt;getResponse();
    $this-&gt;assertSame('""EmailPasswordValidAndHasNotPlayer""', $response-&gt;getContent());
    $this-&gt;assertSame(200, $response-&gt;getStatusCode());

}
</code></pre>

<p>Login function :</p>

<pre><code>/**
 * Login Scouter
 * @Route(""/login"", name=""login_scouter"", methods={""POST""})
 * @param Request $request
 * @return JsonResponse
 */
public function login(Request $request): JsonResponse
{
    $content = json_decode($request-&gt;getContent(), true);
    $message = $this-&gt;securityService-&gt;loginScouter($content);
    $this-&gt;securityService-&gt;loginScouter($content);
    return new JsonResponse($message, JsonResponse::HTTP_OK);
}
</code></pre>

<p>Login service :</p>

<pre><code> /**
 * @param $content
 * @return array|string
 */
public function loginScouter($content)
{
    $scouter = $this-&gt;em-&gt;getRepository(Scouter::class)-&gt;findOneBy(['email' =&gt; $content['email']]);
    if ($scouter) {
        /* @var $scouter Scouter */
        if ($this-&gt;encoder-&gt;isPasswordValid($scouter, $content['password'])) {
            if (is_null($scouter-&gt;getPlayer())) {
                $message = ""EmailPasswordValidHasNotPlayer"";
            } else {
                /* @var $player Player */
                $player = $scouter-&gt;getPlayer();
                /* @var $lastMatch Match */
                $lastMatch = $this-&gt;em-&gt;getRepository(Match::class)-&gt;findLastInserted($player-&gt;getId());
                $message = ['idPlayer' =&gt; $player-&gt;getId(), 'firstName' =&gt; $player-&gt;getFirstName(), 'lastName' =&gt; $player-&gt;getFamilyName(), 'team' =&gt; $lastMatch-&gt;getTeam(), 'oppTeam' =&gt; $lastMatch-&gt;getOppositeTeam()];
            }
        } else {
            $message = ""PasswordInvalid"";
        }
    } else {
        $message = ""EmailInvalid"";
    }
    return $message;
}
</code></pre>
",https://stackoverflow.com/questions/58391310/unit-testing-with-mock-symfony-4-api,"['php', 'api', 'symfony', 'mocking', 'phpunit']",649,False,0,0
Unit Testing a private method giving MissingMethodException,"<p>I need to call a <code>private</code> method in my unit test using <code>PrivateObject</code>.</p>

<pre class=""lang-cs prettyprint-override""><code>private void UrgentBackupButton_Click(object parameter)
{
    // Do Something...
}
</code></pre>

<p>Here is my unit test:</p>

<pre class=""lang-cs prettyprint-override""><code>[TestMethod]
public void TestMethod1()
{
    //MainWindowViewModel main = new MainWindowViewModel();

    PrivateObject privateObj = new
    PrivateObject(typeof(MainWindowViewModel));

    privateObj.Invoke(""UrgentBackupButton_Click"",null);
}
</code></pre>

<p>It is giving me exception at <code>privateObj.Invoke(""UrgentBackupButton_Click"",null)</code>:</p>

<blockquote>
  <p>An exception of type 'System.MissingMethodException' occurred in mscorlib.dll but was not handled in user code</p>
</blockquote>

<p>Can someone please help?</p>
",https://stackoverflow.com/questions/56239875/unit-testing-a-private-method-giving-missingmethodexception,"['c#', 'unit-testing']",368,True,-1,2
Create database for unit testing in sqlite,"<p>I have a simple class driven sqlite app. Basically, I want to run unit tests for it, but I haven't been able to so far.</p>

<pre><code>class DB:
    def __init__(self, dbname='mydb.db'):    
        try:
            self.connection = sqlite3.connect(dbname)
        except:
            print('Error')
        finally:
            pass
</code></pre>

<p>Any class would use it then:</p>

<pre><code>class Hello:
    def hi(self):
        db = DB() # Create db or connect to existing one
        cursor = db.connection.cursor()
</code></pre>

<p>Now, when testing, I pass on a test database:</p>

<pre><code>db = DB('test.db')
#create datatabase here and all works fine
h = Hello()
</code></pre>

<p>Now, h makes use of mydb.db, instead of test.db. How does one go out about testing the above structure?</p>
",https://stackoverflow.com/questions/55480435/create-database-for-unit-testing-in-sqlite,"['python', 'sql', 'python-3.x', 'sqlite']",5069,True,0,1
Unit Testing Go Functions having ORM interactions,"<p>I have written a function:</p>

<pre><code>func AllItems(w http.ResponseWriter, r *http.Request) {
    db, err := gorm.Open(""sqlite3"", ""test.db"")
    if err != nil {
        panic(""failed to connect database"")
    }
    defer db.Close()

    var items [] Item
    db.Find(&amp;items)
    fmt.Println(""{}"", items)

    json.NewEncoder(w).Encode(items)
}
</code></pre>

<p>I want to do unit testing on this. Ideally, unit testing means that each line of the function needs to be tested. I'm not sure how I should test if a database connection is opened and then if it is displaying all the contents of the database. How should I test this code? </p>

<p>This function is the GET endpoint of a simple CRUD application. The code is <a href=""https://github.com/ShubhamRathi/ToDo-App"" rel=""nofollow noreferrer"">here</a>. </p>
",https://stackoverflow.com/questions/54648551/unit-testing-go-functions-having-orm-interactions,"['unit-testing', 'go', 'mocking', 'testify']",195,True,0,1
Unit Testing a simple in-memory cache,"<p>I have a simple in-memory cache that looks like (oversimplified) below:</p>

<pre class=""lang-cs prettyprint-override""><code>class Cache {
    private Map&lt;String, Integer&gt; m = new HashMap&lt;&gt;();

    public String get(String key) {
        if(!m.containsKey(key))
            return null;

        return m.get(key);
    }

    public void set(String key, String value) {
        m.put(key, value);
    }

    public Set&lt;String&gt; getKeys() {
        return m.keySet();
    }
}
</code></pre>

<p>Now I want to write Unit Tests for this class. I was thinking I can do something along the lines of:</p>

<pre class=""lang-cs prettyprint-override""><code>[TestMethod]
public void Get_Success() {
    Cache c = new Cache();
    c.set(""Apple"", 1);
    c.set(""Grape"", 2);
    c.set(""Banana"", 3);

    Assert.Equals(1, c.get(""Apple""));
    Assert.Equals(2, c.get(""Grape""));
    Assert.Equals(3, c.get(""Banana""));
}
</code></pre>

<p>But the problem is, it tests both <code>Set</code> and <code>Get</code> methods. So if the test breaks, I will not know whether the bug is in <code>Set</code> or <code>Get</code>.</p>

<p>What is the recommended way to test the <code>Get</code> and <code>Set</code> methods individually?</p>

<p>One way I thought was, to modify the <code>Cache</code> class to accept a <code>Map&lt;String, Integer&gt;</code> instance like:</p>

<pre class=""lang-cs prettyprint-override""><code>class Cache {
    private Map&lt;String, Integer&gt; m = new HashMap&lt;&gt;();

    public Cache(Map&lt;String, Integer&gt; m) {
        this.m = m;
    }

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

<p>Then from the test, I can create an instance of Map and pass it to Cache constructor. Then all the <code>Set</code> operations will happen in the map instance that I passed and I can validate whether <code>Set</code> worked as expected.</p>

<p>But I am not very sure whether it's the right approach.</p>

<p>Similarly, I want the ability to test <code>Get</code> as well without depending on <code>Set</code>.</p>
",https://stackoverflow.com/questions/54680898/unit-testing-a-simple-in-memory-cache,"['java', 'unit-testing']",820,False,0,0
Unit testing with multi-step user inputs,"<p>I'm unit testing a part of code which asks for one argument at a time before bringing them back.
I'd like to write a test that the prompt is what it should be, but I'm unsure how to test each stage of the prompt.
Say the prompt is: 
""what is variable 1""
--user input--
""what is variable 2""
--user input--</p>

<p>Then the unit test would be something like..</p>

<pre><code>with self.subTest(args=args):
                    result = _run(args)
                    self.assertRegex(result.stdout,r'(?m)^'what is variable 1?""
</code></pre>

<p>But when I try to submit just one variable at a time to 'args' then the test hangs. But when I try to submit all variables at once, the code fails and says <code>""'what is variable 1' not found in ''""</code></p>
",https://stackoverflow.com/questions/57446100/unit-testing-with-multi-step-user-inputs,"['python', 'unit-testing']",54,True,-1,1
Django channels ProtocolTypeRouter unit testing with pytest,"<p>I am checking out channels for the next project. But I am stuck at unit testing the basics. I guess it must be something I keep overlooking. </p>

<p><strong>Versions:</strong></p>

<ul>
<li>channels==2.1.7</li>
<li>django==2.1.3</li>
</ul>

<p><strong>routing.py</strong></p>

<pre><code>from channels.routing import ProtocolTypeRouter #, URLRouter
from Phoenix.ProtocolTestConsumer import ProtocolTestConsumer

application = ProtocolTypeRouter({
    # Empty for now (http-&gt;django views is added by default)

    ""test"": ProtocolTestConsumer,
})
</code></pre>

<p><strong>ProtocolTestConsumer.py</strong></p>

<pre><code>import logging
logging.basicConfig(level=logging.DEBUG)

from django.conf import settings
from channels.consumer import SyncConsumer

class ProtocolTestConsumer(SyncConsumer):
    def test_a(self, event):
        logging.debug(""consumer test_a {}"".format(event))

    def test_b(self, event):
        logging.debug(""consumer test_b {}"".format(event))

    def test_c(self, event):
        logging.debug(""consumer test_c {}"".format(event))
</code></pre>

<p><strong>test_ProtocolTestConsumer.py</strong></p>

<pre><code>import pytest
import logging

from Phoenix.ProtocolTestConsumer import ProtocolTestConsumer
from channels.testing import ApplicationCommunicator

communicator = ApplicationCommunicator(ProtocolTestConsumer, {""type"": ""test""})

@pytest.mark.asyncio
async def test_call_a():
    await communicator.send_input(
        {""type"": ""test.a"",
         ""text"": ""Blue""})
    logging.debug(""pytest is printing this"")
</code></pre>

<p><strong>DJANGO_SETTINGS_MODULE=web.settings pytest -s -v</strong></p>

<pre><code>== test session starts ==
platform linux -- Python 3.7.1, pytest-4.1.1, py-1.7.0, pluggy-0.8.1 -- /home/user/src/web/Phoenix/venv-phoenix/bin/python3.7
cachedir: .pytest_cache
Django settings: web.settings (from environment variable)
rootdir: /home/user/src/web/Phoenix/web/Phoenix, inifile:
plugins: django-3.4.5, asyncio-0.10.0
collected 1 item                                                                                        

test_ProtocolTestConsumer.py::test_call_a DEBUG:asyncio:Using selector: EpollSelector
DEBUG:root:pytest is printing this
PASSED

== 1 passed in 0.24 seconds ==
</code></pre>

<p>I expected to see more console output from the Consumer.</p>
",https://stackoverflow.com/questions/54477038/django-channels-protocoltyperouter-unit-testing-with-pytest,['django-channels'],1009,False,0,1
Skip authorization while unit testing in Lumen,"<p>Is there a way to skip Authorization middleware when running unit testing for a Lumen application?</p>
",https://stackoverflow.com/questions/58536850/skip-authorization-while-unit-testing-in-lumen,"['middleware', 'lumen', 'lumen-5.8']",562,True,0,1
MassTransit - Unit Testing a Large Payload Consumer,"<p>Using the InMemoryTestHarness, I am working on unit testing a Consumer that handles a command with a MessageData property.  Using the InMemoryMessageDataRepository to populate the MessageData property works fine however, when the consumer attempts to load the payload (message.Body.Value) I am receiving the following exception: ""The message data was not loaded: urn:msgdata:xxxxxxxxxxxxxxxxxxxxxxxxxx""}.  What is the proper way to unit test a consumer that handles commands with a MessageData property?</p>

<p>I was going to use the In-memory transport, but it doesn't seem like the right approach since the unit test(s) will not receive immediate feedback from the consumer.  Ultimately the end goal is for my unit tests to be able assert that specific exceptions are thrown or that the consumer completed successfully without errors.</p>

<pre><code>using System;
using System.Linq;
using System.Threading.Tasks;
using MassTransit;
using MassTransit.MessageData;
using MassTransit.Testing;
using Newtonsoft.Json;
using Xunit;

namespace Test
{
    public class LargePayloadConsumerTest
    {
        [Fact]
        public async Task Consumer_Should_Deserialize_Message()
        {
            var harness = new InMemoryTestHarness();
            var consumer = harness.Consumer&lt;BigMessageConsumer&gt;();
            var command = new BigMessageCommand();
            var dataRepo = new InMemoryMessageDataRepository();

            var largePayload = new BigMessagePayload()
            {
                Id = 1,
                FirstName = ""TestFirstName"",
                MiddleName = ""TestMiddleName"",
                LastName = ""TestLastName""
            };


            var json = JsonConvert.SerializeObject(largePayload);
            command.Body = await dataRepo.PutString(json);

            var thisWorks = await command.Body.Value;
            await harness.Start();
            await harness.InputQueueSendEndpoint.Send(command);

            Assert.True(harness.Consumed.Select&lt;BigMessageCommand&gt;().Any());
        }

        public class BigMessageConsumer : IConsumer&lt;BigMessageCommand&gt;
        {
            public async Task Consume(ConsumeContext&lt;BigMessageCommand&gt; context)
            {
                try
                {
                    var json = await context.Message.Body.Value;
                    var deserialized = JsonConvert.DeserializeObject&lt;BigMessagePayload&gt;(json);
                    Console.WriteLine($""{deserialized.Id}: {deserialized.FirstName} {deserialized.MiddleName} {deserialized.LastName}"");
                }
                catch (Exception e)
                {
                    //throws {""The message data was not loaded: urn:msgdata:xxxxxxxxxxxxxxxxxxxxxxxxxx""}
                    Console.WriteLine(e);
                    throw;
                }
            }
        }

        public class BigMessageCommand
        {
            public MessageData&lt;string&gt; Body { get; set; }
        }

        public class BigMessagePayload
        {
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string MiddleName { get; set; }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/56193041/masstransit-unit-testing-a-large-payload-consumer,"['c#', 'masstransit']",835,True,0,1
Unit testing for a protected is failing,"<p>I have a class <code>EllaService</code> and I would like to test the <code>EllaService::isTrafficIgnored</code> method there. The code is provided below, </p>

<pre><code>@Service
public class EllaService {


    @Autowired
    @Qualifier( ELLA_CONNECTOR_BEAN_NAME )
    private EntityServiceConnectable&lt;EllaResponseDto&gt; connector;

    @Autowired
    @Getter
    private EllaFilterConfigHolder configHolder;

    @Autowired
    @Getter
    private EllaConfiguration config;

    @Autowired
    private Environment env;


    protected boolean isTrafficIgnored( IrisBo irisBo ) {

        if( config.isExternalCostumerFilter( this.env ) &amp;&amp; irisBo.getBuyer().isExternalKnownCustomer() ) {
            return true;
        }

        if( config.isInternalCostumerFilter( this.env ) &amp;&amp; irisBo.getBuyer().isInternalKnownCustomer() ) {
            return true;
        }

        return checkIfShopIdFilterIsApplied( irisBo );
    }

    // ========================================================================

    private boolean checkIfShopIdFilterIsApplied( IrisBo irisBo ) {
        return configHolder.getShopIdsToFilterSet().contains( irisBo.getOrder().getShopId() );
    }

    // ........................

}
</code></pre>

<p>I provided 2 tests for the method in the test class, </p>

<pre><code>@RunWith( PowerMockRunner.class )
@PrepareForTest( EllaDtoConverter.class )
public class EllaServiceTest {

    private static final String VALID_TRX_ID = ""valid-trx-id"";
    private static final String VALID_GW_ID = ""valid-gw-id"";

    @InjectMocks
    private EllaService ellaService;

    private IrisBo validIrisBo;

    @Mock
    private EllaRequestDto ellaRequestDto;

    @Mock
    private EntityServiceConnectable&lt;EllaResponseDto&gt; entityServiceConnector;

    @Mock
    private EllaResponseDto ellaResponseDto;

    @Mock
    private EllaConfiguration ellaConfiguration;

    @Mock
    private EllaFilterConfigHolder ellaFilterConfigHolder;

    @Mock
    private EllaService ellaServiceMock;

    @Mock
    private Environment environment;

    @SuppressWarnings( ""unchecked"" )
    @Before
    public void setup() {

        PowerMockito.mockStatic( EllaDtoConverter.class );
        when( EllaDtoConverter.convertToRequest( any() ) ).thenReturn( ellaRequestDto );

        ServiceResponse&lt;EllaResponseDto&gt; validServiceResponseMock = mock( ServiceResponse.class );
        when( entityServiceConnector.call( any(), (HttpHeaders) any() ) ).thenReturn( validServiceResponseMock );

        when( validServiceResponseMock.isSuccess() ).thenReturn( true );
        when( validServiceResponseMock.getResponse() ).thenReturn( ellaResponseDto );
        when( validServiceResponseMock.getErrorMessage() ).thenReturn( """" );

        when( ellaServiceMock.getConfigHolder() ).thenReturn( ellaFilterConfigHolder );
        when( ellaServiceMock.getConfig() ).thenReturn( ellaConfiguration );
        when( ellaConfiguration.isExternalCostumerFilter( any() ) ).thenReturn( false );
        when( ellaConfiguration.isInternalCostumerFilter( any() ) ).thenReturn( false );
        when( ellaConfiguration.extractShopIdsToFilter( any() ) ).thenReturn( """" );

        when( ellaFilterConfigHolder.getShopIdsToFilterSet() ).thenReturn( new HashSet&lt;&gt;() );

        validIrisBo = new IrisBo();

        RequestInformation requestInfo = Mockito.mock( RequestInformation.class );

        when( requestInfo.getTransactionId() ).thenReturn( VALID_TRX_ID );
        when( requestInfo.getGatewayRequestId() ).thenReturn( VALID_GW_ID );

        OrderBo orderBo = new OrderBo();

        orderBo.addProduct( INVOICE );
        orderBo.setShopId( 123 );

        AddressBo addressBo = new AddressBo();

        addressBo.setStreetName( ""Rutherfordstraße"" );
        addressBo.setHouseNumber( ""2"" );
        addressBo.setZipCode( ""12489"" );

        ServiceBo serviceBo = new ServiceBo();

        serviceBo.setDate( LocalDate.parse( ""2018-11-26"" ) );
        serviceBo.setExistingCustomer( Boolean.TRUE );

        TransactionBo transactionBo = new TransactionBo();

        transactionBo.setTrxId( ""valid-trx-id"" );
        transactionBo.setCurrencyCode( ""EUR"" );
        transactionBo.setAmount( 12.5 );

        BuyerBo buyerBo = new BuyerBo();

        buyerBo.setBillingAddress( addressBo );
        buyerBo.setDeliveryAddress( addressBo );

        validIrisBo.setRequestInfo( requestInfo );
        validIrisBo.setOrder( orderBo );
        validIrisBo.setBuyer( buyerBo );

        validIrisBo.getBuyer().setBillingAddress( addressBo );
        validIrisBo.getBuyer().setDeliveryAddress( addressBo );

        validIrisBo.setTrackingId( ""9241999998422820706039"" );
        validIrisBo.setEmail( ""test@ratepay.com"" );
        validIrisBo.setIp( ""123.120.12.12"" );
        validIrisBo.setFirstName( ""Max"" );
        validIrisBo.setLastName( ""Musterman"" );
    }



    @Test
    public void testIsTrafficIgnoredWhenExternalCostumerFilterReturnsTrueAndBuyerIsExternalKnownCustomer() {

        when( ellaConfiguration.isExternalCostumerFilter( environment ) ).thenReturn( true );
        validIrisBo.getBuyer().setExternalKnownCustomer( true );

        assertEquals( true, ellaService.isTrafficIgnored( validIrisBo ) );
    }

    @Test
    public void testIsTrafficIgnoredWhenInternalCostumerFilterReturnsTrueAndBuyerIsInternalKnownCustomer() {

        when( ellaConfiguration.isInternalCostumerFilter( environment ) ).thenReturn( true );
        validIrisBo.getBuyer().setInternalKnownCustomer( true );

        assertEquals( true, ellaService.isTrafficIgnored( validIrisBo ) );
    }


}
</code></pre>

<p>Now, I would like to test </p>

<p>a. if the condition </p>

<pre><code>if( config.isExternalCostumerFilter( this.env ) &amp;&amp; irisBo.getBuyer().isExternalKnownCustomer() ) 
</code></pre>

<p>is false </p>

<p>b. the condition </p>

<pre><code>if( config.isInternalCostumerFilter( this.env ) &amp;&amp; irisBo.getBuyer().isInternalKnownCustomer() )
</code></pre>

<p>is <code>false</code></p>

<p>c. the </p>

<pre><code>checkIfShopIdFilterIsApplied( irisBo ) 
</code></pre>

<p>returns <code>true</code></p>

<p>Then the <code>isTrafficIgnored</code> will also return <code>true</code>. </p>

<p>My test method is provided below, </p>

<pre><code>@Test
    public void testIsTrafficIgnoredWhenAllOtherConditionsAreFalseButCheckIfShopIdFilterIsAppliedReturnsTrue() throws Exception {

        when( ellaConfiguration.isExternalCostumerFilter( environment ) ).thenReturn( false );
        when( ellaConfiguration.isInternalCostumerFilter( environment ) ).thenReturn( false );

        PowerMockito.when( ellaServiceMock, ""checkIfShopIdFilterIsApplied"", validIrisBo ).thenReturn( true );

        assertTrue( ellaService.isTrafficIgnored( validIrisBo ) );
    }
</code></pre>

<p>I get <code>NullPointerException</code> exception provided below, </p>

<pre><code>java.lang.NullPointerException
    at com.ratepay.iris.ella.service.EllaService.checkIfShopIdFilterIsApplied(EllaService.java:118)
</code></pre>

<p>I updated the test method provided, </p>

<pre><code>    @Test
    public void testIsTrafficIgnoredWhenAllOtherConditionsAreFalseButCheckIfShopIdFilterIsAppliedReturnsTrue() throws Exception {

        EllaFilterConfigHolder e = spy( new EllaFilterConfigHolder() );

        doReturn( true ).when( e.getShopIdsToFilterSet().contains( validIrisBo.getOrder().getShopId() ) );

        when( ellaConfiguration.isExternalCostumerFilter( environment ) ).thenReturn( false );
        when( ellaConfiguration.isInternalCostumerFilter( environment ) ).thenReturn( false );

        PowerMockito.when( ellaServiceMock, ""checkIfShopIdFilterIsApplied"", validIrisBo ).thenReturn( true );

        assertTrue( ellaService.isTrafficIgnored( validIrisBo ) );
    }
</code></pre>

<p>I get the error stack provided, </p>

<pre><code>org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-&gt; at com.ratepay.iris.ella.service.EllaServiceTest.testIsTrafficIgnoredWhenAllOtherConditionsAreFalseButCheckIfShopIdFilterIsAppliedReturnsTrue(EllaServiceTest.java:216)

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.ratepay.iris.ella.service.EllaServiceTest.testIsTrafficIgnoredWhenAllOtherConditionsAreFalseButCheckIfShopIdFilterIsAppliedReturnsTrue(EllaServiceTest.java:216)
    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)
</code></pre>

<p>How do I correct my test?</p>

<p><em>Update</em></p>

<p>I have the feelings that my question is not clear. I would like to know how do I mock the statement <code>checkIfShopIdFilterIsApplied( irisBo )</code> to return <code>true</code>?</p>
",https://stackoverflow.com/questions/56492376/unit-testing-for-a-protected-is-failing,"['java', 'junit', 'mockito', 'powermock']",47,True,0,1
Moq MongoDB UpdateOneAsync method for unit testing,"<p>I  want to moq update method that is using mongodbContext. here is what i am trying to do but its not working. how to pass UpdateResult return type <code>.ReturnsAsync&lt;UpdateResult&gt;()</code>. I am very new to Mongodb database Unit Testing with .net core.</p>

<pre><code> public void UpdateEventAsync_Test()
        {
            //Arrange
            var eventRepository = EventRepository();
            var pEvent = new PlanEvent
            {
                ID = ""testEvent"",
                WorkOrderID = ""WorkOrderID"",
                IsDeleted = false,
                IsActive = true,
                EquipmentID = ""EquipmentID""
            };
            ////Act

            mockEventContext.Setup(s =&gt; s.PlanEvent.UpdateOneAsync(It.IsAny&lt;FilterDefinition&lt;PlanEvent&gt;&gt;(), It.IsAny&lt;UpdateDefinition&lt;Model.EventDataModel.PlanEvent&gt;&gt;(), It.IsAny&lt;UpdateOptions&gt;(), It.IsAny&lt;System.Threading.CancellationToken&gt;())).ReturnsAsync&lt;UpdateResult&gt;();
            var result = eventRepository.UpdateEventAsync(pEvent);
            ////Assert
            result.Should().NotBeNull();
            Assert.AreEqual(true, result);

        }
</code></pre>

<p>below is the code for which i want to write Moq Test</p>

<pre><code>   public async Task&lt;bool&gt; UpdateEventAsync(Model.EventDataModel.PlanEvent eventobj)
    {
        var filter = Builders&lt;Model.EventDataModel.PlanEvent&gt;.Filter.Where(f =&gt; f.ID == eventobj.ID);

        // TO Do: Use replace instead of update.
        var updatestatement = Builders&lt;Model.EventDataModel.PlanEvent&gt;.Update.Set(s =&gt; s.IsDeleted, eventobj.IsDeleted)
            .Set(s =&gt; s.EquipmentID, eventobj.EquipmentID)
            .Set(s =&gt; s.PlannedStartDateTime, eventobj.PlannedStartDateTime)
            .Set(s =&gt; s.PlannedEndDatetime, eventobj.PlannedEndDatetime)
            .Set(s =&gt; s.WorkOrderID, eventobj.WorkOrderID)
            .Set(s =&gt; s.ResourceID, eventobj.ResourceID)
            .Set(s =&gt; s.LastUpdatedBy, eventobj.LastUpdatedBy)
            .Set(s =&gt; s.EventComment, eventobj.EventComment)
            .Set(s =&gt; s.SiteID, eventobj.SiteID)
            .Set(s =&gt; s.LastUpdatedDateTime, DateTime.UtcNow.ToString());

        UpdateResult updateResult = await _eventContext.PlanEvent.UpdateOneAsync(filter, updatestatement);
        return updateResult != null &amp;&amp; updateResult.IsAcknowledged &amp;&amp; updateResult.ModifiedCount &gt; 0;
    } 
</code></pre>
",https://stackoverflow.com/questions/54636283/moq-mongodb-updateoneasync-method-for-unit-testing,"['mongodb', 'unit-testing', '.net-core']",2300,True,0,1
Unit testing for spring boot RESTFUL Controller,"<p>I am trying to do unit testing for spring boot RESTFUL controller but I am receiving a null pointer exception. The application has a <code>StudentController</code> which depends on a <code>StudentService</code>. 
Here is the controller code: </p>

<pre><code>package com.demo.student.demo.controller;

import com.demo.student.demo.annotation.ApiDescription;
import com.demo.student.demo.entity.Student;
import com.demo.student.demo.entity.StudentDto;
import com.demo.student.demo.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = ""/v1/students"")
@Api(description = ""This is a general description for StudentController RESTFUL Controller"")
public class StudentController {

    private StudentService studentService;
    private ModelMapper modelMapper;

    public StudentController(ModelMapper modelMapper, StudentService studentService){
        this.studentService = studentService;
        this.modelMapper = modelMapper;
    }

    private StudentDto convertToDto(Student student) {
        StudentDto studentDto = modelMapper.map(student, StudentDto.class);
        return studentDto;
    }

    private Student convertToEntity(StudentDto studentDto) {
        Student student = modelMapper.map(studentDto, Student.class);
        return student;
    }

    @GetMapping
    @ApiOperation(""Returns a list of all students in the system."")
    @ApiDescription(""FIND_ALL_STUDENTS.md"")
    public List&lt;StudentDto&gt; findAll(){
        List&lt;Student&gt; students = studentService.findAl();
        return students.stream()
                .map(student -&gt; convertToDto(student))
                .collect(Collectors.toList());
    }

    @GetMapping(""/{id}"")
    @ApiOperation(""Returns a specific Student by his/her identifier. 404 if does not exist."")
    @ApiDescription(""FIND_STUDENT_BY_ID.md"")
    public StudentDto findById(@PathVariable(""id"") long id){
        return convertToDto(studentService.findById(id));
    }

    @PostMapping
    @ApiOperation(""Creates/Updates a new Student."")
    @ApiDescription(""SAVE_OR_UPDATE_STUDENT.md"")
    public StudentDto saveOrUpdate(@RequestBody StudentDto studentDto) {
        Student student = convertToEntity(studentDto);
        student.setUsername(student.getEmail() + ""----"" + student.getId());
        Student studentCreated = studentService.saveOrUpdate(student);
        return convertToDto(studentCreated);
    }

    @DeleteMapping(""/{id}"")
    @ApiOperation(""Deletes a Student from the system. 404 if the Student's identifier is not found."")
    @ApiDescription(""DELETE_STUDENT_BY_ID.md"")
    public void deleteById(@PathVariable(""id"") long id){
        studentService.deleteById(id);
    }

}
</code></pre>

<p>And here is the service implementation code: </p>

<pre><code>package com.demo.student.demo.service;

import com.demo.student.demo.entity.Student;
import com.demo.student.demo.exception.StudentNotFoundException;
import com.demo.student.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class StudentServiceImpl implements StudentService {

    private StudentRepository studentRepository;

    @Autowired
    public StudentServiceImpl(StudentRepository studentRepository){
        this.studentRepository = studentRepository;
    }

    @Override
    public List&lt;Student&gt; findAl() {
        return studentRepository.findAll();
    }

    @Override
    public Student findById(long id) {
        return  studentRepository.findById(id).orElseThrow(() -&gt; new StudentNotFoundException(id));
    }

    @Override
    public Student saveOrUpdate(Student student) {
        studentRepository.save(student);
        return student;
    }

    @Override
    public void deleteById(long id) {
        if(this.findById(id) != null)
            studentRepository.deleteById(id);
    }

}
</code></pre>

<p>And this is the test class for the controller: </p>

<pre><code>package com.demo.student.demo.controller;

import com.demo.student.demo.entity.Student;
import com.demo.student.demo.service.StudentService;
import com.demo.student.demo.service.StudentServiceImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
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 java.util.Arrays;
import java.util.List;

import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(StudentController.class)
class StudentControllerTest {

    private final static String URI = ""/v1/students"";

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private StudentService studentService;

    @Test
    void findAll() throws Exception {    
        // given
        Student student = new Student(1, ""test"", ""test@test.test"");
        List&lt;Student&gt; students = Arrays.asList(student);
        given(studentService.findAl()).willReturn(students);

        // when + then
        mockMvc.perform(get(URI))
                .andExpect(status().isOk())
                .andExpect(content().json(""[{'id':1,'email':'test@test.test'}]""));
    }

}
</code></pre>

<p>Here is also the pom.xml:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://maven.apache.org/POM/4.0.0""
         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.0.5.RELEASE&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
    &lt;groupId&gt;com.demo.student&lt;/groupId&gt;
    &lt;artifactId&gt;demo&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;name&gt;demo&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-actuator&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.h2database&lt;/groupId&gt;
            &lt;artifactId&gt;h2&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.postgresql&lt;/groupId&gt;
            &lt;artifactId&gt;postgresql&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&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.modelmapper/modelmapper --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.modelmapper&lt;/groupId&gt;
            &lt;artifactId&gt;modelmapper&lt;/artifactId&gt;
            &lt;version&gt;0.7.5&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.plugin&lt;/groupId&gt;
            &lt;artifactId&gt;spring-plugin-core&lt;/artifactId&gt;
            &lt;version&gt;1.2.0.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.springfox&lt;/groupId&gt;
            &lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt;
            &lt;version&gt;2.8.0&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.springfox&lt;/groupId&gt;
            &lt;artifactId&gt;springfox-swagger-ui&lt;/artifactId&gt;
            &lt;version&gt;2.8.0&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.springfox&lt;/groupId&gt;
            &lt;artifactId&gt;springfox-bean-validators&lt;/artifactId&gt;
            &lt;version&gt;2.8.0&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;javax.xml&lt;/groupId&gt;
            &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt;
            &lt;version&gt;2.1&lt;/version&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;dependency&gt;
            &lt;groupId&gt;org.javassist&lt;/groupId&gt;
            &lt;artifactId&gt;javassist&lt;/artifactId&gt;
            &lt;version&gt;3.25.0-GA&lt;/version&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.22.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.skyscreamer&lt;/groupId&gt;
            &lt;artifactId&gt;jsonassert&lt;/artifactId&gt;
            &lt;version&gt;1.5.0&lt;/version&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>When I run the test I receive a NULL POINTER EXCEPTION pointing to a code line in the <code>StudentController</code> class where the student service retrieves all the student data: <code>List&lt;Student&gt; students = studentService.findAl();</code></p>

<pre><code>java.lang.NullPointerException: null
    at com.demo.student.demo.controller.StudentController.findAll
</code></pre>

<p>Can anyone tell me what is the problem?</p>
",https://stackoverflow.com/questions/59051719/unit-testing-for-spring-boot-restful-controller,"['java', 'spring-boot', 'unit-testing', 'mockito', 'mockmvc']",1224,False,0,3
Unit testing involving hardware communication worth it?,"<p>I am developing a C# application that involves communication with hardware devices such as an NFC reader and Spectrometer. We have the hardware already and I am not sure if it is still worth the time converting the hardware into mock classes. I am thinking of testing the software functions together with the hardware device. </p>

<p>Is there still any benefit conducting unit tests without hardware? Currently i do not have the interfaces for the different hardware classes. It would seem to require some work to properly configure the hardware interface classes. </p>

<p>I am using DLLImports for the hardware communication. I’m not sure if im able to simulate these dll calls using a fake class as well ? </p>
",https://stackoverflow.com/questions/56900006/unit-testing-involving-hardware-communication-worth-it,"['c#', 'unit-testing', 'embedded']",277,True,0,1
Unit testing involving hardware communication worth it?,"<p>I am developing a C# application that involves communication with hardware devices such as an NFC reader and Spectrometer. We have the hardware already and I am not sure if it is still worth the time converting the hardware into mock classes. I am thinking of testing the software functions together with the hardware device. </p>

<p>Is there still any benefit conducting unit tests without hardware? Currently i do not have the interfaces for the different hardware classes. It would seem to require some work to properly configure the hardware interface classes. </p>

<p>I am using DLLImports for the hardware communication. I’m not sure if im able to simulate these dll calls using a fake class as well ? </p>
",https://stackoverflow.com/questions/56900006/unit-testing-involving-hardware-communication-worth-it,"['c#', 'unit-testing', 'embedded']",277,True,0,1
Unit testing a function with a timestamp,"<p>I have an object function to send <strong>news</strong> to an <strong>API</strong>:</p>

<pre><code>class Manager
{
    public function __construct(GuzzleHttp\Client $client)
    {
        $this-&gt;client = $client;
    }


    public function uploadNews($title, $text, $timestamp = null)
    {
        // DEFAULT FOR PUBLISH TIMESTAMP IS SET IF VALUE IS NULL
        $timestamp = $timestamp ?? time();

        $requestBody = [
            'header' =&gt; [
                'Accept' =&gt; 'application/json',
            ],
            'timeout' =&gt; 300,
            'body' =&gt; [
                'title' =&gt; $title,
                'text' =&gt; $text,
                'publish_date' =&gt; $timestamp,
            ]
        ];

        return $this-&gt;client-&gt;request('POST', 'http://api/endpoint', $requestBody);
    }
}
</code></pre>

<p>How do I write a PHPUnit unit test to test the final <code>$request</code> passed to the client's <code>request()</code> function is of the expected format, when the <code>$timestamp</code> is not set (the API expects a timestamp)? I've written a unit test. But is not ideal, since there could be a difference in the tow timestamps.</p>

<pre><code>class ManagerTest extends \PHPUnit\Framework\TestCase
{
    public function testCanUploadNewsWithoutTimestamp()
    {
        $expectedRequestBody = [
            'header' =&gt; [
                'Accept' =&gt; 'application/json',
            ],
            'timeout' =&gt; 300,
            'body' =&gt; [
                'title' =&gt; 'News title',
                'text' =&gt; 'News article sample text.',
                'publish_date' =&gt; time(),
            ]
        ];

        $guzzleMock = $this-&gt;createMock(GuzzleHttp\Client::class);
        $guzzleMock-&gt;expects($this-&gt;once())
            -&gt;method('request')
            -&gt;with(
                'POST',
                'http://api/endpoint',
                $expectedRequestBody
            );

        (new Manager($guzzleMock))-&gt;uploadNews(
            'News title',
            'News article sample text.'
        );
    }
}
</code></pre>

<p>This is my current test result:</p>

<pre><code>Parameter 2 for invocation GuzzleHttp\Client::request('POST', 'http://api/endpoint', Array (...)) does not match expected value.
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
     'body' =&gt; Array (
         'title' =&gt; 'News title'
         'text' =&gt; 'News article sample text.'
-        'publish_date' =&gt; 1574550178
+        'publish_date' =&gt; 1574550179
     )
 )
</code></pre>

<p><strong>Please note that the only thing I need to make sure is that the timestamp is passed with request. The value of the timestamp doesn't matter.</strong></p>

<p>PS: I'm really new to Test Driven Development, so the answer might be obvious and I might still not know it.</p>
",https://stackoverflow.com/questions/59013132/unit-testing-a-function-with-a-timestamp,"['php', 'unit-testing', 'testing', 'phpunit']",675,False,0,0
How to do Unit testing using Junit4?,"<p>I had created a JWTCreateImpl class given below to generate a jwt token using generatToken() method and respond a jwt string using loginUser() method. loginUser() method takes email and password as a parameter coming from frontend. This email is compare with email exist in database and if email is not present the errorResponse will become ""email not exist"" similarly do for password doesn't match. And lastly if email and password exist for a particular id then extracting the result from database and pass only uuid of user to generate a token and response will be jwt string. I want to perform unit testing for this class using Junit4, how can I write the test case using Junit4 for this?</p>

<p>JWTCreateImpl class Implements JWTCreate Interface which Contains abstract Methods loginUser(UserInfoJWT userInfoJWT) and generateToken(UUID uuid) and one String JWT_TOKEN_KEY which is used in generateToken() method mainly use with HMAC256 Algorithm. UserInfoJWT is a POJO class Which contains email and password of user.</p>

<p>ResponseJWT is a POJO class  which contains UserToken and errorResponse.</p>

<pre><code>import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.knoldus.magad.jwt.api.JWTCreate;
import com.knoldus.magad.jwt.model.ResponseJWT;
import com.knoldus.magad.jwt.model.UserInfoJWT;
import com.knoldus.magad.dao.model.UserInfo;
import com.knoldus.magad.user.api.UserInfoProcessingAPI;

import org.apache.log4j.Logger;


import java.io.UnsupportedEncodingException;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class JWTCreateImpl implements JWTCreate {
private static final Logger LOGGER = Logger.getLogger(JWTCreateImpl.class);
private UserInfo existingUser;
private ResponseJWT response;
private  UserInfoProcessingAPI userInfoProcessingAPI;
private static final String NO_USER_EMAIL = ""Email doesn't exists.."";
private static  final String LOGIN_UNSUCCESSFUL = ""Wrong Password"";


@Override
public CompletableFuture&lt;String&gt;loginUser(final UserInfoJWT userInfoJWT) {
    return userInfoProcessingAPI.getUserInfo(userInfoJWT.getUserEmail()).thenApply(result -&gt; {
        existingUser = result.orElse(null);
        if (existingUser == null) {
            response = ResponseJWT.builder().errorResponse(NO_USER_EMAIL).build();
        } else {
            final String dataBasePassword = existingUser.getUserPassword();
            if (userInfoJWT.getUserPassword().equals(dataBasePassword)) {
                response = ResponseJWT.builder().userToken(generateToken(existingUser.getUuid())).build();
            } else {
                response = ResponseJWT.builder().errorResponse(LOGIN_UNSUCCESSFUL).build();
            }
        }
        return response.toString();
    });
}
@Override
public String generateToken(final UUID uuid) {
    try {
        final Algorithm algorithm = Algorithm.HMAC256(JWT_TOKEN_KEY);
        final Date expirationDate = Date.from(ZonedDateTime.now().plusHours(24).toInstant());
        final Date issuedAt = Date.from(ZonedDateTime.now().toInstant());
        final String id = String.valueOf(uuid);
        final String issuer = ""MagADAuth"";
        return JWT.create()
                .withIssuedAt(issuedAt) // Issue date.
                .withExpiresAt(expirationDate) // Expiration date.
                .withClaim(""userId"", id)
                .withIssuer(issuer) // Issuer of the token.
                .sign(algorithm); // And the signing algorithm.
    } catch (UnsupportedEncodingException | JWTCreationException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
</code></pre>
",https://stackoverflow.com/questions/57335875/how-to-do-unit-testing-using-junit4,"['java', 'jwt', 'junit4']",191,True,0,1
How to do unit testing with AVA?,"<p>I'm doing a website booking of coffee-shop for my studies, and I need to do unit test for the front and the back. 
For the front I'm doing test with AVA but I NEVER doing test in my life and I don't know what I need to do. My final examination is Thursday and I need to do fast my units. </p>

<p>Where do I start?</p>
",https://stackoverflow.com/questions/57768755/how-to-do-unit-testing-with-ava,"['nuxt.js', 'ava']",82,False,-3,1
StencilJS Unit Testing using Jest throwing error,"<p>Jest unit test case for listening <code>click</code> event emitted from child is throwing error </p>

<pre><code>expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: &gt;= 1
Received number of calls:    0
</code></pre>

<p>// .spec.ts code</p>

<pre class=""lang-js prettyprint-override""><code>import { newSpecPage } from '@stencil/core/testing';
import { MyComponent } from './my-component';
import { MyEmbeddedComponent } from './my-embedded-component';

describe('click event', () =&gt; {
  let page;
  beforeEach(async () =&gt; {
    page = await newSpecPage({
      components: [MyComponent, MyEmbeddedComponent],
      html: '&lt;my-component color=""green""&gt;&lt;/my-component&gt;'
    });
  });

  it('should emit click event', async () =&gt; {
    let callbackFn = jest.fn();

    page.doc.addEventListener('clickCompleted', callbackFn);
    const button = page.root.shadowRoot.querySelector('button');
    await button.dispatchEvent(new Event('clickCompleted'));
    await page.waitForChanges();
    expect(callbackFn).toHaveBeenCalled();
  });
});
</code></pre>

<p>// my-embedded-component.ts</p>

<pre class=""lang-js prettyprint-override""><code>import { Component, Prop, h, Event, EventEmitter } from '@stencil/core';

@Component({
  tag: 'my-embedded-component'
})
export class MyEmbeddedComponent {
  @Prop() color: string;

  @Event() clickCompleted: EventEmitter;
  handleClickCompleted() {
    console.log('Emitting clickCompleted event');
    this.clickCompleted.emit(4);
  }

  render() {
    return &lt;button onClick={this.handleClickCompleted.bind(this)}&gt;I'm a child&lt;/button&gt;;
  }
}
</code></pre>

<p>// my-component.tsx</p>

<pre class=""lang-js prettyprint-override""><code>import { Component, h, Listen } from '@stencil/core';

@Component({
  tag: 'my-component',
  styleUrl: 'my-component.css',
  shadow: true
})
export class MyComponent {
  @Listen('clickCompleted')
  listenClickCompleted(e: CustomEvent) {
    console.log('Listening listenClickCompleted ', e.detail);
  }

  render() {
    return (
      &lt;div class=""hello""&gt;
        &lt;my-embedded-component color=""green""&gt;&lt;/my-embedded-component&gt;
      &lt;/div&gt;
    );
  }
}

</code></pre>
",https://stackoverflow.com/questions/58282248/stenciljs-unit-testing-using-jest-throwing-error,"['jestjs', 'stenciljs']",1756,True,0,1
Unit Testing ServiceBus.Message. How to set value for SystemProperties.LockToken?,"<p>I want to test a message handler callback that I have registered with a QueueClient using <code>queueClient.RegisterMessageHandler(MyCallBack, messageHandlerOptions)</code>.</p>

<pre><code>public Task MyCallBack(Message msg, CancellationToken token)
{
   // Read msg. Do something

   // Since everything ran fine, complete the msg.
   await _client.CompleteAsync(msg.SystemProperties.LockToken);
}
</code></pre>

<p>Now as part of my unit test I call <code>MyCallBack</code>. Since I pass a <em>valid</em> message. I expect <code>client.CompleteAsync()</code> to be called. However the test throws an exception.</p>

<pre><code>System.InvalidOperationException: Operation is not valid due to the current state of the object.
</code></pre>

<p>This is because <code>msg.SystemProperties.LockToken</code> is <strong>not</strong> set (which is because message was not <em>actually</em> read from a queue by a client with <code>ReceiveMode.PeekLock</code> mode).</p>

<p>Is there a way to set/mock this so that I can run my tests with a dummy string as a token?</p>

<p><br>
PS: I know I can check for <code>msg.SystemProperties.IsLockTokenSet</code> before actually accessing the LockToken field; but even in that case I will never be able to unit test if <code>_client.CompleteAsync()</code> was called.</p>
",https://stackoverflow.com/questions/56275725/unit-testing-servicebus-message-how-to-set-value-for-systemproperties-locktoken,"['c#', 'azureservicebus', 'azure-servicebus-queues']",7143,True,13,2
Local-Dynamodb unit testing; GSI not updating,"<p>I have a test case which seems flaky; 
Following is a workflow I am following and currently observed only on <code>amazon/local-dynamodb</code> as available on dockerhub</p>

<p>-- Create a table with 8 secondary indexes
-- In one step add 2 entries as such </p>

<pre><code>[{""id"": 1, ""status"": ""INCOMPLETE"", ""team"": ""A""},
 {""id"": 2, ""status"":""INCOMPLETE"", ""team"": ""B""}]
</code></pre>

<p>-- In step 2 add / update as follows</p>

<pre><code>[{""id"": 1, ""status"": ""DONE"", ""team"": ""C""},
 {""id"": 2, ""status"":""INCOMPLETE"", ""team"": ""B""}, 
 {""id"": 3, ""status"":""INCOMPLETE"", ""team"": ""A""}]
</code></pre>

<p>In the test I am checking that count of done: this works correctly  --uses a GSI</p>

<p>In second assert I am checking count of team ""A""; this comes out to 2!!! --uses another GSI</p>

<p>This test is becoming flaky; every time a new table is created in local-dynamodb (available on docker-hub) and then queried. It runs most of the times and fails some times after the second assert; 
The table GSI never gets updated. </p>
",https://stackoverflow.com/questions/56072925/local-dynamodb-unit-testing-gsi-not-updating,"['docker', 'amazon-dynamodb']",336,False,0,0
Angular Unit Testing with karma and jamis,"<p>I have set up my Angularjs application for unit testing with Karma and Jasmin. but when I try to run my test cases with <code>karma start</code> I am getting the error The controller with the name <code>Myctrl</code> is not registered.</p>

<p>My application structure is as follows</p>

<pre><code>project-folder
  - app
    - components
      - controllers
        - account
          - signInController.js
          - SignUpController.js
  - app.modules.js
  - app.routes.js
  - test
</code></pre>

<p>This is my app.modules.js</p>

<pre><code>let app = angular.module( 'app', [
  'app.config', 'templates', 'ngAnimate', 'ngAria', 'ngCookies', 'ngMessages', 'ngResource', 'ngSanitize',
  'ngTouch', 'ui.router', 'ui.bootstrap', 'ui.utils', 'ui.load', 'ui.jq', 'oc.lazyLoad','angular-cache',
  'ngToast', 'ngFileUpload', 'ngFileSaver', 'angularMoment', 'angulartics', 'angulartics.google.analytics',
  'ngMessages', 'ng.httpLoader'
]);
</code></pre>

<p>And the karma.config.js file</p>

<pre><code>module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'browserify'],

    // list of files / patterns to load in the browser
    files: [
      'dist/libs/jquery/jquery.js',
      'dist/libs/angular/angular.js',
      'dist/libs/angular-ui-router/angular-ui-router.js',
      'dist/libs/angular-sanitize/angular-sanitize.js',
      'dist/libs/angular-mocks/angular-mocks.js',
      'dist/libs/angular-bootstrap/ui-bootstrap-tpls.js',
      'app/app.modules.js',
      'app/app.routes.js',
      'app/config.lazyload.js',
      'app/components/controllers/account/*.js',
      'test/**/*spec.js',
      ],
      . 
      .
</code></pre>

<pre><code>describe('Myctrl Test', function() {

  describe('Myctrl', function() {
    var vm;

    beforeEach(inject(function( ) {
      angular.module('app')
    }));

    beforeEach(inject(function(_$rootScope_, $controller) {
      var scope = _$rootScope_.$new();
      vm = $controller('Myctrl', {$scope: scope});
    }));

    it('test controller', function() {
      expect(vm.title).toBe(null);
    });

  });

});
</code></pre>

<pre><code>app.controller( 'Myctrl', ['$scope', '$state', 'backendApi', 'ngToast', 'access_token', 'FileUploader', 'keys',
function( $scope, $state, backendApi, ngToast, access_token, FileUploader, keys ) {

  $scope.title = ""Hello"";


}])
</code></pre>
",https://stackoverflow.com/questions/54568235/angular-unit-testing-with-karma-and-jamis,"['angularjs', 'karma-jasmine']",148,False,0,1
await application before exporting for unit testing?,"<p>I'm attempting to use Jest to unit test an express API I've been working on however the database has to be ready before it runs the test. This does not seem to be happening however. I have a server.ts file which contains:</p>

<pre><code>import App from './app';
import UsersController from './controllers/users.controller';

const app = new App();

app.initialize(
  [
    new UsersController(),
  ]
);

if (process.env.NODE_ENV !== 'test') {
  app.listen();
}

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

<p><code>app.initialize</code> is an aysnc function which configures the database and routes my controllers.</p>

<p>In my unit test I then have the following</p>

<pre><code>import server from ""../server"";
import supertest from 'supertest';

const request = supertest(server.app);

it('should allow users to register', async () =&gt; {
    // Arrange
    const user = {
      firstName: 'John',
      lastName: 'Smith',
      age: 42
    };

    return request.post('/api/users')
      .send(user)
      .set('Accept', 'application/json')
      .then(response =&gt; {
        expect(response).toEqual(user.firstName)
        expect(response.body.lastName).toEqual(user.lastName)
        expect(response.body.id).toBeGreaterThan(0)
    });
});
</code></pre>

<p>This however falls over with a 404 error, however if I remove the NODE_ENV check on ""test"" in the server file I can see that app.listen() get's called well after my test so I believe it's safe to assume that the tests are running before that file has finished.</p>

<p>For completeness here is my App class:</p>

<pre><code>import ""reflect-metadata"";
import express from 'express';
import * as bodyParser from 'body-parser';
import {createConnection} from ""typeorm"";
import IController from './controllers/baseController.interface';

class App {
  public app = express();
  public port: number = 8080;
  public ready: boolean = false;

  public async initialize(controllers : [IController]) {
    await createConnection().then(async connection =&gt; {
      connection.synchronize();
      this.initializeMiddlewares();
      this.initializeControllers(controllers);
    });
  }

  private initializeMiddlewares() {
    this.app.use(bodyParser.json());
  }

  private initializeControllers(controllers : [IController]) {
    controllers.forEach((controller) =&gt; {
      this.app.use('/api/', controller.router);
    });
  }

  public listen() {
    this.app.listen(this.port, () =&gt; {
      console.log(`App listening on the port ${this.port}`);      
    });
  }
}

export default App;
</code></pre>
",https://stackoverflow.com/questions/59361393/await-application-before-exporting-for-unit-testing,"['javascript', 'node.js', 'typescript', 'express', 'ecmascript-6']",212,True,0,1
Unit testing when generic type is needed,"<p>I have the following problem. I want to test a generic class MyClass&lt;'T>. However, I don't really care about the type being used for T.
However, when I create an instance of MyClass in the test, I need to specify what T is supposed to be.
I can do it like that: </p>

<pre><code>var sut = new MyClass&lt;Object&gt;();
</code></pre>

<p>It works of course, however, I don't like to put Object specifically, because it suggests to someone reading this test that maybe Object type is somehow significant here.</p>

<p>I like the approach used by AutoFixture where each value is created using <code>fixture.Create&lt;T&gt;()</code>, because it shows the reader that the value is not really important. Example of that:</p>

<pre><code>[Fact]
public void IntroductoryTest()
{
    // Arrange
    Fixture fixture = new Fixture();

    int expectedNumber = fixture.Create&lt;int&gt;();
    MyClass sut = fixture.Create&lt;MyClass&gt;();
    // Act
    int result = sut.Echo(expectedNumber);
    // Assert
    Assert.Equal(expectedNumber, result);
}
</code></pre>

<p>In the code above we don't care about the number, so we use AutoFixture as an abstraction about the fact that some number is needed.</p>

<p>Is there a solution like that, but in regard to types being used with generic classes?</p>

<p>Something like: <code>var sut = MyClass&lt;fixture.GenericType&gt;();</code>
I don't care here what is the actual type. To explain my use-case a bit more: I have AutoFac module that is used to register MyClass. In my test I just want to test if the module registers MyClass properly. For that registration I don't want to specify some exact type to be used for MyClass. It can be any.</p>
",https://stackoverflow.com/questions/54573716/unit-testing-when-generic-type-is-needed,"['c#', 'unit-testing', 'generics', 'autofixture']",507,True,0,2
Log and Unit testing in Kotlin Android,"<p>I am fairly new to android-x and using Room for the first time.  This seems like it should be dead simple.  yet I am having some issues with my setup and test.</p>

<p>I have a Unit Test that is failing</p>

<p>Error:
java.lang.AssertionError: </p>

<p>Expected :1</p>

<p>Actual   :null</p>

<p>I hope someone is able to assist.  not sure what else to add (SO requires me to add more content to post this lol). So hopefully someone can see where I am going wrong.</p>

<pre><code>class LogTest {
    //setup db
    private lateinit var logDao: LogDao
    private lateinit var testAppDatabase: AppDatabase

    @Before
    fun setUp() {
        val context = ApplicationProvider.getApplicationContext&lt;Context&gt;()
        testAppDatabase = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).allowMainThreadQueries().build()
        logDao = testAppDatabase.getLogDao()
    }

    @After
    @Throws(IOException::class)
    fun closeDb() {
        testAppDatabase.close()
    }

    @Test
    @Throws(Exception::class)
    fun `log Database is Empty on Start`() {
        assertEquals(null, logDao.getAllLogs().value?.size)

        val testLog = LogModel(""Test"", ""Test"", 0, 0, 0.0, 0.0)
        logDao.insertAll(testLog)
        assertEquals(1, logDao.getAllLogs().value?.size)
    }
}

@Entity(tableName = ""Logs"")
data class LogModel (
    @ColumnInfo(name = ""tag"") var tag: String,
    @ColumnInfo(name = ""msg"") var msg: String,
    @ColumnInfo(name = ""device_id"") var deviceID: Int,
    @ColumnInfo(name = ""user_id"") var userID: Int,
    @ColumnInfo(name = ""latitude"") var latitude: Double,
    @ColumnInfo(name = ""longitude"") var longitude: Double
) {
    @PrimaryKey(autoGenerate = true) var id: Long? = null
    //@ColumnInfo(name = ""timestamp"") var timestamp: String? = null
}


@Dao
interface LogDao {
    @Query(""SELECT * FROM Logs"")
    fun getAllLogs(): LiveData&lt;List&lt;LogModel&gt;&gt;

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(vararg logs: LogModel)
}


@Database(entities = [LogModel::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    //Database to be initialised here
    abstract fun getLogDao(): LogDao

    companion object {
        @Volatile
        private var INSTANCE: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase {
            val tempInstance = INSTANCE
            if (tempInstance != null) {
                return tempInstance
            }
            synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    ""My_Database""
                ).build()
                INSTANCE = instance
                return instance
            }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/54833920/log-and-unit-testing-in-kotlin-android,"['android', 'unit-testing', 'testing']",1867,False,0,1
Angular Unit Testing: Using Generics to Create Component,"<p>I am trying to create a generic wrapper around <code>TestBed.createComponent</code>, which takes a type argument and creates the component for that type. However, the <code>TestBed.createComponent</code> function takes an argument of type <code>Type&lt;T&gt;</code>. I'm unable to create a <code>Type&lt;T&gt;</code> from the passed in generic T argument.</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>export function createTestHarness&lt;T&gt;(): TestHarness&lt;T&gt; {
  let component: T;
  let fixture: ComponentFixture&lt;T&gt;;

  fixture = TestBed.createComponent&lt;T&gt;(**PROBLEM AREA**);
  component = fixture.componentInstance;
  fixture.detectChanges();

  return new TestHarness&lt;T&gt;(component, fixture);
}</code></pre>
</div>
</div>
</p>

<p>Is there a way to derive a <code>Type&lt;T&gt;</code> from the type passed in?</p>
",https://stackoverflow.com/questions/56062777/angular-unit-testing-using-generics-to-create-component,"['angular', 'typescript', 'unit-testing', 'typescript-generics']",2659,True,5,2
Unit testing for UNUserNotificationCenter .requestAuthorization in Swift 5,"<p>I am using test-driven development on Xcode and in Swift to develop an app.</p>

<p>I want to add timed notification alerts to remind people to come back to the app to perform an action. To do that I need to request authorization from my user using the notification center.</p>

<p>To do this, I want to write a test in my unit tests that only passes when the shared UNUserNotificationCenter instance calls its requestAuthorization(options:completionHandler:) method.</p>

<p>I have tried mocking UNUserNotificationCenter:</p>

<pre><code>extension NotificationsExperimentsTests {

    class MockNotificationCentre: UNUserNotificationCenter {

        var didRequestAuthorization = false

        override func requestAuthorization(options: UNAuthorizationOptions = [], completionHandler: @escaping (Bool, Error?) -&gt; Void) {
            didRequestAuthorization = true
        }
    }
}
</code></pre>

<p>But then when I try and initialise it in a test,</p>

<pre><code>func test_requestAuthorization_IsCalled() {

    var mockNotificationCenter = MockNotificationCentre()
}
</code></pre>

<p>the compiler tells me that:</p>

<blockquote>
  <p>'NotificationsExperimentsTests.MockNotificationCentre' cannot be constructed because it has no accessible initializers</p>
</blockquote>

<p>I'm not sure what to try next, or even whether what I'm trying to do is possible?</p>
",https://stackoverflow.com/questions/58960233/unit-testing-for-unusernotificationcenter-requestauthorization-in-swift-5,"['swift', 'tdd', 'unusernotificationcenter']",2128,True,5,1
Unit Testing - Wiremock verify failing with connection error,"<p>I'm testing a spring-boot application and using wiremock stubs to mock external API. In one test case I want to make sure that my stub gets called exactly once but it's failing with connection error.</p>

<p>My Test File:</p>

<pre><code>@SpringBootTest
@AutoConfigureWebTestClient
@ActiveProfiles(""test"")
class ControllerTest {

    @Autowired
    private lateinit var webClient: WebTestClient

    private lateinit var wireMockServer: WireMockServer

    @BeforeEach
    fun setup() {
        wireMockServer = WireMockServer(8081)
        wireMockServer.start()
        setupStub()
    }

    @AfterEach
    fun teardown() {
        wireMockServer.stop()
    }

    // Stub for external API
    private fun setupStub() {
        wireMockServer.stubFor(
        WireMock.delete(WireMock.urlEqualTo(""/externalApiUrl""))
            .willReturn(
                WireMock.aResponse()
                    .withHeader(""Content-Type"", ""application/json"")
                    .withStatus(204)
                    .withBodyFile(""file.json"")
            )
    )
    }

    @Test
    fun test_1() {

        val email = ""some-email""
        val Id = 123

        webClient.post()
        .uri { builder -&gt;
            builder.path(""/applicationUrl"")
                .queryParam(""email"", email)
                .queryParam(""id"", Id)
                .build()
        }
        .exchange()
        .expectStatus().isOk

        WireMock.verify(exactly(1), WireMock.deleteRequestedFor(WireMock.urlEqualTo(""/externalApiUrl"")))
}
</code></pre>

<p>When I run this test I'm getting the following error:</p>

<blockquote>
  <p>org.apache.http.conn.HttpHostConnectException: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused (Connection refused)</p>
</blockquote>

<p>Please let me know where I'm doing wrong. Thanks in advance.</p>
",https://stackoverflow.com/questions/54900364/unit-testing-wiremock-verify-failing-with-connection-error,"['spring-boot', 'junit', 'kotlin', 'wiremock']",6162,True,5,1
How to mock kotlin object for unit testing,"<p>I have a sample method(which I need to write test case) as given below,</p>

<pre><code> fun setName(val auxName:String) {
        val configUrl = getConfig(auxName)
    }
</code></pre>

<p>I want to mock the getConfig method and return a specific string value. 
getConfig is a method in a Kotlin Object as below,</p>

<pre><code>object Configuration{
    fun getConfig(auxName:String){
    ....
    }
    }
</code></pre>

<p>Below is the test that I tried</p>

<pre><code>@Test
fun setTest()
{
val testname=""test""
val testObject=Mockito.mock(Configuration::class.java)
doReturn(""configTest"").`when`(testObject).getConfig(Mockito.anyString())
setName(testname)
}
</code></pre>

<p>I am not getting any error but the method getConfig is not mocked. The actual implementation is executed. I tried using Powermockito also. Please help me with this</p>
",https://stackoverflow.com/questions/55448967/how-to-mock-kotlin-object-for-unit-testing,"['unit-testing', 'kotlin', 'mockito', 'powermockito']",7885,False,5,1
How to do Unit Testing in Kotlin/Native Multiplatform?,"<p>I have follow the tutorial of <a href=""https://kotlinlang.org/docs/tutorials/native/mpp-ios-android.html"" rel=""noreferrer"">https://kotlinlang.org/docs/tutorials/native/mpp-ios-android.html</a> and I wanted to Unit testing the commonTest I created in the SharedModule.</p>

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

<p>Things I tried:</p>

<p>I had tried using kotlin.test in the common file. I research online that you can use JUnit5 but when I imported in the dependencies in the commonTest, I can't access the library of the kotlin.test. Now I had successfully implemented the kotlin.test in the commonTest but how do I run it?</p>

<p>I tried gradlew commonTest.kt but it doesn't work. Please help thanks!</p>

<p>My SharedModule gradle codes:</p>

<pre><code>    apply plugin: 'kotlin-multiplatform'

kotlin {
    targets {
        final def iOSTarget = System.getenv('SDK_NAME')?.startsWith(""iphoneos"") \
                              ? presets.iosArm64 : presets.iosX64

        fromPreset(iOSTarget, 'iOS') {
            binaries {
                framework('SharedCode')
            }
        }

        fromPreset(presets.jvm, 'android')
    }

    sourceSets {
        commonMain.dependencies {
            api 'org.jetbrains.kotlin:kotlin-stdlib-common'
            api 'org.jetbrains.kotlin:kotlin-stdlib'
            //implementation(""com.ionspin.kotlin:bignum:0.0.8"")

            //Testing
            //implementation ""org.jetbrains.kotlinx:kotlinx-coroutines-core-common:$coroutines_version""
            //implementation ""org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serialization_version""
/*
            implementation ""io.ktor:ktor-client-core:$ktor_version""
            implementation ""io.ktor:ktor-client-json:$ktor_version""
            implementation ""io.ktor:ktor-client-logging:$ktor_version""*/

        }

        commonTest.dependencies{
            //implementation (""org.junit.jupiter:junit-jupiter-api:5.2.0"")
            //implementation (""org.junit.jupiter:junit-jupiter-engine:5.0.3"")
            //implementation 'junit:junit:4.12'
            implementation 'org.jetbrains.kotlin:kotlin-test-junit5:1.3.31'
            implementation 'org.jetbrains.kotlin:kotlin-test:1.3.31'
            //implementation ""io.mockk:mockk-common:1.9.3""
            //implementation 'io.kotlintest:kotlintest-runner-junit5:3.3.0'

            //Testing
            //implementation ""org.jetbrains.kotlin:kotlin-test-common""
            //implementation ""org.jetbrains.kotlin:kotlin-test-annotations-common""

            //implementation ""org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version""
            implementation ""io.mockk:mockk:1.8.13.kotlin13""
            implementation ""io.mockk:mockk-common:1.8.13.kotlin13""
            implementation 'org.amshove.kluent:kluent:1.42'
        }

        androidMain.dependencies {
            api 'org.jetbrains.kotlin:kotlin-stdlib'
        }
    }
}

// workaround for https://youtrack.jetbrains.com/issue/KT-27170
configurations {
    compileClasspath
}

task packForXCode(type: Sync) {
    final File frameworkDir = new File(buildDir, ""xcode-frameworks"")
    final String mode = project.findProperty(""XCODE_CONFIGURATION"")?.toUpperCase() ?: 'DEBUG'
    final def framework = kotlin.targets.iOS.binaries.getFramework(""SharedCode"", mode)

    inputs.property ""mode"", mode
    dependsOn framework.linkTask

    from { framework.outputFile.parentFile }
    into frameworkDir

    doLast {
        new File(frameworkDir, 'gradlew').with {
            text = ""#!/bin/bash\nexport 'JAVA_HOME=${System.getProperty(""java.home"")}'\ncd '${rootProject.rootDir}'\n./gradlew \$@\n""
            setExecutable(true)
        }
    }
}
tasks.build.dependsOn packForXCode
</code></pre>
",https://stackoverflow.com/questions/56267942/how-to-do-unit-testing-in-kotlin-native-multiplatform,"['android', 'kotlin', 'kotlin-multiplatform']",5061,True,11,1
How to perform unit testing of complex objects?,"<p>Let's suppose you want to create unit tests for a game.</p>

<p>You have the <code>Player</code> class, which has a local variable of the <code>World</code> class (instantiated by the construtor) and the <code>World</code> object has an open connection to the database.</p>

<p>So <code>player.breakBlock()</code> method would call <code>world.breakBlockAt(x,y,z)</code> and <code>world.breakBlockAt(int x, int y, int z)</code> method would perform changes to the database and return the result.</p>

<p>In cases like this where you have complex ""object dependencies"", what would be the best way to perform testing?</p>

<p>Currently I'm basically starting the whole game environment, with a test database, spawning a fake Player and using it for the testing.</p>
",https://stackoverflow.com/questions/58358422/how-to-perform-unit-testing-of-complex-objects,"['java', 'unit-testing', 'junit']",2020,True,5,4
Unit Testing a Service with Moq &amp; xUnit,"<p>Sorry, this is likely a very amateur question, but I am struggling to understand how to use Moq properly. I am quite new to unit testing as a whole, but I think I'm <em>starting</em> to get the hang of it.</p>

<p>So here's my question... I have this snippet of code below which is using a <code>TestServer</code> in Visual Studio that I using for am Unit Testing... I'm trying to mock <code>IGamesByPublisher</code> so that my test is not reliant on data in the repository (or would it be better to mock <code>GamesByPublisher</code>?... Or do I need to do both?)</p>

<pre><code>public static TestServerWithRepositoryService =&gt; new TestServer(services =&gt;
{
    services.AddScoped&lt;IGamesByPublisher, GamesByPublisher(); 
}).AddAuthorization(""fake.account"", null);


[Fact] // 200 - Response, Happy Path
public async Task GamesByPublisher_GamesByPublisherLookup_ValidRequestData_Produces200()
{

    // Arrange
    var server = ServerWithRepositoryService;

    // Act
    var response = await server.GetAsync(Uri);

    // Assert
    Assert.NotNull(response);
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);

}
</code></pre>

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

<pre><code>public interface IGamesByPublisher interface.
{
    Task&lt;IEnumerable&lt;Publisher&gt;&gt; Execute(GamesByPublisherQueryOptions options);
    }
}
</code></pre>

<p>I tried</p>

<pre><code>public static TestServerWithRepositoryService =&gt; new TestServer(services =&gt;
{
    services.AddScoped&lt;Mock&lt;IGamesByPublisher&gt;, Mock&lt;GamesByPublisher&gt;&gt;(); 
}).AddAuthorization(""fake.account"", null);
</code></pre>

<p>And then I tried</p>

<pre><code>// Not exactly what I attempted, but that code is long gone... 
var mock = new Mock&lt;IGamesByPublisher &gt;();
var foo = new GamesByPublisherQueryOptions();
mock.Setup(x =&gt; x.Execute(foo)).Returns(true);
</code></pre>

<p>I didn't really find great documentation on using Moq, just the quick start guide on GitHub, which I wasn't sure how to apply (probably my own level of experience at fault there...).</p>

<p>I am obviously missing some fundamentals on using Moq...</p>
",https://stackoverflow.com/questions/54165639/unit-testing-a-service-with-moq-xunit,"['c#', 'unit-testing', 'moq', 'xunit']",2319,True,4,1
unit testing angular service that uses firebase auth?,"<p>I've setup simple authentication service on angular that returns a Promise:</p>

<pre><code>import * as firebase from 'firebase/app';

@Injectable({
    providedIn: 'root'
})

export class AuthService {

  doLogin(val:{email:string, password:string}) {
  return new Promise&lt;any&gt;((resolve, reject) =&gt; {
    firebase
      .auth()
      .signInWithEmailAndPassword(val.email, val.password)
      .then(
        res =&gt; resolve(res),
        err =&gt; reject(err)
      );
    });
  }

}
</code></pre>

<p>How do I properly implement unit testing on the service? 
The way I currently achieve this to do unit testing using jasmine, by providing real user credential (which is not a good thing, as I'm going to push the code to github) and calling the doLogin method directly using the credential.</p>

<pre><code>describe('AuthService', () =&gt; {
let service: AuthService;
const userCreds = {
    email: 'somerealemail@somedomain.com',
    password: 'somerealpassword'
};

beforeEach(() =&gt; TestBed.configureTestingModule({
    imports: [FirebaseModule],
    providers: [AuthService]
}));

beforeEach(() =&gt; {
    service = TestBed.get(AuthService);
});

it('should logged in', async((done) =&gt; {
    service.doLogin(userCreds).then(
        res =&gt; {
            expect(res).toBeTruthy();
        }
    )
}));
</code></pre>

<p>Sorry if the code is mess, I'm totally new on both angular and jasmine, any advice or idea is greatly appreciated,
thanks</p>
",https://stackoverflow.com/questions/55235078/unit-testing-angular-service-that-uses-firebase-auth,"['angular', 'firebase', 'unit-testing', 'jasmine', 'firebase-authentication']",1689,True,4,1
Is there any DataRowAttribute in f# unit testing?,"<p>In c# I can do this (<a href=""https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.datarowattribute?view=mstest-net-1.2.0"" rel=""nofollow noreferrer"">DataRowAttribute (c#)</a>)</p>

<pre><code>[TestMethod]
[DataRow(1,2,3)]
[DataRow(2,2,4)]
public void TestSum (int x, int y, int expected)
</code></pre>

<p>I could not find a way to do this in f#. If it does not exist, how can I create such attribute for f# unit testing ?</p>

<hr>

<p>UPDATE</p>

<p>Providing code after Jonathon Chase's suggestion with <code>[&lt;DataRow (2,4,6)&gt;]</code>.
Unfortunately the test <code>AddTest</code> is not discovered by the test runner.</p>

<pre><code>namespace FsharpTests

open System
open Microsoft.VisualStudio.TestTools.UnitTesting

[&lt;TestClass&gt;]
type TestClass () =

    [&lt;TestMethod&gt;]
    member this.TestMethodPassing() =
        Assert.IsTrue(true);

    [&lt;TestMethod&gt;]
    [&lt;DataRow (1,2,3)&gt;]
    [&lt;DataRow (2,4,6)&gt;]
     member this.AddTest(a, b, expected) = 
        Assert.AreEqual(expected, a+b); //won't be discovered by the test runner
</code></pre>
",https://stackoverflow.com/questions/58718596/is-there-any-datarowattribute-in-f-unit-testing,"['c#', 'f#']",154,True,3,1
Mocking Highcharts (w/ Exporting) for Jest Unit Testing,"<p>I am working on a React project that I am testing using Jest.
Our application uses Highcharts to render data visulaizations on our views, but I am having an issue when it comes to using one of Highcharts plugin modules ""exporting"" that is used for capturing the dataURL of the svg Highcharts has already rendered.</p>

<p>Everything unfortunately works beautifully when it comes to actually running the application and seeing everything work, but since unit testing is a big requirement  I am now stuck on this mocking aspect. </p>

<p>My component imports highcharts and it's module like</p>

<pre><code>import Highcharts, { Chart } from 'highcharts';
import addExporting from 'highcharts/js/modules/exporting.src.js'
addExporting(Highcharts);
</code></pre>

<p>I created a genMockFromModule in <strong>mocks</strong>/highcharts.ts</p>

<pre><code>const highcharts: any = jest.genMockFromModule(`highcharts`);
highcharts.getOptions = () =&gt; ({ plotOptions: {}, exporting: {} });
module.exports = highcharts;
</code></pre>

<p>I tried in my test file (<strong>tests</strong>/components/Chart.ts)</p>

<pre><code>jest.mock('highcharts', () =&gt; ({
  Chart: jest.fn(),
  setOptions: jest.fn(),
  seriesTypes: {},
}));
jest.mock('highcharts/js/modules/exporting.src.js', () =&gt; jest.fn() )
</code></pre>

<p>Seems whatever I try, I always get this issue: </p>

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

<pre><code>  16 |
&gt; 18 | addExporting(Highcharts);
     | ^
  19 |

  at node_modules/highcharts/js/modules/exporting.src.js:49:23
  at node_modules/highcharts/js/modules/exporting.src.js:1760:3
</code></pre>
</blockquote>

<p>Without addExporting module I can't figure out how to mock the other highcharts functionality such as </p>

<pre><code>if(this.chartRef) {
    this.chartRef.destroy()
}
</code></pre>
",https://stackoverflow.com/questions/56117785/mocking-highcharts-w-exporting-for-jest-unit-testing,"['reactjs', 'highcharts', 'jestjs', 'enzyme']",2365,False,3,0
Angular Unit Testing - Mock Child Component using Stub,"<p>I am trying to unit test a component that has a child component that I want to mock. I don't want to use the NO_ERRORS_SCHEMA cause the drawbacks associated. I am trying to use a stub/dummy child component. The code is as follows: </p>

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

<pre><code>@Component({
  selector: 'parent',
  template: `
    &lt;!-- Does other things --&gt;
    &lt;child&gt;&lt;/child&gt;
  `
})
export class ParentComponent { }
</code></pre>

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

<pre><code>@Component({
  selector: 'child',
  template: '&lt;!-- Does something --&gt;'
})
export class ChildComponent {
  @Input() input1: string;
  @Input() input2?: number;
}
</code></pre>

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

<pre><code>describe('ParentComponent', () =&gt; {
  let component: ParentComponent;
  let fixture: ComponentFixture&lt;ParentComponent&gt;;
  let router: Router;

  @Component({
    selector: 'child',
    template: '&lt;div&gt;&lt;/div&gt;'
  })
  class ChildStubComponent {
    @Input() input1: string;
    @Input() input2: number;
  }

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ ParentComponent, ChildStubComponent ],
      imports: [
        AppRoutingModule, HttpClientModule, BrowserAnimationsModule,
        RouterTestingModule.withRoutes(routes)
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ParentComponent);
    component = fixture.componentInstance;
    router = TestBed.get(Router);
    spyOnProperty(router, 'url', 'get').and.returnValue('/somePath');
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    component.ngOnInit();
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>The problem I'm having is that angular is complaining with the following error: </p>

<pre><code>Failed: Template parse errors:
More than one component matched on this element.
Make sure that only one component's selector can match a given element.
</code></pre>

<p>I'm using Angular version 8 if that helps. Everywhere I looked so far shows that you stub a child component the same way I am doing now. Using ngMocks is not an option at the moment.</p>

<p><strong>EDIT</strong>
Tried using ngMock but this only has the same problem. Any help would be very much appreciated!</p>

<p><strong>Solution</strong></p>

<p>Got it working. Problem was that the AppRoutingModule had the real component imported already.</p>
",https://stackoverflow.com/questions/59290948/angular-unit-testing-mock-child-component-using-stub,"['angular', 'typescript', 'unit-testing', 'jasmine']",8955,True,3,1
Unit testing using sinon stub promise and axios,"<p>I am trying to test my node js api using sinon. I have a function <strong>appRequest()</strong>  that returns the appDetails; but I am not able to get the result. I am using proxyquire to get the result but its not working.</p>

<p><strong>appService.js</strong></p>

<pre><code>function appRequest(apprequestData) {
 return new Promise(function (resolve, reject) {
     console.log(apprequestData);
    axios.get(url + apprequestData.dataId).then(appResult =&gt; {
        console.log('appResult'+appResult);
        if ('' == appResult.data.result || appResult.data.result[0].dataId!= apprequestData.dataId) {
            reject({
                status: 404,
                message: ""APP not Found""
            });
            return;
        }
        resolve({
            clientId: appResult.data.result[0].dataId
        });

    }).catch(error =&gt; {
        console.log(error);
        if (null == error.response || error.response.status == 404) {
            reject({ status: 404, message: ""APP service down"", referenceNumber: apprequestData.referenceNumber });
            return;
        }
        reject({ status: 404, message: ""APP service down"", referenceNumber: apprequestData.referenceNumber });
        return;
    });
});
</code></pre>

<p>}</p>

<p><strong>app.test.js</strong></p>

<p>describe(""App request"", function() {</p>

<pre><code>describe('get app details', () =&gt;{
 var appDetails, teststub;
 let req = {
  ""dataId"": ""1234""
}

let response={ ""dd"":23}

//  teststub = sinon.stub(axios,'get').resolves(Promise.resolve(response));
teststub = sinon.stub();

it('should return app ', function() {

     appDetails = proxyquire('../app/service/appService', { 'axios': teststub.returns(response)}) 
      console.log(appDetails);
      var result=appDetails.appRequest(req);
      console.log(""***""+JSON.stringify(result)); // this is coming as empty
      expect(result.statusCode).equal(200);
      });


});
</code></pre>

<p>});</p>
",https://stackoverflow.com/questions/58832791/unit-testing-using-sinon-stub-promise-and-axios,"['node.js', 'axios', 'proxyquire']",1018,False,2,0
Unit Testing a method with a large string,"<p>I'm currently using C#, but I believe the question applies to more languages.</p>

<p>I have a method, which takes a string value, and throws an exception, if it's too big. I want to unit test it that the exception is correct.</p>

<pre><code>int vlen = Encoding.UTF8.GetByteCount(value);
if (vlen &lt; 0 || 0x0FFFFFFF &lt; vlen)
   throw new ArgumentException(""Valid UTF8 encodded value length is up to 256MB!"", ""value"");
</code></pre>

<p>What is the best way to generate such a string? Should I just have a file of that size? Should I create such a file every time running unit tests? </p>
",https://stackoverflow.com/questions/54869854/unit-testing-a-method-with-a-large-string,"['c#', 'string', 'unit-testing']",2344,True,2,3
Unit Testing AntD Modal with Jest and Enzyme,"<p>I'm trying to Unit test AntD modal in React using Jest and Enezym and it gives me following errors:</p>

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

<p>and another one </p>

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

<p>this as well:
   Invariant Violation: Objects are not valid as a React child (found: object with keys {destroy, update}). If you meant to render a collection of children, use an array instead.</p>

<p>and here's the modal I've created</p>

<pre><code>import propTypes from 'prop-types';
import { Modal } from 'antd';

const SuccessModal = props =&gt; {
const { title, content } = props;
return Modal.success({
title,
content,
});
   };

SuccessModal.propTypes = {
title: propTypes.string.isRequired,
content: propTypes.string.isRequired,
  };
  export default SuccessModal;
</code></pre>

<p>and here are my unit tests</p>

<pre><code>import React from 'react';
import { shallow } from 'enzyme';
import SuccessModal from './index';

describe('SuccessModal', () =&gt; {
  it('should render the component correctly in ', () =&gt; {
    shallow(&lt;SuccessModal title=""time to succeed"" content=""sucess content        success content"" /&gt;);
  });
  it('check the props values', () =&gt; {
    const props = {
      title: 'this is a success title',
      content: 'sucess content sucess content',
    };

    const renderedComponent = shallow(&lt;SuccessModal {...props} /&gt;);
    expect(renderedComponent.prop('title')).toBe('this is a success title');
    expect(renderedComponent.prop('content')).toBe('sucess content sucess content');
  });
});
</code></pre>

<p>I've also tried this way</p>

<pre><code>  expect(

        (      
    &lt;SuccessModal title=""this is a success title"" content=""sucess content sucess content"" /&gt;
  ).exists(),
).toEqual(true);
expect((   &lt;SuccessModal title=""this is a success title"" content=""sucess content sucess content"" /&gt;).text()).toContain('this is a success title');
</code></pre>

<p>any help highly appreciated and if more clarification is needed let me know in the comment</p>
",https://stackoverflow.com/questions/55022003/unit-testing-antd-modal-with-jest-and-enzyme,"['reactjs', 'jestjs', 'enzyme', 'antd']",2892,False,2,1
Unit testing Apollo Graphql in React using Hooks,"<p>I am trying to create a unit test using React and Apollo Graphql, however I keep getting this error:</p>

<pre><code>Watch Usage: Press w to show more.  console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:104
    Warning: An update to ThemeHandler 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 */

    This ensures that you're testing the behavior the user would see in the browser. 
        in ThemeHandler (at theme-handler.spec.tsx:51)
        in ApolloProvider (created by MockedProvider)
        in MockedProvider (at theme-handler.spec.tsx:50)
</code></pre>

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

<pre><code>import { createMuiTheme, MuiThemeProvider } from '@material-ui/core';
import * as Sentry from '@sentry/browser';
import React, { useState } from 'react';
import { BrandTheme, useGetBrandThemeQuery } from '../../generated/graphql';

/**
 * Handles the app theme. Will set the default theme or the brand theme taken from the backend.
 */
export default function ThemeHandler(props: React.PropsWithChildren&lt;any&gt;): React.ReactElement {
  const brandId = Number(process.env.REACT_APP_BRAND);

  // Default Onyo theme
  const [theme, setTheme] = useState({
    palette: {
      primary: { main: '#f65a02' },
      secondary: { main: '#520075' },
    },
    typography: {
      fontFamily: 'Quicksand, sans-serif',
    },
  });

  useGetBrandThemeQuery({
    variables: { brandId },
    skip: brandId &lt;= 0,
    onCompleted: data =&gt; {
      if (
        !data.brandTheme ||
        !data.brandTheme.brandThemeColor ||
        data.brandTheme.brandThemeColor.length === 0
      ) {
        console.warn('Empty brand theme returned, using default');
        Sentry.captureMessage(`Empty brand theme for brandId: ${brandId}`, Sentry.Severity.Warning);
      } else {
        const palette = parseBrandPalette(data.brandTheme as BrandTheme);
        setTheme({ ...theme, palette });
        console.log('Theme', theme, data.brandTheme);
      }
    },
  });

  return &lt;MuiThemeProvider theme={createMuiTheme(theme)}&gt;{props.children}&lt;/MuiThemeProvider&gt;;
}

function parseBrandPalette(brandTheme: BrandTheme) {
  const pallete: any = {};

  for (const color of brandTheme.brandThemeColor!) {
    if (color &amp;&amp; color.key === 'primaryColor') {
      pallete.primary = { main: color.value };
    } else if (color &amp;&amp; color.key === 'darkPrimaryColor') {
      pallete.secondary = { main: color.value };
    }
  }

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

<p>And my test:</p>

<pre><code>import renderer from 'react-test-renderer';
import React from 'react';
import ThemeHandler from './theme-handler';

import { MockedProvider, wait } from '@apollo/react-testing';
import { GetBrandThemeDocument } from '../../generated/graphql';
import { Button } from '@material-ui/core';

const { act } = renderer;

describe('Theme Handler', () =&gt; {
  const originalEnv = process.env;

  beforeEach(() =&gt; {
    // https://stackoverflow.com/questions/48033841/test-process-env-with-jest/48042799
    jest.resetModules();
    process.env = { ...originalEnv };
    delete process.env.REACT_APP_BRAND;
  });

  afterEach(() =&gt; {
    process.env = originalEnv;
  });

  it('should use a theme retrieved from the backend', async () =&gt; {
    process.env.REACT_APP_BRAND = '39';

    const mocks = [
      {
        request: {
          query: GetBrandThemeDocument,
          variables: { brandId: 39 },
        },
        result: {
          data: {
            brandTheme: {
              brandThemeColor: [
                { key: 'primaryColor', value: '#182335' },
                { key: 'darkPrimaryColor', value: '#161F2F' },
              ],
            },
          },
        },
      },
    ];

    let wrapper;
    act(() =&gt; {
      wrapper = renderer.create(
        &lt;MockedProvider mocks={mocks} addTypename={false}&gt;
          &lt;ThemeHandler&gt;
            &lt;Button color='primary' id='test-obj'&gt;
              Hello world!
            &lt;/Button&gt;
          &lt;/ThemeHandler&gt;
        &lt;/MockedProvider&gt;
      );
    });

    await wait(0);
    expect(wrapper).toBeTruthy();
  });
});
</code></pre>

<p>I also tried to use Enzyme's <code>mount</code> instead of the React test renderer, but the result is the same.</p>

<p>As far as I could tell, this error is being caused because I am changing the current state using an async function and hooks. But I am not sure what could I do differently for this to work.</p>
",https://stackoverflow.com/questions/57477504/unit-testing-apollo-graphql-in-react-using-hooks,"['reactjs', 'typescript', 'graphql']",1586,True,2,1
How to test getElementsByClassName method with unit-testing?,"<p>I want to test a function which add a classname to a div container when there are more than 7 pages. But don't get it worked.</p>

<p>Tried with spyOn, but no result.</p>

<p>The constructor</p>

<pre><code>constructor($document, $element) {
  this.$document = $document;
  this.$element = $element;
}
</code></pre>

<p>onInit function</p>

<pre><code>$onInit() {
const listPages = this.element.children;
const totalPages = listPages.length;

if (totalPages&gt; 7) {
  this.$document[0].getElementsByClassName('test-container')[0].className += ' test';
}
}
</code></pre>

<p>I tried this:</p>

<pre><code>beforeEach(() =&gt; {
this.documentSpy = jasmine.createSpyObj('$document', ['getElementsByClassName']);
this.elementSpy = jasmine.createSpyObj('$element', ['find']);
});


fit('should add class test when styles contain atleast 7 steps', () =&gt; {
    let stepPage = new stepPageController(this.documentSpy, this.elementSpy);
    stepPage.element = {
        children: [
            { step: ['current'] },
            { step: ['step2'] },
            { step: ['step3'] },
            { step: ['step4'] },
            { step: ['step5'] },
            { step: ['step6'] },
            { step: ['step7'] },
            { step: ['step8'] }
        ]
    };

    const element = angular.element(this.$document[0].body).append('&lt;div class=""test-container""&gt;&lt;/div&gt;');
    spyOn(stepPage.$document[0], 'getElementsByClassName').and.returnValue(element);

    // When
    stepPage.$onInit();

    // Then
    expect(stepPage.$document[0].getElementsByClassName('test-container')[0].className).toBe('test');
});
</code></pre>

<p>but get this as error:  TypeError: Cannot read property '0' of undefined</p>
",https://stackoverflow.com/questions/57689547/how-to-test-getelementsbyclassname-method-with-unit-testing,"['angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",1475,False,2,0
Android - Unit testing with Robolectric is very slow,"<p>I'm using Robolectric 4.2 to write unit test cases for one of my Android applications. The test case is very simple like below:</p>

<pre><code>@Before
public void setUp() {
    landingActivity = Robolectric.setupActivity(LandingActivity.class);
}

@Test
public void shouldNotBeNull() {
    assertNotNull(landingActivity);
}
</code></pre>

<p>But its taking forever to get completed. Can someone help me out what is happening and is there anything I'm missing.</p>
",https://stackoverflow.com/questions/54859504/android-unit-testing-with-robolectric-is-very-slow,"['android', 'unit-testing', 'robolectric']",945,False,2,0
PHPUnit unit testing: Handling session_start() in a method,"<p>I have the following class in a file located in <code>./src/PCMagas/Dropbox.php</code>. that I need to test it:</p>

<pre><code>namespace PCMagas;
define(""API_OAUTH_TOKEN_URL"",""https://api.dropboxapi.com/oauth2/token"");

use \GuzzleHttp\Client; 
use \GuzzleHttp\RequestOptions;

class Dropbox
{
    /**
     * @param String $appid The Dropbox Application Id.
     * @param String $secret The dropbox Secret
     * @param Client $httpClient The interface used to consume the Dropbox Rest API
     */
    public function __construct($appId,$secret,Client $httpClient)
    {
        $this-&gt;appId=$appId;
        $this-&gt;secret=$secret;
        $this-&gt;httpClient=$httpClient;
    }

    /**
     * Common Logic for Handling Http Error
     * @param Integer $code
     * @throws Exception
     */
    private function httpErrorHandling($code)
    {
        switch($code){
            case 400:
                throw new Exception('Invalid HttpRequest to DropBoxApi');
            case 401:
                throw new Exception('Invalid Dropbox Token');
            case 403:
                throw new Exception('Access Denied');
            case 429:
                throw new Exception('Try again later (after a 10th cup of coffee)');
            case 409:
                throw new Exception('Api user provided error');
            //Treat all 500 error code (seems kinda ugly)
            case 500:
            case 501:
            case 502:
            case 503:
            case 504:
            case 505:
            case 506:
            case 507:
            case 508:
            case 510:
            case 511:
                throw new Exception('Internal Dropbox Error');
        }
    }

    /**
     * @param String $code
     * @return String
     * @throws InvalidArgumentException In case that the code is not correctly Provided.
     * @throws Exception if any error occured when token cannot be fetched
     */
    public function getToken($code)
    {
        //If code get token from code
        //Else get token from $session
        //Not satisfiable thows Esception
        session_start();
        if(!empty($_SESSION['token'])){
            return $_SESSION['token'];
        }

        if(empty($code)){
            throw new \InvalidArgumentException('Please provide a code fetched from Dropbox Athorization.');
        }

        if(empty($_SESSION['redirect_url'])){
            throw new \Exception('Cannot find the url that Dropbox Redirected From');
        }

        $response = $this-&gt;httpClient-&gt;request(""POST"",API_OAUTH_TOKEN_URL,[
            RequestOptions::FORM_PARAMS =&gt;[
                'code'=&gt;$code,
                'grant_type'=&gt;'authorization_code',
                'redirect_uri'=&gt;$_SESSION['redirect_url']
            ],
            RequestOptions::AUTH=&gt;[$this-&gt;appId,$this-&gt;secret]
        ]);

        //Call method and let it blow up
        $this-&gt;httpErrorHandling($response-&gt;getStatusCode());

        $body=$response-&gt;getBody()-&gt;getContents();
        $body=json_decode($body,true);
        $_SESSION['token']=$body['access_token'];
        return $_SESSION['token'];
    }
}
</code></pre>

<p>Then I try to unit test the method <code>getToken</code> like that (file located in <code>./tests/DropBoxTest.php</code>:</p>

<pre><code>namespace PCMagas\Tests;

use PHPUnit\Framework\TestCase;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Client;

use PCMagas\Dropbox;

define('ERROR_CODES',[400,401,403,409,429,500,501,502,503,504,505,506,507,508,510,511]);
define('ERROR_CODE_LENGTH',count(ERROR_CODES));

final class DropBoxTest extends TestCase
{

    private function mockErrorGuzzle()
    {
        $responses=array_map(function($statusCode){
            return new Response($statusCode);
        },ERROR_CODES);
        $handler = new MockHandler($responses);
        $client = new Client(['handler'=&gt;$handler]);
        return $client;
    }

    public function testHttpErrorOnTonenFetch()
    {
        $guzzle=$this-&gt;mockErrorGuzzle();
        $dropBox=new Dropbox(""dummyappId"",""dummySecret"",$guzzle);
        for($i=0;$i&lt;ERROR_CODE_LENGTH;$i++) {
            $this-&gt;expectException(\Exception::class);
            $dropBox-&gt;getToken(""dummyCode"");
        }
    }
}
</code></pre>

<p>My file structure is:</p>

<pre><code>|- src
|-- PCMagas
|---- Dropvox.php
|- tests
|-- DropBoxTest.php
</code></pre>

<p>And my <code>phpunit.xml</code> is:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;phpunit
     backupStaticAttributes=""false""
     bootstrap=""./vendor/autoload.php""
     cacheTokens=""false""
     colors=""true""
     convertErrorsToExceptions=""true""
     convertNoticesToExceptions=""true""
     convertWarningsToExceptions=""true""
     forceCoversAnnotation=""false""
     mapTestClassNameToCoveredClassName=""false""
     processIsolation=""false""
     stopOnError=""false""
     stopOnFailure=""false""
     stopOnIncomplete=""false""
     stopOnSkipped=""false""
     verbose=""false""&gt;
    &lt;testsuites&gt;
        &lt;testsuite name=""Application Unit Tests""&gt;
            &lt;directory&gt;./tests&lt;/directory&gt;
        &lt;/testsuite&gt;
    &lt;/testsuites&gt;
&lt;/phpunit&gt;
</code></pre>

<p>Whilst my <code>composer.json</code> has the following input:</p>

<pre><code>{
    ""require"": {
        ""guzzlehttp/guzzle"": ""~6.0"",
    },
    ""require-dev"": {
        ""phpunit/phpunit"": ""~6.0"",
        ""laravel/homestead"": ""^7.20""
    },
    ""autoload"": {
        ""psr-4"":{
            ""PCMagas\\"": ""src/PCMagas""
        }
    },
    ""autoload-dev"": {
        ""psr-4"": { ""PCMagas\\Tests\\"": ""tests/"" }
    }
}
</code></pre>

<p>But when I try to run the unit test I get the following error:</p>

<blockquote>
  <p>Time: 621 ms, Memory: 4.00MB</p>
  
  <p>There was 1 error:</p>
  
  <p>1) PCMagas\Tests\DropBoxTest::testHttpErrorOnTonenFetch
  session_start(): Cannot start session when headers already sent</p>
  
  <p>/home/vagrant/code/src/PCMagas/Dropbox.php:84
  /home/vagrant/code/tests/DropBoxTest.php:36</p>
</blockquote>

<p>Do you know how to fix that error?</p>
",https://stackoverflow.com/questions/55849664/phpunit-unit-testing-handling-session-start-in-a-method,"['php', 'unit-testing', 'session', 'phpunit']",1902,True,2,1
Unit Testing Private Methods in Unity Test Runner,"<p>I'd like to do a unit test for my private methods in C#. Since the methods are private, they are not accessible from the test environment.</p>
",https://stackoverflow.com/questions/58851638/unit-testing-private-methods-in-unity-test-runner,"['c#', 'visual-studio', 'unit-testing', 'unity-game-engine', 'private-methods']",1965,True,2,2
Unit testing FTP in Java (JSch &amp; MockFtpServer),"<p>I'm using JCraft's JSch library for as a FTP client for my program, it's working fine. But I had difficulties creating a mock (MockFtpServer) for unit testing. </p>

<pre><code>import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.mockftpserver.fake.FakeFtpServer;
import org.mockftpserver.fake.UserAccount;
import org.mockftpserver.fake.filesystem.FileEntry;
import org.mockftpserver.fake.filesystem.FileSystem;
import org.mockftpserver.fake.filesystem.UnixFakeFileSystem;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Properties;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SFTPManagerTest {

static FakeFtpServer fakeFtpServer;

@BeforeClass
public static void startFTP() throws Exception {
    fakeFtpServer = new FakeFtpServer();
    fakeFtpServer.setServerControlPort(9999);

    FileSystem fileSystem = new UnixFakeFileSystem();
    fileSystem.add(new FileEntry(""/data/JFS_HCID_APPLICATION_STATUS_20190109.TXT"", ""&lt;schema/&gt;""));
    fakeFtpServer.setFileSystem(fileSystem);

    UserAccount userAccount = new UserAccount(""user"", ""password"", ""/"");
    fakeFtpServer.addUserAccount(userAccount);
    fakeFtpServer.start();
}

@Test
public void getFileListing() {

    try {
        JSch jsch = new JSch();
        Session jschSession = jsch.getSession(""user"", ""localhost"", 9999);
        jschSession.setPassword(""password"");

        Properties config = new Properties();
        config.put(""StrictHostKeyChecking"", ""no"");
        jschSession.setConfig(config);
        jschSession.connect();

        Channel jschChannel = jschSession.openChannel(""ftp"");
        jschChannel.connect();
        ChannelSftp channel = (ChannelSftp) jschChannel;
        Vector v = channel.ls(""/data"");
        Assert.assertNotNull(v);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

@AfterClass
public static void stopFTP() {
    fakeFtpServer.stop();
}
}
</code></pre>

<p>Dependencies:</p>

<ul>
<li>com.jcraft:jsch:0.1.55</li>
<li>org.mockftpserver:MockFtpServer:2.7.1</li>
</ul>

<p>Output: it always stuck/stall during executing test method, not finishing. When stuck/stalling I could access the MockFtpServer with WinSCP or FTP CLI. From the log it seems the command from JSch not recognized.</p>

<pre class=""lang-none prettyprint-override""><code>2019-02-18 17:54:15,996 INFO  [Thread-0] org.mockftpserver.core.server.AbstractFtpServer: Connection accepted from host /127.0.0.1
2019-02-18 17:54:16,002 INFO  [Thread-6] org.mockftpserver.core.command.AbstractTrackingCommandHandler: Sending reply [220 Service ready for new user. (MockFtpServer 2.7.1; see http://mockftpserver.sourceforge.net)]
2019-02-18 17:54:16,004 INFO  [Thread-6] org.mockftpserver.core.session.DefaultSession: Received command: [SSH-2.0-JSCH-0.1.54]
2019-02-18 17:54:16,004 WARN  [Thread-6] org.mockftpserver.core.command.UnsupportedCommandHandler: No CommandHandler is defined for command [SSH-2.0-JSCH-0.1.54]
2019-02-18 17:54:16,005 INFO  [Thread-6] org.mockftpserver.core.command.AbstractTrackingCommandHandler: Sending reply [502 Command not implemented: SSH-2.0-JSCH-0.1.54.]
</code></pre>

<p>Where did i go wrong?</p>
",https://stackoverflow.com/questions/54746688/unit-testing-ftp-in-java-jsch-mockftpserver,"['java', 'ftp', 'mocking', 'jsch']",3162,True,2,1
Working with NSPredicate for Unit Testing in iOS,"<p>I have following test class, that get data from remote server and trying to check it for nil:</p>

<pre><code>import XCTest
@testable import DogYears

class DogYearsUnitTests: XCTestCase {
    var resData: Data? = nil

  func testInfoLoading(){

    let url = ""https://raw.githubusercontent.com/FahimF/Test/master/DogYears-Info.rtf""
    HTTPClient.shared.get(url: url) { (data, error) in
      XCTAssertNil(error)
      XCTAssertNotNil(data)
        self.resData = data
    }

    let predicate = NSPredicate(format: ""resData != nil"")
    let exp = expectation(for: predicate, evaluatedWith: self, handler: nil)
    let res = XCTWaiter.wait(for: [exp], timeout: 5.0)
    if res == XCTWaiter.Result.completed {
      XCTAssertNotNil(resData, ""No data recieved from server for InfoView content"")
    } else {
      XCTAssert(false)
    }

  }
}
</code></pre>

<p>It does work, but i wonder why NSPredicate Not working. You see, changing <code>let predicate = NSPredicate(format: ""resData != nil"")</code> to <code>let predicate = NSPredicate(format: ""resData == nil"")</code> have no effect, and test still passed, why it's passed even for this <code>let predicate = NSPredicate(format: ""resData == nil"")</code> ? </p>
",https://stackoverflow.com/questions/56824081/working-with-nspredicate-for-unit-testing-in-ios,"['ios', 'swift']",773,True,2,1
Mocking vscode API when unit testing in Jest,"<p>Environment:</p>

<pre class=""lang-sh prettyprint-override""><code>$ jest -v &gt; 24.9.0
$ node -v &gt; 10.15.3
""@types/vscode"": ""1.37.0""
""vscode"": ""^1.37.0""
</code></pre>

<p>Inspiration came from <a href=""https://stackoverflow.com/questions/47906194/unit-test-functions-that-use-vscode-extension-api-functions"">Unit test functions that use vscode extension api functions</a></p>

<p>The layer of indirection has solved part of my problem! However, I need to remove the following function from my extension code so that I can unit test without the dependency of vscode api:</p>

<pre class=""lang-js prettyprint-override""><code>await commands.executeCommand('vscode.open', uri);
</code></pre>

<p>The code is refactored to  <code>VscodeEnv</code> as follows:</p>

<pre class=""lang-js prettyprint-override""><code>import { Uri, commands, ExtensionContext, WebviewPanel, Disposable } from 'vscode';

export type VSCodeWebviewPanel = WebviewPanel;
export { ExtensionContext as VSCodeExtensionContext };
export { Uri as VSCodeUri };

export class VscodeEnv {
    private static instance: VscodeEnv;
    private constructor() {
        // Nothing added
    }

    public static async executeCommand(command: string, ...rest: any[]): Promise&lt;any | undefined&gt; {
        return commands.executeCommand(command, rest);
    }

    public static registerCommand(command: string, callback: (...args: any[]) =&gt; any, thisArg: any): Disposable {
        return commands.registerCommand(command, callback, thisArg);
    }

    public static getInstance(): VscodeEnv {
        if (!VscodeEnv.instance) {
            VscodeEnv.instance = new VscodeEnv();
        }
        return VscodeEnv.instance;
    }
}
</code></pre>

<p>Commands are registered as follows:</p>

<pre class=""lang-js prettyprint-override""><code>       const openFileCommand = new OpenFileCmd();
        VscodeEnv.registerCommand(
            ExtensionConfig.Commands.OpenFile.cmd,
            async (uri: VSCodeUri) =&gt; openFileCommand.openFile(context, uri.fsPath || ''), this);
</code></pre>

<p>And commands are executed as follows:</p>

<pre class=""lang-js prettyprint-override""><code>await VscodeEnv.executeCommand(ExtensionConfig.Commands.Display.cmd, editParams);
</code></pre>

<p>The following error message is thrown when I try to call <code>executeCommand</code> with the new flow:</p>

<blockquote>
  <p>No extension context</p>
</blockquote>

<p>Still a few tweaks to incorporate Jest but it allows me to mock vscode API.</p>

<p>Any improvements would be appreciated or any idea why the context is empty?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/58290565/mocking-vscode-api-when-unit-testing-in-jest,"['javascript', 'jestjs', 'vscode-extensions']",1039,False,2,1
Unit testing Nativescript application logic on a browser,"<p>I am trying to set up unit testing for a Nativescript application, run by <code>ng test</code> on a browser. The problem is that whenever there is a <code>tns-core-modules</code> or another plugin import, the module cannot be resolved because of the platform specific files (e.g. ""tns-core-modules/application/application.android.js"") that never get compiled into the bundle, thus throwing an error like ""Module not found: Error: Can't resolve 'tns-core-modules/application'"".</p>

<p>I know there is a built-in unit test support in Nativescript. The problem I have with it is that it can't run on CI. I would like to be a ble to have lightweight tests for my business logic, mocking out all platform dependencies.
I have looked for a way to mock the module imports at runtime with no luck. I looked into <code>rewire</code> package but it only runs on node.</p>
",https://stackoverflow.com/questions/55458902/unit-testing-nativescript-application-logic-on-a-browser,"['unit-testing', 'angular-cli', 'nativescript', 'nativescript-angular']",268,True,2,2
Unit testing respository with in MVVM pattern android,"<p>I am trying to write unit tests for repository while using MVVM pattern in android.</p>

<p>What i have is a repository which fetched data from the network using retrofit</p>

<pre><code>   public class ValidateCbuRepository {

    private static ValidateCbuRepository single_instance = null;

    private MutableLiveData&lt;CBUValidationImageResponse&gt; data = new MutableLiveData&lt;&gt;();

    public static ValidateCbuRepository getInstance() {
        if (single_instance == null)
            single_instance = new ValidateCbuRepository();

        return single_instance;
    }

    public MutableLiveData&lt;CBUValidationImageResponse&gt; processImage(String encodedString) {

        JsonObject postParam = new JsonObject();
        postParam.addProperty(""image"", encodedString);

        Api service = RetrofitClientInstance.getRetrofitInstance().create(Api.class);
        data.setValue(null);

        HttpUrl httpUrl = HttpUrl.parse(""some url"");
        Call&lt;CBUValidationImageResponse&gt; responseCall = service.getProcessedImage_cbu_validation(httpUrl.toString(),postParam);
        responseCall.enqueue(new Callback&lt;CBUValidationImageResponse&gt;() {
            @Override
            public void onResponse(Call&lt;CBUValidationImageResponse&gt; call, Response&lt;CBUValidationImageResponse&gt; response) {
                if(response.isSuccessful()) {
                    CBUValidationImageResponse res = response.body();
                    CBUValidationImageResponse cbuValidationImageResponse = res;
                    Log.i(""CBU response "",""""+cbuValidationImageResponse.toString());
                    cbuValidationImageResponse.setSuccess(true);
                    cbuValidationImageResponse.setShowProgres(false);
                    cbuValidationImageResponse.setError(false);
                    data.setValue(cbuValidationImageResponse);
                }
            }

            @Override
            public void onFailure(Call&lt;CBUValidationImageResponse&gt; call, Throwable t) {
                CBUValidationImageResponse cbuValidationImageResponse = new CBUValidationImageResponse();
                cbuValidationImageResponse.setError(true);
                cbuValidationImageResponse.setShowProgres(false);
                data.setValue(cbuValidationImageResponse);
                t.printStackTrace();
            }
        });
        return data;
    }
}
</code></pre>

<p>The unit test part</p>

<pre><code> @Mock
    private Observer&lt;CBUValidationImageResponse&gt; observer;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

    }


    @Test
    public void testApiResponse_success() {
        Api mockedApiInterface = Mockito.mock(Api.class);
        Call&lt;CBUValidationImageResponse&gt; mockedCall = Mockito.mock(Call.class);

        Mockito.when(mockedApiInterface.getProcessedImage_cbu_validation(any(),any())).thenReturn(mockedCall);
        try {
            Mockito.doAnswer(new Answer() {
                @Override
                public Void answer(InvocationOnMock invocation) throws Throwable {
                    Callback&lt;CBUValidationImageResponse&gt; callback = invocation.getArgument(0);

                    CBUValidationImageResponse cbuValidationImageResponse = new CBUValidationImageResponse();
                    cbuValidationImageResponse.setCBU_code(""some code"");
                    cbuValidationImageResponse.setHeight(7);
                    cbuValidationImageResponse.setBreadth(7);
                    cbuValidationImageResponse.setLength(7);

                    callback.onResponse(mockedCall, Response.success(cbuValidationImageResponse));
                    // or callback.onResponse(mockedCall, Response.error(404. ...);
                    // or callback.onFailure(mockedCall, new IOException());
                    return null;
                }
            }).when(mockedCall).enqueue(any(Callback.class));

            ValidateCbuRepository validateCbuRepository = new  ValidateCbuRepository();
            String encodedString= """";
            validateCbuRepository.processImage(encodedString).observeForever(observer); 
</code></pre>

<p>Getting a null pointer exception at <code>validateCbuRepository.processImage(encodedString).observeForever(observer)</code>. Next step is to verify the observer.</p>

<p>I expect the test to pass. What am i doing wrong here?. I did something similar foe view model and the test passes with 100% code coverage.</p>

<p>The retrofit call is asynchronous. Is that the reason why it fails?</p>

<p>Edit : It seems livedata is null while testing causing NPE.</p>
",https://stackoverflow.com/questions/54455699/unit-testing-respository-with-in-mvvm-pattern-android,"['java', 'android', 'unit-testing', 'android-mvvm']",2940,False,2,0
Unit testing with xunit that involves dynamo db,"<p>I have a .net core api project where I am connecting to dynamo db as my database.
I also have few endpoints for getting data, saving data and deleting data from dynamo db. Now I wanted to write unit test cases for those endpoints.
Unit testing that I am able to get correct data, data correctly saves to dynamo db, data correctly gets deleted from dynamo db.</p>

<p>To get started with this, I came across the following post at stackoverflow and I have a similar setup already:
<a href=""https://stackoverflow.com/questions/52879141/net-core-testing-with-xunit"">.Net core testing with Xunit</a></p>

<p>I have a few questions based on the accepted answer in the above post:</p>

<p>The user in the above post is using MOQ to moq up data and pass to its dynamodb manager to set it up which means for example we can mock our model as per below test</p>

<pre><code>[Fact]
public async Task GetAllData_ShouldGetAll()
{
    var searchResult = new List&lt;MyModel&gt;()
    {
        new MyModel() {FirstName = ""abc"", LastName=""def"", Address = ""123 street"", UpdatedBy = ""abc""},
        new MyModel() {FirstName = ""ghj"", LastName=""asd"", Address = ""56 street"", UpdatedBy = ""ghj""}
    };
    _dbManager
        .Setup(_ =&gt; _.GetAsync(It.Is&lt;List&lt;ScanCondition&gt;&gt;(list =&gt; list.Count == 2)))
        .ReturnsAsync(searchResult);


     // Act
     var okResult = _setController.GetAllData().Result as OkObjectResult;

     // Assert
    var items = Assert.IsType&lt;List&lt;MyModel&gt;&gt;(okResult.Value);
    Assert.Equal(2, items.Count);
}
</code></pre>

<p>As per above test since our model is setup with 2 records, the above test returns true as we are checking items count to be 2.</p>

<p>Ques:
- Is this the correct way to mock?
- Is this the correct way to write the test and check if it returns all data from db.</p>

<p>Now the above is all about mocking. What if I dont want to mock and use actual database to check and run my tests. How can I do that.</p>

<p>I tried setting up my test contructor as below:</p>

<pre><code>public class ValuesControllerTests
{
      private ValuesController _valuesController;
      private readonly IDynamoDbManager&lt;MyModel&gt; _dbManager;
      public ValuesControllerTests()
      {

            _dbManager = mockRepository.Create&lt;IDynamoDbManager&lt;MyModel&gt;&gt;();

            _valuesController = new ValuesController(options, _dbManager);      

      } 
}
</code></pre>

<p>But my _dbManager is always null, I am not sure how to set this up correctly.</p>

<p>My final question:
- Which is a better approach: using moq for testing or using live connection.</p>

<p>Sorry for long post but I wanted to clear out things and follow correct approach.</p>

<p>Anyone for inputs?</p>
",https://stackoverflow.com/questions/54395375/unit-testing-with-xunit-that-involves-dynamo-db,"['unit-testing', 'amazon-dynamodb', 'moq', 'xunit', 'xunit.net']",488,False,2,0
Use Predicate as a Argument for Unit Testing,"<p>I currently have a function that uses the data type predicate as one of the parameters for the function. See below:</p>

<pre><code>@RequestMapping(method = GET)
function getAll(WebRequest request, @QuerydslPredicate(root = Image.class) Predicate predicate, @PageableDefault Pageable pageable) {
   return ""test""
}
</code></pre>

<p>However, I am currently writing Unit test to test the validity of this function, and I'm having a hard time trying to pass a argument for the Predicate into this function so I can test. Can someone please assist?? This is the test function I have so far:</p>

<pre><code> @RunWith(MockitoJUnitRunner.class)
 public class ImageTest {

 private Predicate predicate;

 @InjectMocks
ImageController imageController = new ImageController(); 

 @Test
public void testGetAll() throws Exception {
    WebRequest webRequest = mock(WebRequest.class);

    ResponseEntity responseEntity = ok(new PagedResponse&lt;&gt;(page));
    when(imageController.getAll(Mockito.eq(webRequest), Mockito.eq(predicate), any(Pageable.class)))
            .thenReturn(responseEntity);
   }
}
</code></pre>

<p>In this instance, predicate is null because I'm not sure what to set as the argument</p>
",https://stackoverflow.com/questions/54770714/use-predicate-as-a-argument-for-unit-testing,"['java', 'unit-testing', 'spring-boot', 'mockito', 'predicate']",2391,True,1,1
Unit testing an async method that uses System.Threading.Timer,"<p>In .NET Core, background tasks are implemented as <a href=""https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2&amp;tabs=visual-studio"" rel=""nofollow noreferrer"">IHostedService</a>. This is my hosted service:</p>

<pre><code>public interface IMyService {
    void DoStuff();
}

public class MyHostedService : IHostedService, IDisposable
{
    private const int frequency;

    private readonly IMyService myService;

    private Timer timer;

    public MyHostedService(IMyService myService, Setting s)
    {
        this.myService = myService;
        frequency = s.Frequency;
    }

    public void Dispose()
    {
        this.timer?.Dispose();
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        this.timer = new Timer(this.DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(this.frequency));
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        this.timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        try
        {
            this.myService.DoStuff();
        }
        catch (Exception e)
        {
            // log
        }
    }
}
</code></pre>

<p>I am trying to unit test this class, and all I want is to make sure <code>DoStuff</code> gets called when <code>StartAsync</code> method is called. This is my unit test:</p>

<pre><code>[TestFixture]
public class MyHostedServiceTests
{
    [SetUp]
    public void SetUp()
    {
        this.myService = new Mock&lt;IMyService&gt;();

        this.hostedService = new MyHostedService(this.myService.Object, new Setting { Frequency = 60 });
    }

    private Mock&lt;ImyService&gt; myService;
    private MyHostedService hostedService;

    [Test]
    public void StartAsync_Success()
    {
        this.hostedService.StartAsync(CancellationToken.None);

        this.myService.Verify(x =&gt; x.DoStuff(), Times.Once);
    }
}
</code></pre>

<p>Why is this failing?</p>
",https://stackoverflow.com/questions/57908482/unit-testing-an-async-method-that-uses-system-threading-timer,"['c#', 'unit-testing', 'nunit', 'moq']",837,True,1,1
Unit testing vue routing with b-button &quot;to&quot;,"<p>I have a component that contains a b-button component from Vue Bootstrap. In my the unit test, I want to check that when I click that button within the component, I get routed to the url I specified in the ""to"" prop I'm passing to b-button.</p>

<p>My problem is the routing is not being triggered in my unit test. Or b-button / router-link within it aren't using the my router instance.</p>

<p>How can I test this? Do I even need to? I've simplified my examples - I know that the ""to"" functionality is covered by b-button's own unit tests, but I wanted to test that I'm passing the correct url to it.</p>

<p>Demo component</p>

<pre><code>&lt;template&gt;
    &lt;b-card
        header=""Button demo""
    &gt;
        &lt;b-button
            class=""test""
            v-bind:to=""toPath""
        &gt;Test&lt;/b-button&gt;
    &lt;/b-card&gt;
&lt;/template&gt;

&lt;script&gt;
export default {

    name: 'ButtonDemo',

    data(){
        return {
            toPath: '/expected/path'
        }
    }

}
&lt;/script&gt;
</code></pre>

<p>Unit test</p>

<pre><code>import { mount, createLocalVue } from '@vue/test-utils'
import ButtonDemo from '@/path/to/ButtonDemo'
import BootstrapVue from 'bootstrap-vue'
import Vuex from 'vuex'
import VueRouter from 'vue-router'

const localVue = createLocalVue()

localVue.use(VueRouter)
const router = new VueRouter()

localVue.use(BootstrapVue)

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

    let $wrapper

    test('Clicking ""new"" takes you to the create flow', async () =&gt; {

        $wrapper = mount(ButtonDemo, { localVue, router })

        $wrapper.find('.test').trigger('click')

        expect($wrapper.vm.$route.path).toBe('/expected/path')

    })

})
</code></pre>
",https://stackoverflow.com/questions/59055263/unit-testing-vue-routing-with-b-button-to,"['unit-testing', 'vue.js', 'vue-router', 'bootstrap-vue', 'vue-test-utils']",1716,True,1,1
unit testing the interceptor with axios throws error,"<p>I'm writing Unit test for my Nestapp. For the interceptor file, I'm writing a test case to throw an error when <code>error.message.indexOf('timeout') &gt;= 0</code> and call <code>Axios.Cancel</code> with the error message.</p>
<p>But in my spec file I get :  <code>Cannot read property 'intercept' of undefined</code>
PFB my code and what am I missing here?</p>
<p>Can provide any mocks if required!</p>
<h3>timeout.interceptor.ts</h3>
<pre><code>import {
    Injectable,
    NestInterceptor,
    CallHandler,
    HttpCode
} from '@nestjs/common';
import {
    Observable
} from 'rxjs';
import Axios from 'axios';


@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
    intercept(context: any, next: CallHandler): Observable &lt;any&gt; {

        const CancelToken = Axios.CancelToken;
        const source = CancelToken.source();

        const url: string = context.url ? context.url : context.args[0].url;
        Axios.defaults.timeout = 200;


        Axios.get(url, {
            cancelToken: source.token
        }).then((res) =&gt; {}, error =&gt; {
            if (error.message.indexOf('timeout') &gt;= 0) {
                throw new Axios.Cancel('Operation canceled due to timeout!');
            }
        }).catch((error) =&gt; {
            if (Axios.isCancel(error)) {
                console.log('Request canceled ', error);
            } else {
                console.log('--else part--');
            }
        });
        return next.handle();
    }
}
</code></pre>
timeout.interceptor.spec.ts
<pre><code>import {
    Test,
    TestingModule
} from '@nestjs/testing';
import {
    HttpModule,
    Controller,
    ExecutionContext,
    Get,
    InternalServerErrorException
} from '@nestjs/common';
import {
    of ,
    Observable,
    throwError
} from 'rxjs';
//import { Reflector } from '@nestjs/core';
import Axios from 'axios';

describe('Content Service', () =&gt; {
    let module: TestingModule;
    //let reflector;
    let timeoutInterceptor;
    //const loggerSpy = jest.fn()
    let getSpy;
    let cancelSpy;
    const errCode = 'MockController#decorated';
    const errMessage = 'Controller threw an error';


    beforeEach(async () =&gt; {
        module = await Test.createTestingModule({
            imports: [HttpModule],

        }).compile();

        getSpy = jest.spyOn(Axios, 'get');
        timeoutInterceptor = new timeoutInterceptor();
    })

    it('should call Axios.Cancel when it catches an timeout&gt;0', done =&gt; {

        const context = {
            url: ''
        }
        timeoutInterceptor.intercept(context, throwError(new InternalServerErrorException()))
            .subscribe(
                () =&gt; {},
                () =&gt; {
                    expect(Axios.Cancel).toHaveBeenCalled();
                    done();
                }
            )
            .unsubscribe();
    });

});
</code></pre>
",https://stackoverflow.com/questions/55816450/unit-testing-the-interceptor-with-axios-throws-error,"['javascript', 'node.js', 'typescript', 'jestjs', 'nestjs']",3274,True,1,1
Creating MOCK UP Data for Neo4j Unit testing,"<p>I want to do unit testing for my application in neo4j with java code .We are writing junit test cases for it. But we want when we run the junit test cases it should not communicate it to the main database rather then some other mockup data. </p>

<p><strong>We are using neo4j server and no embedded database is used.</strong></p>

<blockquote>
  <p>How could this be achieved?</p>
  
  <p>How can we create mockup data for testing neo4j related code?</p>
  
  <p>How to create a mocked database for unit testing so that main database
  not be touched.</p>
  
  <p>Is there any tool to mock the main database or we have to do it
  manually through the code?</p>
</blockquote>
",https://stackoverflow.com/questions/56017824/creating-mock-up-data-for-neo4j-unit-testing,"['unit-testing', 'neo4j', 'junit5']",1663,True,1,1
EF Core Logging SQL Queries when Unit Testing,"<p>I'm running some unit tests (NUnit) on my <code>DbContext</code> (to an Oracle database) in EF Core 2.2 and I'd like to see the <code>SQL</code> queries it's constructing for each unit test, preferably </p>

<ul>
<li>in the Debug window <em>and</em> </li>
<li>in the Test Explorer pane's detail view of each test.</li>
</ul>

<p>I have a Unit Test similar to:</p>

<pre><code>[SetUp]
public void Setup()
{
    var options = new DbContextOptionsBuilder&lt;MyContext&gt;()
        .UseOracle(""some connection string"")
        .Options;

    _context = new MyContext(options);
}
[Test]
public void We_can_count_all_the_things()
{
    var count = _context.Things.Count();

    Assert.That(count, Is.GreaterThan(0));

    // something like this for Test output:
    Assert.Pass($""SQL QUERY:{???}"")
}
</code></pre>

<p>... or maybe I can use an <code>ILogger</code> to direct output to the test result or some magic I'm unaware of.</p>

<p>Any assistance is appreciated.</p>
",https://stackoverflow.com/questions/57633746/ef-core-logging-sql-queries-when-unit-testing,"['c#', 'unit-testing', 'logging', 'nunit', 'ef-core-2.2']",3926,True,2,2
ctor is not a constructor. Angular7 unit testing,"<p>I am writing a unit test case for a component which uses a service.
While testing i am getting following error:</p>

<p><code>ctor is not a constructor</code></p>

<p>How to resolve this error?</p>

<p><a href=""https://i.stack.imgur.com/qtebS.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/qtebS.png"" alt=""ctor is not a constructor - error screenshot""></a></p>
",https://stackoverflow.com/questions/54825852/ctor-is-not-a-constructor-angular7-unit-testing,"['angular', 'jasmine', 'angular7']",1579,True,1,1
Unit-testing - TypeError: &#39;dict&#39; object is not callable,"<p>I am new to databases in general, so sorry if this question  is too basic.</p>

<p>I'm trying to test a <code>Playlist</code> model which has a relationship with a <code>Track</code> model.</p>

<pre><code>class Track(db.Model):
    """"""
    Model for storing track information
    """"""
    id = db.Column(db.Integer, primary_key=True)
    artist = db.Column(db.String(140))
    title = db.Column(db.String(140))
    created = db.Column(db.DateTime, default=func.now())
    track_id = db.Column(db.String(140))
    tempo = db.Column(db.Float)      
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))

    def __init__(self, title, artist, uri):
        self.title = title
        self.artist = artist
        self.uri = uri

    @property
    def serialize(self):
       """"""Return object data in easily serializeable format""""""
       return {
           'id' : self.id,
           'title': self.title,
           'artist': self.artist,
           'track_id': self.track_id,
            'tempo':self.tempo
       } 
</code></pre>

<p>and then I have this secondary table:</p>

<pre><code>tracks = db.Table('tracks',
    db.Column('track_id', db.Integer, db.ForeignKey('track.id')),
    db.Column('playlist_id', db.Integer, db.ForeignKey('playlist.id')))
</code></pre>

<p>here, the <code>Playlist</code> Model:</p>

<pre><code>class Playlist(db.Model):
    """"""
    Model for storing playlist information belonging to a specific user
    """"""
    __tablename__ = 'playlist'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50))
    created = db.Column(db.DateTime, default=func.now())    
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))

    tracks = db.relationship('Track', 
                            secondary=tracks,
                            backref=db.backref('playlists', 
                            lazy='dynamic'))

    def __init__(self, title):
        self.title = title

    @property
    def serialize(self):
       """"""Return object data in easily serializeable format""""""
       return {
           'id' : self.id,
           'created' : self.created,
           'title': self.title,
           'tracks': [ item.serialize for item in self.tracks]
       }
</code></pre>

<p>and now I'm trying to test <code>Playlist</code>, like so:</p>

<p><strong>test_playlist_model.py</strong></p>

<pre><code>import unittest
# third party libs
from sqlalchemy.exc import IntegrityError
# application modules
from project.api.models.base import db
from project.api.models.all import Playlist, tracks
from project.tests.base import BaseTestCase
from project.tests.utils import add_playlist


class TestPlaylistModel(BaseTestCase):

    def test_add_track(self):

        track = add_track(title='Karma Police',
                          artist='Radiohead',
                          uri='spofity:test')

        self.assertEqual(track.title, 'Karma Police')
        self.assertEqual(track.artist, 'Radiohead')
        self.assertEqual(track.uri, 'spofity:test')


    def test_add_playlist(self):

        track = add_track(title='Karma Police',
                          artist='Radiohead',
                          uri='spofity:test')

        playlist = add_playlist(title='Alternative')
        self.assertEqual(playlist.title, 'Alternative')
        self.assertTrue(playlist.id)
        self.assertEqual(playlist.tracks, track.serialize())

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

<p><strong>utils.py</strong></p>

<pre><code>from project.api.models.base import db
from project.api.models.all import Playlist

def add_playlist(title):
    playlist = Playlist(
        title=title)
    db.session.add(playlist)
    db.session.commit()
    return playlist

def add_track(title, artist, uri):
    track = Track(
                title=title,
                artist=artist,
                uri=uri
            )
    db.session.add(track)
    db.session.commit()
    return track
</code></pre>

<p>but I'm getting:</p>

<pre><code>======================================================================
ERROR: test_add_playlist (test_playlist_model.TestPlaylistModel)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""/usr/src/app/project/tests/test_playlist_model.py"", line 34, in test_add_playlist
    self.assertEqual(playlist.tracks, track.serialize())
TypeError: 'dict' object is not callable
</code></pre>

<p>what am I missing?</p>
",https://stackoverflow.com/questions/55801658/unit-testing-typeerror-dict-object-is-not-callable,"['unit-testing', 'flask-sqlalchemy']",248,True,1,1
How should I handle ClaimsPrincipal in unit testing?,"<p>I have a controller that checks the claims to get the current user's username, role, like so:</p>

<pre><code>var identity = ClaimsPrincipal.Current.Identities.First();
bUsername = identity.Claims.First(c =&gt; c.Type == ""Username"").Value;
role = identity.Claims.First(c =&gt; c.Type == ""Role"").Value;
</code></pre>

<p>These details are set when the user first logs in.  When I try to test this method, if falls over at the lines of code above because there was no login.  So I tried creating a principal in the TestInitialization so it would always be available for the controllers asking for the username in the above way:</p>

<pre><code>var claims = new List&lt;Claim&gt;()
{
    new Claim(ClaimTypes.Name, ""Test Name""),
    new Claim(ClaimTypes.NameIdentifier, ""test""),
    new Claim(""Username"", ""test""),
    new Claim(""Role"",""ADMIN"")
};
var identity = new ClaimsIdentity(claims, ""TestAuthType"");
var claimsPrincipal = new ClaimsPrincipal(identity);
</code></pre>

<p>I breakpointed the code, and it hits this code before it hits the above code, so it seems like it is creating the principal before checking for the username, however it still falls over on the username check, it's still not finding anything.</p>

<p>Can anybody advise me on what I'm doing wrong?</p>
",https://stackoverflow.com/questions/57922719/how-should-i-handle-claimsprincipal-in-unit-testing,"['c#', 'unit-testing']",628,True,1,1
Unit Testing Nested HTTP Calls with Angular 7,"<p>I have a service method in Angular 7 to get photos which are stored in the cloud by first requesting the google uri from the backend, and then querying the returned uri for the photo blob. Since there can be many nested photos, this process maps the blobs onto the previous media</p>

<pre><code>public getPhotos(media: Media[]): Observable&lt;any[]&gt; {
  return forkJoin(media.map((media: Media) =&gt; {

    return this.http.get&lt;any&gt;(`http://www.test.net/media/${media.mediaId}?mediaType=${media.mediaType}`).pipe(
      switchMap(data =&gt; {

        return this.http.get&lt;any[]&gt;(data.signedUrl, {
          responseType: 'blob'
        })
      })
    )
  }))
}
</code></pre>

<p>I'm trying to test this, but my tests give false positives and then error out with: <code>Cannot read property 'toLowerCase' of undefined at HttpXsrfInterceptor.intercept</code>.</p>

<p>Here are my tests:</p>

<pre><code>it('should get photos', () =&gt; {
  let api: string = 'http://www.test.net'
  let mockMedia: Media = mock(Media) // ts-mockito
  mockMedia.mediaId = '123'
  mockMedia.mediaType = 'jpg'

  let mockUri: string = 'http://google.photo.com'

  imageService.getPhotos([mockMedia], '456', api).subscribe((uri: any) =&gt; {
    expect(uri).toEqual(mockUri)
  })

  const req1 = testControl.expectOne(`${api}/media/123?mediaType=jpg`)
  expect(req1.request.method).toEqual('GET')

  // const req2 = testControl.expectOne(`${mockUri}`)
  // expect(req2.request.method).toEqual('GET')

  req1.flush(mockUri)
})
</code></pre>

<p>How can I test the nested http call and flush fake data into it? Am I doing this test wrong due to the <code>forkJoin</code>?</p>

<p>I tried nesting a flushed request inside the first subscribe like so, but that also didn't work (false positive, same error as above):</p>

<pre><code>imageService.getPhotos([mockMedia], '456', api).subscribe((uri: any) =&gt; {
    expect(uri).toEqual(mockUri)

    const req2 = testControl.expectOne(`${mockUri}`)
    expect(req2.request.method).toEqual('GET')

    req2.flush(['image1'])
  })
</code></pre>
",https://stackoverflow.com/questions/59399647/unit-testing-nested-http-calls-with-angular-7,"['angular', 'unit-testing', 'jasmine']",274,False,1,0
catchError always gets called in HTTP unit testing,"<p>I have a service that makes a HTTP call and I am trying to write tests for it. The method in the service that I am trying to test looks like this</p>

<pre><code>// my.service.ts

setUserAgreement(accept: boolean): Observable&lt;any&gt; {
  const data = { accept };

  return this.http.post&lt;any&gt;(this.url, data, this.getHttpHeader('1'))
    .pipe(
      tap(x =&gt; this.logHttp(x)),
      map(x =&gt; this.parseHttp(x)),
      catchError(this.handleErrorInternal('setUserAgreement'))
    );
}
</code></pre>

<p>My test file looks like this</p>

<pre><code>import { TestBed, async } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { myService } from './my.service';

describe('myService', () =&gt; {
  let service;
  let httpMock: HttpTestingController;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule ]
    });

    service = TestBed.get(myService);
    httpMock = TestBed.get(HttpTestingController);
  });

  describe(`#setUserAgreement`, () =&gt; {
    const mockResponse = 'Mock response';

    afterEach(() =&gt; {
      httpMock.verify();
    });

    it(`should not call handleErrorInternal when the call resolves successfully`, async(() =&gt; {
      spyOn(service, 'handleErrorInternal');
      service.setUserAgreement(true).subscribe(() =&gt; {
        expect(service.handleErrorInternal).not.toHaveBeenCalled();
      });

      const req = httpMock.expectOne(service.url);
      req.flush(mockResponse, { status: 200, statusText: 'OK' });
    }));
  });
});
</code></pre>

<p>However the test fails with the message <code>Error: Expected spy handleErrorInternal not to have been called.</code></p>

<p>Can someone please help?</p>
",https://stackoverflow.com/questions/57718654/catcherror-always-gets-called-in-http-unit-testing,"['angular', 'unit-testing', 'rxjs', 'jasmine']",830,True,1,1
Unit testing a stream that returns a stream,"<p>I'm currently trying to unit test my BLoC Flutter code but I've got a failed test because of what I'll describe as a 'nested' stream.</p>

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

<pre><code>test('fetch carbon events successfully', () async {
      final List&lt;CarbonAction&gt; actions = [];
      final List expected = [
        StateA(),
        StateB(),
        StateC()
      ];


      when(repo.getActions()).thenAnswer((_) =&gt; Stream.value(actions));

      expectLater(
        homeBloc.state,
        emitsInOrder(expected),
      );

      homeBloc.dispatch(FetchActionsEvent());
    });
</code></pre>

<p>It is failing with this error:</p>

<pre><code>Expected: should do the following in order:
          • emit an event that StateA:&lt;StateA&gt;
          • emit an event that StateB:&lt;StateB&gt;
          • emit an event that StateC:&lt;StateC&gt;
  Actual: &lt;Instance of 'BehaviorSubject&lt;State&gt;'&gt;
   Which: emitted • StateA
                  • StateB
                  • StateC
            which didn't emit an event that StateC:&lt;StateC&gt;
</code></pre>

<p>I believe this is happening because StateC actually comes a stream that is emitted using <code>async*</code> and <code>yield*</code>. In my code all of this is working currently. </p>
",https://stackoverflow.com/questions/58105343/unit-testing-a-stream-that-returns-a-stream,"['testing', 'flutter', 'dart']",241,True,1,1
Mocking Request.UserHostAddress for Unit Testing for WEB API,"<p>I am writing Unit Test for my WEB API Service. I want to mock request from ip address. I am using Microsoft Unit Test. </p>

<pre><code>[TestClass]
public class UnitTest1
{
    private Mock&lt;HttpContextBase&gt; moqContext;
    private Mock&lt;HttpRequestBase&gt; moqRequest;

    [TestMethod()]
    public void TestMethod1()
    {
       var controller = new TestController();
        controller.ControllerContext = new ControllerContext(moqContext.Object, new System.Web.Routing.RouteData(), controller);

    }
    [TestInitialize]
    public void SetupTests()
    {
        // Setup Moq
        moqContext = new Mock&lt;HttpContextBase&gt;();
        moqRequest = new Mock&lt;HttpRequestBase&gt;();
        moqContext.Setup(x =&gt; x.Request).Returns(moqRequest.Object);
        moqContext.Setup(x =&gt; x.Request.UserHostAddress).Returns(""192.111.1.1"");
    }

}
</code></pre>

<p>I don't know how to proceed further, I am getting below error.</p>

<pre><code>&gt; Severity  Code    Description Project File    Line    Suppression State
&gt; Error CS1503  Argument 3: cannot convert from
&gt; 'WebApplication1.Controllers.TestController' to
&gt; 'System.Web.Mvc.ControllerBase'   UnitTestProject1
</code></pre>

<p>Any help appreciated.
Is MOQ better than Rino, also, alternate ways for avoiding virtual methods for MOQ testing.</p>

<p>Updates 
Ok so the Controller is an API Controller as follows</p>

<pre><code>// GET: api/Test
        public IEnumerable&lt;string&gt; Get()
        {
            string s =HttpContext.Current.Request.UserHostAddress;
             ...Authentication/Authorization based on IP address
            return new string[] { s };
        }
</code></pre>

<p>I want to mock HttpContext.Current.Request.UserHostAddress in my Unit test so as to test different IP address. My question is how to set the mock IP address. I have found a link <a href=""https://blog.slatner.com/geeky/mocking-request-userhostaddress-in-asp-net-mvc.html"" rel=""nofollow noreferrer"">https://blog.slatner.com/geeky/mocking-request-userhostaddress-in-asp-net-mvc.html</a>. but I couldn't figure out how to use. Any help much appreciated.</p>
",https://stackoverflow.com/questions/54104213/mocking-request-userhostaddress-for-unit-testing-for-web-api,"['c#', 'asp.net-mvc', 'unit-testing', 'moq']",1128,False,1,2
setting up unit testing arduino code in eclipse,"<p>Before retiring, I successfully introduced unit testing in Eclipse for an embedded arm cross compiled target to my team, based on the book Test-Driven Development for Embedded C by James W. Grenning</p>

<p>Now I'm wanting to do the same for my own Arduino projects, but I've hit a bit of a snag</p>

<p>I have the Eclipse Arduino plugin working on a sample project (the target project) - the functions &amp; classes to be unit tested are in a separate folder in this project (called 'application')</p>

<p>I have the CppUTest unit test libraries installed in a separate testing project
I've included the 'application' folder from the target project in this testing project</p>

<p>Now, This testing project can't immediately resolve the  include file in the target files, and if I manually include this header file into the testing project, it references other include files, and I start to disappear down a rabbit hole trying to satisfy other header file references</p>

<p>I've initially worked around this by removing  from the target functions and classes, and the only changes needed so far has been to change Arduino type defs like 'byte' to standard C 'unsigned char' - these then copile fine in both projects ad the tests run and pass</p>

<p>But I don't particularly like having to change the type defs, and would like to be able to include , and keep the code in the usual Arduino 'style'</p>

<p>So, the question is - is there a better way to do this?</p>

<p>I did think that I should be able to add the CppUTest libraries to an Arduino Eclipse project, as a test project, but there doesn't seem to be the option to add library &amp; include paths to an Arduino project like you can with a c/c++ project, and I don't see an easy way to add all the necessary Arduino header files to a standard C++ project, especially as I believe some of the headers are dependant on the Arduino platform chosen, which of course isn't supported in a standard C++ project</p>

<p>It would be nice to have a generic solution to this so that I could create other test projects with different unit testing frameworks, as my former colleagues have moved onto the Cxx unit test framework, and there are others (like google) i'd like to try</p>

<p>Looking forward to your suggestions</p>
",https://stackoverflow.com/questions/58068968/setting-up-unit-testing-arduino-code-in-eclipse,"['eclipse', 'unit-testing', 'arduino', 'tdd', 'cpputest']",62,False,1,0
Unit Testing Domain Models attributes in CQRS System,"<p>I'm seeking other's thoughts on a specific scenario re: unit testing domain model (entities, VOs etc) attributes in a App that is utilising CQRS.</p>

<p>Imagine a simplified example of a Product (entity), with a Product Name (VO).</p>

<pre><code>class Product
private ProductName productName
</code></pre>

<p>Product has some basic guard rails and invariants:</p>

<ul>
<li>A Product Name can't be more than 100 characters (enforced in the VO).</li>
<li>A Product must have a Product Name (enforced in the entity, with Product Name set in the constructor to ensure it's always valid).</li>
</ul>

<p>I can unit test the Product entity and Product Name VO to ensure these are enforced correctly by ensuring the correct errors and exceptions are raised. Easy.</p>

<p>My question is regarding Unit Testing the happy path — that the Product Name is set successfully when a Product is initially Developed.</p>

<p>In a non-CQRS system I would have a public read-only property or getter on the Product Name, so that it can be retrieved for reporting, displaying or populating a DTO. I can then unit test with this property.</p>

<p>In a CQRS system though, the Product Name can be private in the Entity, as retrieval of the Product Name happens via the Read Model on the query side. Setting the Product Name happens through the command when the product is Developed, but after that the Product Name isn't required for any core business actions (except I could imagine for renaming the product).</p>

<p>To unit test the successful creation of a product though I need to make the Product Name a read-only public property to test it, but it doesn't seem right to do this just to fulfil a unit test. Without the unit test the Product Name can remain private and everything would work as needed. </p>

<p>Wondering if anyone has come across a similar scenario for unit testing -> Where an attribute that is mostly for presentation purposes (although obviously very important... I wouldn't expect users to try and work with Products via only part numbers or identifiers) is being tested?</p>

<p>I'm leaning towards testing this via the Read Model? ie. Create the Product , then determine the name has been successfully set via the Read Model. But this seems to be a lot for a unit test to take on.</p>
",https://stackoverflow.com/questions/54185538/unit-testing-domain-models-attributes-in-cqrs-system,"['unit-testing', 'domain-driven-design', 'cqrs', 'accessor']",438,True,1,1
How to set Cypress up for unit testing?,"<p>I'm checking out Cypress as a testing framework.  However, I'm having trouble following the basic setup to test some application code, like some utility functions.  I followed the link here <a href=""https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/unit-testing__application-code"" rel=""nofollow noreferrer"">https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/unit-testing__application-code</a></p>

<p>Here's the given code I'd like to test (COPIED FROM EXAMPLE).</p>

<p>src/lib/math:</p>

<pre><code>export default {
  add: (a, b) =&gt; {
    return a + b
  },

  subtract: (a, b) =&gt; {
    return a - b
  },

  divide: (a, b) =&gt; {
    return a / b
  },

  multiply: (a, b) =&gt; {
    return a * b
  }
}
</code></pre>

<p>Here's my test: 
cypress/integration/unit.spec.js:</p>

<pre><code>import {add} from '../../src/lib/math';  &lt;---I'd like to use aliases!

context('math.js', function() {
  if('can add numbers', function() {
    expect(add(1,2)).to.eq(3)
  })
})
</code></pre>

<p>But when I run it I get this error:</p>

<pre><code> Oops...we found an error preparing this test file:
/home/terry/myProjects/tester/cypress/integration/unit.spec.js
This occurred while Cypress was compiling and bundling your test code. This is usually caused by:

A missing file or dependency
A syntax error in the file or one of its dependencies
Fix the error in your code and re-run your tests.
</code></pre>

<p>It seems to not be importing the file like in the example.  What setup step did I miss?  I'm using webpack. </p>

<p>Also, is it possible to use webpack's module resolve alias feature within the integration tests?  To avoid ""../../../"" etc?</p>

<p>EDIT: For completeness, here's my babel and webpack and package.json setup:</p>

<p>.babelrc</p>

<pre><code>{
      ""presets"": [
         ""@babel/preset-react"",
         ""@babel/preset-env""
      ],
      ""plugins"": [
        ""@babel/plugin-proposal-object-rest-spread"",
        ""babel-plugin-webpack-alias""
      ]
    }
</code></pre>

<p>webpack.config.js</p>

<pre><code>const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require(""mini-css-extract-plugin"");

const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './src/index.html',
  filename: 'index.html',
  inject: 'body'
})

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'app.bundle.js'
  },
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist'
  },
  module: {
   rules: [
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: {
            loader: ""babel-loader""
          }
        },
        {
          test: /\.html$/,
          use: [
            {
              loader: ""html-loader"",
              options: { minimize: true }
            }
          ]
        },

        {
          test: /\.(scss|sass|css)$/,
          use: [
              MiniCssExtractPlugin.loader,
              { loader: 'css-loader' },
              { loader: 'postcss-loader',
                  options: {
                    plugins: () =&gt; [autoprefixer({ grid: false})]
                  }
              },
              {
                loader: 'fast-sass-loader',
                options: {
                  includePaths: [  path.resolve(__dirname, 'src'), path.resolve(__dirname, 'src','styles') ,'./node_modules', '/node_modules/materialize-css/sass/components'],
                  sourceMap: true
                }
              }
          ]

        },
        {
          test: /\.(jpg|png)$/,
          loader: 'url-loader',
          options: {
            limit: 8192 // inline base64 URLs for &lt;=8k images, direct URLs for the rest
          },
        },
        {    
          test: /\.svg/,
          use: {
            loader: 'svg-url-loader',
            options: {}
          }
        },
         {
            test: /\.mp3$/,
            loader: 'file-loader'
        },

      ]
  },
  resolve: {
    alias: {
      components: path.resolve(__dirname, 'src', 'components'),
      routes: path.resolve(__dirname, 'src', 'routes'),
      styles: path.resolve(__dirname, 'src', 'styles'),
      lib: path.resolve(__dirname, 'src', 'lib')
    },
  },
  devtool: 'source-map',
  plugins: [HtmlWebpackPluginConfig]
 }
</code></pre>

<p>package.json</p>

<pre><code>{
  ""name"": ""react-cypress-boilerplate"",
  ""version"": ""1.0.0"",
  ""description"": """",
  ""main"": ""index.js"",
  ""scripts"": {
    ""build"": ""webpack"",
    ""watch"": ""webpack --watch --mode development --port 8080"",
    ""dev"": ""webpack-dev-server --open"",
    ""test"": ""cypress open""
  },
  ""keywords"": [],
  ""author"": """",
  ""license"": ""ISC"",
  ""dependencies"": {
    ""axios"": ""^0.18.0"",
    ""concurrently"": ""^4.1.0"",
    ""react"": ""^16.8.4"",
    ""react-dom"": ""^16.8.4"",
    ""react-router-dom"": ""^5.0.0""
  },
  ""devDependencies"": {
    ""@babel/core"": ""^7.4.0"",
    ""@babel/plugin-proposal-object-rest-spread"": ""^7.4.0"",
    ""@babel/preset-env"": ""^7.4.2"",
    ""@babel/preset-react"": ""^7.0.0"",
    ""@cypress/webpack-preprocessor"": ""^4.0.3"",
    ""autoprefixer"": ""^9.5.0"",
    ""babel-loader"": ""^8.0.5"",
    ""babel-plugin-webpack-alias"": ""^2.1.2"",
    ""css-loader"": ""^2.1.1"",
    ""cypress"": ""^3.2.0"",
    ""fast-sass-loader"": ""^1.4.7"",
    ""file-loader"": ""^3.0.1"",
    ""html-loader"": ""^0.5.5"",
    ""html-webpack-plugin"": ""^3.2.0"",
    ""mini-css-extract-plugin"": ""^0.5.0"",
    ""postcss-loader"": ""^3.0.0"",
    ""style-loader"": ""^0.23.1"",
    ""svg-url-loader"": ""^2.3.2"",
    ""url-loader"": ""^1.1.2"",
    ""webpack"": ""^4.29.6"",
    ""webpack-cli"": ""^3.3.0"",
    ""webpack-dev-server"": ""^3.2.1""
  }
}
</code></pre>

<p>EDIT: Here's the plugins file for Cypress below. I've tried both with and without it.</p>

<p>plugins/index.js</p>

<pre><code>const webpack = require('@cypress/webpack-preprocessor')

module.exports = (on, config) =&gt; {
  const options = {
    // send in the options from your webpack.config.js, so it works the same
    // as your app's code
    webpackOptions: require('../../webpack.config'),
    watchOptions: {},
  }
// `config` is the resolved Cypress config

  on('file:preprocessor', webpack(options));

}
</code></pre>
",https://stackoverflow.com/questions/55305071/how-to-set-cypress-up-for-unit-testing,"['unit-testing', 'cypress']",2144,False,1,0
Unit testing of a Sitecore item using fakeDb,"<p>I am currently trying to create a unit test for an override I made, but unit testing seems a bit more difficult than I expected. </p>

<pre><code>public class Extension
{
    public fallback(HttpContext context)
    {
       return new HttpContext();
    }  

    public IEnumerable&lt;SiteDefinition&gt; RunOn =&gt; new[]
    {
       ""Some"", ""Dome"", ""Gone""
    };

    public bool AllowedOnSite(string site)
    {
        bool allowed = RunOn.Any(sd =&gt; sd.Name == site);
        return allowed;
    }

    protected bool Process(HttpContext context)
    {
        var site = Context.Site.Name;
        if (Context.Domain.Name == ""sitecore"" || !AllowedOnSite(site))
        {
            return fallback(context);
        } 
     ....

    }
</code></pre>

<p>I seem to have a problem with <code>AllowedOnSite</code>, I can unit test it by itself, but not as part of <code>Process</code>, which is needed to unit test the rest of the code. </p>

<p>How do I include <code>AllowedOnSite</code> as always <code>true</code>, as part of the unit test for <code>Process</code>?</p>

<p>Unit test: </p>

<pre><code>    [Theory]
    [CustomAutoData(""Gonw"")]
    public void AllowedOnSite_IncorrectSite_ReturnFalse(string site)
    {
        //arrange
        var processor = new MediaRequestExtensions();

        //act
        processor.AllowedOnSite(site);

        //assert
        Assert.False(processor.AllowedOnSite(site));
    }
</code></pre>

<p>This works as expected, but I don't know how to make this condition <code>true</code>, when I run the <code>Process</code> method.</p>

<pre><code>[Theory]
[CustomAutoData(""http://gonw.com"",""Gonw"")]
public void Process_RequestURLIsIncorrect_Return(string url, string name)
{
    // Arrange
    var fakeSite = new Sitecore.FakeDb.Sites.FakeSiteContext(new Sitecore.Collections.StringDictionary
    {
        { ""name"", ""Some"" },
        { ""b"", ""Dome"" },
        { ""c"", ""Gone"" }
    });
    HttpRequest httpRequest = new HttpRequest(string.Empty, url, string.Empty);
    HttpResponse httpResponse = new HttpResponse(new StringWriter());
    HttpContext httpContext = new HttpContext(httpRequest, httpResponse);

    var processor = new MediaRequestExtensionsMock
    {
        GetHttpContextFunc = () =&gt; httpContext
    };
    using (new Db())
    {
        using (new Sitecore.Sites.SiteContextSwitcher(fakeSite))
        {
            Sitecore.Context.Site.Name = name;
            // Act
            processor.Process(httpContext);

            // Assert
            Assert.Equal(string.Empty, httpContext.Response.Output.ToString());
        }
    }
}
</code></pre>

<p>I trigger the right <code>if</code> statement in this test, but if I want to trigger the next one, I shouldn't trigger the first one, which I can't seem to do. </p>

<p>Could you please advise me?</p>
",https://stackoverflow.com/questions/54028213/unit-testing-of-a-sitecore-item-using-fakedb,"['c#', 'unit-testing', 'sitecore']",256,False,1,0
ionic errors with unit testing ionic 4 app,"<p>I am trying to write the most basic of unit tests like this one here </p>

<pre><code>it('should create the app', async(() =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
}));
</code></pre>

<p>and I always get errors like</p>

<blockquote>
  <p>Failed: Template parse errors: Can't bind to 'routerLink' since it
  isn't a known property of 'ion-item'.
  1. If 'ion-item' is an Angular component and it has 'routerLink' input, then verify that it is part of this module.
  2. If 'ion-item' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
  3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (""ggle auto-hide=""false""
  *ngFor=""let p of appPages"">
              ][routerLink]=""[p.url]"">
                
            ""): ng:///DynamicTestModule/AppComponent.html@6:49 The pipe 'translate' could not be found (""
                
                    [ERROR ->]             {{ p.title | translate }}
                
               ""</p>
</blockquote>

<p>it's like ng test unit tests doesn't accept any ionic elements in html? I am importing indeed the forms module and the ionic module in my spec file.</p>
",https://stackoverflow.com/questions/55741860/ionic-errors-with-unit-testing-ionic-4-app,"['angular', 'ionic-framework']",494,True,1,1
Unit Testing for IBM MFP 8 - Javascript Adapters,"<p>Is there any possibility to write Unit Testing on MFP 8 Javascript adapters using Jasmine/Karma/JUnit ?</p>

<p>I heard that Unit testing can be done for IBM MFP 8 - JAVA adapters</p>

<p>Is it possible ?</p>
",https://stackoverflow.com/questions/57474478/unit-testing-for-ibm-mfp-8-javascript-adapters,['ibm-mobilefirst'],66,False,1,0
Suggestions for unit testing external cli tool (phpunit),"<p>I am currently working on PHP project where I need to wrap external CLI tool that does something (not really important what that something is). I would like to unit test all that.</p>

<p>For example if I have a code that does this:</p>

<pre class=""lang-php prettyprint-override""><code>function foo($cmdpath, $param1, $param2) {
  $output = [];
  $result = 0;
  exec(
   sprintf(
     '%s %s %s',
     escapeshellcmd($cmdpath),
     escapeshellarg($param1),
     escapeshellarg($param2)
   ),
   $output,
   $result
  );
  if ($result == 0) {
    echo 'We are ok!'
  }
}
</code></pre>

<p>This code assumes that command specified in <code>$cmdpath</code> exists and that it will return numeric result depending on execution result.</p>

<p>Should I just wrap exec into something else and make it behave differently when executed under PHPUNIT?</p>

<p>Can anybody suggest the reasonable strategy for doing this?</p>
",https://stackoverflow.com/questions/58348205/suggestions-for-unit-testing-external-cli-tool-phpunit,"['php', 'unit-testing', 'phpunit']",26,False,1,0
webdriverio 5 for unit testing and functional testing,"<p>I have a  project that is written using node and webpack. </p>

<p>I am writing tests for the application and as the output of my application is a visualization, I went with webdriverio 5 and it is running great(functional testing). However when I add unit tests, it is just failing although in the test reporter it shows that it is false, the logs tell that it FAILED. </p>

<p>Here is how my package.json file looks like</p>

<pre><code>{
  ""name"": ""webdriverio-test"",
  ""version"": ""1.0.0"",
  ""description"": """",
  ""main"": ""app/index.js"",
  ""scripts"": {
""install-selenium"": ""./node_modules/.bin/selenium-standalone install"",
""start-selenium"": ""./node_modules/.bin/selenium-standalone start"",
""test"": ""./node_modules/.bin/wdio wdio.conf.js"",
""allure-report"": ""allure generate allure-results --clean &amp;&amp; allure open""
  },
  ""keywords"": [],
  ""author"": """",
  ""license"": ""ISC"",
  ""devDependencies"": {
    ""@wdio/allure-reporter"": ""^5.12.1"",
    ""@wdio/cli"": ""^5.12.5"",
    ""@wdio/local-runner"": ""^5.12.5"",
    ""@wdio/mocha-framework"": ""^5.12.1"",
    ""@wdio/selenium-standalone-service"": ""^5.12.1"",
    ""@wdio/sync"": ""^5.12.3""
     }
    }
</code></pre>

<p>Here is how my test file looks like</p>

<pre><code>const assert = require('assert'); 
const index = require('../../app/index').default 

describe('test browser', function () { 
    it('should have the right title', function ()  { 
        browser.url('https://webdriver.io'); 
        const title = browser.getTitle(); 
        //assert.strictEqual(title, 'WebdriverIO · Next-gen WebDriver test framework for Node.js'); 
        console.log(""**********I am here*************""); 
        assert.equal(5,5); 
    }); 
}); 


describe('test code', function () { 
    it('should have do the right thing', function ()  { 
        const c = index.add(3,4); 
        assert.equal(c, 7); 
    }); 
}); 
</code></pre>

<p>When I run this code using webdriverio command I get the following stack trace</p>

<pre><code>&gt; webdriverio-test@1.0.0 test /Users/adsf/Desktop/test_scripts/webdriverio-test
&gt; wdio wdio.conf.js


Execution of 1 spec files started at 2019-09-06T15:21:35.952Z

2019-09-06T15:21:35.979Z INFO @wdio/cli:Launcher: Run onPrepare hook
2019-09-06T15:21:36.093Z ERROR @wdio/cli:utils: A service failed in the 'onPrepare' hook
Error: Could not request headers from       https://chromedriver.storage.googleapis.com/2.43/chromedriver_mac64.zip: Error: read ECONNRESET
at Request.&lt;anonymous&gt; (/Users/adsf/Desktop/test_scripts/webdriverio-test/node_modules/selenium-standalone/lib/install.js:552:8)
at Object.onceWrapper (events.js:286:20)
at Request.emit (events.js:198:13)
at Request.EventEmitter.emit (domain.js:448:20)
at Request.onRequestError (/Users/adsf/Desktop/test_scripts/webdriverio-test/node_modules/request/request.js:881:8)
at ClientRequest.emit (events.js:198:13)
at ClientRequest.EventEmitter.emit (domain.js:448:20)
at TLSSocket.socketErrorListener (_http_client.js:392:9)
at TLSSocket.emit (events.js:198:13)
at TLSSocket.EventEmitter.emit (domain.js:448:20)

Continue...
2019-09-06T15:21:36.096Z INFO @wdio/local-runner: Start worker 0-0 with arg: wdio.conf.js
[0-0] RUNNING in chrome - /test/specs/basic.js
[0-0] 2019-09-06T15:21:36.381Z INFO @wdio/local-runner: Run worker command: run
[0-0] 2019-09-06T15:21:36.434Z INFO webdriver: [POST] http://127.0.0.1:4444/wd/hub/session
[0-0] 2019-09-06T15:21:36.434Z INFO webdriver: DATA { capabilities:
   { alwaysMatch: { browserName: 'chrome' }, firstMatch: [ {} ] },
  desiredCapabilities: { browserName: 'chrome' } }
[0-0] 2019-09-06T15:21:37.385Z INFO webdriver: COMMAND navigateTo(""https://webdriver.io/"")
[0-0] 2019-09-06T15:21:37.386Z INFO webdriver: [POST] http://127.0.0.1:4444/wd/hub/session/3e34d38c50817313e3bab65cf8af5e51/url
[0-0] 2019-09-06T15:21:37.386Z INFO webdriver: DATA { url: 'https://webdriver.io/' }
[0-0] 2019-09-06T15:21:38.901Z INFO webdriver: COMMAND getTitle()
[0-0] 2019-09-06T15:21:38.901Z INFO webdriver: [GET] http://127.0.0.1:4444/wd/hub/session/3e34d38c50817313e3bab65cf8af5e51/title
[0-0] 2019-09-06T15:21:38.908Z INFO webdriver: RESULT WebdriverIO · Next-gen WebDriver test framework for Node.js
[0-0] **********I am here*************
[0-0] FAILED in chrome - /test/specs/basic.js
2019-09-06T15:21:39.335Z INFO @wdio/cli:Launcher: Run onComplete hook

Spec Files:      0 passed, 1 failed, 1 total (100% completed) in 00:00:03 

2019-09-06T15:21:39.336Z INFO @wdio/local-runner: Shutting down spawned worker
2019-09-06T15:21:39.590Z INFO @wdio/local-runner: Waiting for 0 to shut down gracefully
2019-09-06T15:21:39.590Z INFO @wdio/local-runner: shutting down
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! webdriverio-test@1.0.0 test: `wdio wdio.conf.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the webdriverio-test@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
</code></pre>

<p>My question is can I run unit tests and functional tests with wdio or will it be a good idea for me to use mocha and wdio to run these tests? </p>

<p>When I just run browser tests, all the browser tests work great</p>
",https://stackoverflow.com/questions/57824864/webdriverio-5-for-unit-testing-and-functional-testing,"['javascript', 'node.js', 'unit-testing', 'functional-testing', 'webdriver-io']",1141,False,0,1
Element not found in native angular unit testing,"<p>I am trying to test my native angular application using ""Mocha""&amp; ""Appium"".simple test case is executed successfully, but facing issue while finding a UI element.</p>

<p><strong>Error: ""Error: [waitForElementByClassName(""android.widget.Button"",5000)] Element condition wasn't satisfied!""</strong></p>

<p>sample.e2e-spec.ts</p>

<pre><code>import { AppiumDriver, createDriver, SearchOptions, nsCapabilities } from ""nativescript-dev-appium"";
import { assert } from ""chai"";
const addContext = require('mochawesome/addContext');

describe(""sample scenario"", async () =&gt; {
    let driver: AppiumDriver;
    before(async function(){
        driver = await createDriver();
        nsCapabilities.testReporter.context = this; 
    });

    after(async function () {      
        console.log(""Quit driver!"");
    });

    afterEach(async function () {
        if (this.currentTest.state === ""failed"") {
            await driver.logTestArtifacts(this.currentTest.title);
        }
    });  
    it(""should find an element by type"",  async function () {    
       let button = await driver.findElementByClassName(driver.locators.button);
       console.log('button ',button);
        const message = ""customLogOut"";

        console.log('button.text()',button.text());
        assert.equal(-1,-1); // simple condition working fine.
       assert.equal(await button.text(),message);
    });
});
</code></pre>

<p><strong>appium.capabilities.json</strong></p>

<pre><code>{

    ""android18"": {
        ""platformName"": ""Android"",
        ""platformVersion"": ""9.0"",
        ""deviceName"": ""Pixel_2_XL_API_27"",
        ""avd"": ""Pixel_2_XL_API_27"",
        ""lt"": 60000,
        ""newCommandTimeout"": 720,
        ""noReset"": false,
        ""fullReset"": false,
        ""app"": ""../platforms/android/app/build/outputs/apk/debug/app-debug.apk""
    }
}
</code></pre>

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

<pre><code> &lt;Button  col=""1"" automationText=""customLogOut"" id=""customLogOut""  row='3' tap="""" text=""customLogOut""&gt;&lt;/Button&gt;
</code></pre>
",https://stackoverflow.com/questions/57040329/element-not-found-in-native-angular-unit-testing,"['mocha.js', 'appium', 'nativescript', 'angular2-nativescript']",481,False,0,1
Angular 1.5 Unit Testing Directive ng-include Template,"<p>I'm trying to test UI state of a directive that dynamically loads templates via ng-include. I was having issues with the element being undefined and after googling the fix was to simply wrap the compiled element with a parent html element i.e, div. This resolved the undefined element issue but now the element is defined as the comment node instead of the rendered template.</p>

<p><strong>directive</strong></p>

<pre><code>function myDirective(
  return {
    scope: {
      tpl: '@'
    },
    template: '&lt;ng-include src=""template""/&gt;',
    link: function(scope, elem, attr, ctrl) {
      if(scope.tpl == 'view') {
        scope.template = 'app/view.tpl.html';
      }
      if(scope.tpl == 'edit') {
        scope.template = 'app/edit.tpl.html';
      }
</code></pre>

<p><strong>parent template of directive</strong></p>

<pre><code>&lt;my-directive ng-repeat=""item in vm.myStuff track by $index"" tpl=""edit""&gt;
&lt;/my-directive&gt;
</code></pre>

<p><strong>spec</strong></p>

<pre><code>describe('myDirective', function() {
  var $rootScope, $compile, element, scope;

  beforeEach(inject(function($injector) {
    $rootScope = $injector.get(""$rootScope"");
    $httpBackend = $injector.get(""$httpBackend"");
    $compile = $injector.get(""$compile"");
    element = angular.element('&lt;div&gt;&lt;my-directive ng-repeat=""item in vm.myStuff track by $index"" tpl=""edit""&gt;&lt;/my-directive&gt;&lt;/div&gt;');
    scope = $rootScope.$new();
    // wrap scope changes using $apply
    scope.$apply(function() {
      scope.template = 'app/edit.tpl.html';
      scope.vm = {
        myStuff: [{}, {}]
      };
      $compile(element)(scope);
    });
  }));
  it(""edit template save button should be displayed"", function() {
    console.log(element.html());
    '&lt;!-- ngRepeat: item in vm.myStuff track by $index --&gt;'
  });
});
</code></pre>

<p><strong>output after adding myStuff array</strong></p>

<pre><code>&lt;div&gt;
  &lt;!-- ngRepeat: item in vm.myStuff track by $index --&gt;
      &lt;!-- ngIf: !$last &amp;&amp; item --&gt;
        &lt;my-directive ng-repeat=""item in vm.myStuff track by $index"" tpl=""edit""&gt; 
        &lt;/my-directive&gt;
      &lt;!-- end ngIf: !$last &amp;&amp; widget --&gt;
  &lt;!-- end ngRepeat: item in vm.myStuff track by $index --&gt;

      &lt;!-- ngIf: !$last &amp;&amp; item --&gt;
  &lt;!-- end ngRepeat: item in vm.myStuff track by $index --&gt;
&lt;/div&gt;
</code></pre>

<h2>UPDATE</h2>

<p>I added the data for <code>ng-repeat</code> but now see the commented directive but not the rendered <code>edit.tpl.html</code> template.</p>
",https://stackoverflow.com/questions/58701933/angular-1-5-unit-testing-directive-ng-include-template,"['angularjs', 'unit-testing', 'karma-jasmine', 'angular-directive']",180,False,0,1
Unit testing of react component with flow types,"<p>I am trying to unit test the component below but I am getting the following warning after running <code>yarn run test</code></p>

<pre><code>&gt; Warning: React.createElement: type is invalid -- expected a string
&gt; (for built-in components) or a class/function (for composite
&gt; components) b ut got: object.
</code></pre>

<p>I'm using here React 16.8 with Flow and Jest and Enzyme as a testing framework</p>

<p>I want to test that component</p>

<pre><code>// @flow

import React from 'react'
import Button from './styled'

export type Props = {
  +children: React$Node
}

const ButtonDark = ({ children }: Props) =&gt; (
  &lt;&gt;
    &lt;Button&gt;{children}&lt;/Button&gt;
  &lt;/&gt;
)

export default ButtonDark

</code></pre>

<p>using this testing file:</p>

<pre><code>import React from 'react'
import { shallow } from 'enzyme'

import ButtonDark from '.'

jest.mock('./styled', () =&gt; ({
    Button: 'Button'
}))

describe('ButtonDark', () =&gt; {
  it('renders', () =&gt; {

    const wrapper = shallow(&lt;ButtonDark&gt;{'some children'}&lt;/ButtonDark&gt;)

    expect(wrapper).toMatchSnapshot()
  })
})
</code></pre>

<p>Any ideas what can I do to fix it?</p>
",https://stackoverflow.com/questions/57699305/unit-testing-of-react-component-with-flow-types,"['javascript', 'reactjs', 'jestjs', 'enzyme', 'flowtype']",380,False,0,0
Unit testing in angular with various test data,"<p>If I need to do unit testing for any c# method with various sets of data, then I can use the <strong>Theory</strong> and <strong>InlineData</strong> to pass varios inputs for testing a method.</p>

<pre><code>[Theory]
[InlineData(""88X"", ""1234"", ""1234"", ""1234"")]
[InlineData(""888"", ""123X"", ""1234"", ""1234"")]
public void ShouldReturnInValidIfCustomerInformationDoestMatch(
    string locationId,
    string quoteBillTo,
    string quoteSoldTo,
    string quoteShipTo)
{
    ....
}
</code></pre>

<p>Similarly is there any way to unit test in <strong>Angular/Jasmine/Karma</strong> to validate the same functionality/method with various set of input data?</p>
",https://stackoverflow.com/questions/56551789/unit-testing-in-angular-with-various-test-data,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'karma-runner']",778,True,0,1
PHP Unit testing fails to pass all test,"<p>I am creating a class with some unit tests, but i am not able to pass few tests. Example is shown below.</p>

<h3>Unit Test</h3>

<pre><code>class OffsetTest extends \PHPUnit\Framework\TestCase
{


   /**
    * @dataProvider getIllegalOffsets
    * @expectedException \InvalidArgumentException
    * @param $offset
    */
   public function testIllegalParameters($offset)
    {
        new \OffsetEncodingAlgorithm($offset);

        $this-&gt;fail('Exception should be thrown');
    }
    /**
     * Data provider for {@link OffsetTest::testIllegalParameters()}
     * @return array
     */
    public function getIllegalOffsets()
    {
        return [
            [-1],
        ];
    }
}
</code></pre>

<h3>My Class</h3>

<pre><code>&lt;?php

class Offset
{
    public function __construct(int $offset = 13)
    {
       try {
            if ($offset &lt; 0) {
                throw new Exception('Exception should be thrown');
            }
        } catch (Exception $e) {
            return $e-&gt;getMessage();
        }
        $this-&gt;offset = $offset;
    }
}
</code></pre>

<p>This how the test progress go
<a href=""https://i.stack.imgur.com/VpPDs.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VpPDs.png"" alt=""enter image description here""></a></p>

<p>I want all to be passed</p>
",https://stackoverflow.com/questions/57069813/php-unit-testing-fails-to-pass-all-test,"['php', 'phpunit']",286,True,0,1
Unit testing spring webservice client Classes Inheriting WebServiceGatewaySupport,"<p>I am trying to unit test a webservice client in Spring boot. My client extends <code>WebServiceGatewaySupport</code> class and I am using <strong>Mockito</strong> framework.</p>

<p>The issue is I am unable to mock the super class method <code>getWebServiceMethod</code> </p>

<p>A quick search only explains about Integration test using spring which is not what I need<a href=""https://memorynotfound.com/spring-ws-client-side-integration-testing/"" rel=""nofollow noreferrer""> [link]</a></p>

<p>in S/O it has been suggested to Mock the entire base class, but its not  possible either since the unit tests are in same package and also I dont want to manually mock a spring class. </p>

<p>I understand <code>composition over inheritance</code> but is this a valid use case for violating this and How do we achieve this unit testing in these cases? </p>
",https://stackoverflow.com/questions/54153776/unit-testing-spring-webservice-client-classes-inheriting-webservicegatewaysuppor,"['java', 'spring', 'unit-testing', 'spring-boot', 'mockito']",436,False,0,1
Unit Testing code that uses a separate AppDomain,"<p>I have code that uses an AppDomain to dynamically load plugins. I have a private internal class called PluginFinder to do the work. This all works in the production environment, but I am now trying to write MS Unit Tests for it, and I am getting an error saying the assembly could not be found.</p>

<p>To be clear, the main class creates the AppDomain and runs the PluginFinder in it to load classes it finds with the correct Interface. Once the classes are loaded, control returns to the default AppDomain. The PluginFinder is only used during loading.</p>

<p>I use the code below to create the environment:</p>

<pre><code>            //  Create a domain to text for plugins
            AppDomain domain = AppDomain.CreateDomain(""PluginLoader"");

            //  Set PluginFinder to run in the new domain (assemblyName, typeName)
            (PluginFinder)domain.CreateInstanceAndUnwrap(
                typeof(PluginFinder).Assembly.FullName, typeof(PluginFinder).FullName);
</code></pre>

<p>PluginFinder uses a default constructor, and is a private internal class. The exception I get is below:</p>

<pre><code>    ------ Exception ------
Error:  Could not load file or assembly 'MyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
There was an error creating the Plugin Loader.
Could not load file or assembly 'MyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark&amp; stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark&amp; stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark&amp; stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Activator.CreateInstance(String assemblyString, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark&amp; stackMark)
   at System.Activator.CreateInstance(String assemblyName, String typeName)
   at System.AppDomain.CreateInstance(String assemblyName, String typeName)
   at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
   at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
   at MyClass.loadPlugins() in C:\Code\...
---- End Exception ----
</code></pre>

<p>I have found <a href=""https://stackoverflow.com/questions/9634438/run-unit-tests-in-different-appdomain-with-nunit/17247211"">this</a> solution, which suggests that NUnit runs in multiple AppDomains, which makes testing of AppDomains impossible without plugins. I'm using MS Unit Test, but I suspect that this may be the case here as well.</p>

<p>**** RESOLVED ****</p>

<p>As was mentioned in the comment below, I needed to use the overload constructor. I modified my code (shown below), and it worked.</p>

<pre><code>// Set up the AppDomainSetup
var setup = new AppDomainSetup();
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;

// Set up the Evidence
var baseEvidence = AppDomain.CurrentDomain.Evidence;

//  Create a domain to text for plugins
AppDomain domain = AppDomain.CreateDomain(""PluginLoader"", baseEvidence, setup);

//  Set PluginFinder to run in the new domain (assemblyName, typeName)
PluginFinder finder = (PluginFinder)domain.CreateInstanceAndUnwrap(
    typeof(PluginFinder).Assembly.FullName, typeof(PluginFinder).FullName);
</code></pre>
",https://stackoverflow.com/questions/54637481/unit-testing-code-that-uses-a-separate-appdomain,"['c#', 'visual-studio', 'unit-testing', 'visual-studio-2017', 'appdomain']",1571,True,0,1
Services throwing unknown provider error - Angularjs Unit Testing,"<p>I'm trying to fix some broken unit tests that were set up a long time ago. For some reason when we run the tests they all fail citing an ""unknown provider error"" that we get for every service inject. I've done a lot of searching and I can't see any apparent issue with the test. If nothing is wrong with the test, could this be a config issue? I've played around with the order the files are loaded and it doesn't seem to matter.</p>

<pre><code>""use strict"";

describe(""Catalogs controller"", function() {

  beforeEach(angular.mock.module(""photonControllersPreSession""));



  var $rootScope;

  var $scope;
  var createController;
  var $window;
  var $location;
  var loggerService;
  var catalogService;
  var feedbackService;


  beforeEach(
    inject( function(
      $controller,
      _$rootScope_,
      _$window_,
      _$location_,
      _loggerService_,
      _catalogService_,
      _feedbackService_
    ) {
      $rootScope = _$rootScope_;
      $window = _$window_;
      $location = _$location_;
      loggerService = _loggerService_;
      catalogService = _catalogService_;
      feedbackService = _feedbackService_;
      $scope = $rootScope.$new();

      spyOn(loggerService, ""info"");

      createController = function() {
        return $controller(""CatalogController"", {
          $scope: $scope,
          $location: $location,
          $window: $window,
          loggerService: _loggerService_,
          catalogService: _catalogService_,
          feedbackService: _feedbackService_
        });
      };
    })
  );


  it(""Should init"", function() {
    var catalogController = null;
    catalogController = createController();
    console.log(""test: "" + createController);


    // Just want to see if the controller is created.
    expect(catalogController).not.toBe(null);
  });
});
</code></pre>
",https://stackoverflow.com/questions/54333648/services-throwing-unknown-provider-error-angularjs-unit-testing,"['angularjs', 'unit-testing', 'jasmine', 'karma-jasmine', 'karma-runner']",46,True,0,1
scope keeps being undefined in angularjs unit-testing,"<p>I am trying to unit-testing for following code, I wrote following code for unit-testing like below, I have tried so many ways to work, but I keep getting error:</p>

<blockquote>
  <p>'Cannot read property 'num' of undefined'</p>
</blockquote>

<p>I do not know why scope is not properly set. If you have any idea about it, can you please give some advices?</p>

<pre><code>var angular = require('angular');
require('angular-mocks');

describe('test directive', function () {

    let $rootScope;
    let $compile;
    let scope;
    let newScope;
    let element;

    beforeEach(angular.mock.inject(function (_$compile_, _$rootScope_) {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
    }));

    describe('test directive', function () {

        beforeEach(function () {
            newScope = $rootScope.$new();
            element = $compile('&lt;test-directive&gt;&lt;/test-directive&gt;')(newScope);
            newScope.$digest();
            scope = element.isolateScope();
        });

        fit('scope initialized', function () {
            expect(scope.num).toEqual(1);
        });

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

<pre class=""lang-js prettyprint-override""><code>module.exports = module.directive('testDirective', ['$rootScope', '$scope', function($rootScope, $scope) {

    return {
        template: require('./test.html'),
        restrict: 'E',
        controller: [
            '$scope',
            function ($scope) {
                    $scope.num = 1

                    $scope.sum = function(a, b) {
                        return a + b;
                    }

            }]
    }
}]);
</code></pre>
",https://stackoverflow.com/questions/58735991/scope-keeps-being-undefined-in-angularjs-unit-testing,"['angularjs', 'unit-testing', 'scope', 'angularjs-scope']",133,False,0,1
Angular unit testing Filter Predicate function with Jasmine,"<p>I have a filter predicate function which I use to filter a mat-table in angular</p>

<pre><code>this.dataSource.filterPredicate = this.myService.tableFilter();

tableFilter(): (data: any, filter: string) =&gt; boolean {
    let filterFunction = function (data, filter): boolean {
      let filterValues = JSON.parse(filter);
      ... my logic ...
    };
    return filterFunction;
  }
}
</code></pre>

<p>I want to write a unit test to test this filter predicate function</p>

<pre><code>it('filter table', inject(
    [MyService],
    (service: MyService) =&gt; {

      // how to do this?
      let messageObject = service.tableFilter(dummyData, 
        getDummyFilterValues());
    }
  ));
</code></pre>

<p>How do I call the service.tableFilter function in the unit test?</p>
",https://stackoverflow.com/questions/58352615/angular-unit-testing-filter-predicate-function-with-jasmine,"['angular', 'jasmine', 'karma-jasmine', 'angular-material2']",2719,False,0,1
C# Unit testing - assert Json from Http response,"<p>I am creating web api for a songsDB and I am trying to test API GET
    methods which return a Json string of songs in a list. The get method in
    question uses a linq queries and returns the songs as expected but am
    unable to write a unit test for this method and many like it with a
    concern for code coverage also. The app is hosted on azure and the data
    is being retrieved from an sql db instance in azure.
    The method displays the 5 cheapest albums in the db in ascending order.
    Any help is greatly appreciated.</p>

<pre><code>//API GET Method
[HttpGet(""leastExpensive"")]
[ProducesResponseType(404)]
[ProducesResponseType(200)]
public ActionResult&lt;Tunes&gt; GetCheapestAlbums()
{
    var price = _context.Songs
        .OrderBy(p =&gt; p.Price)
        .Select(g =&gt; new
    {
        g.ChartPosition,
        g.Artist,
        g.Genre,
        g.Price
    }).Take(5)
    .ToList();
    if (price == null)
    {
        return NotFound();
    }
    else
    {
        return Ok(price);
    }
}
</code></pre>

<p>//Json response</p>

<pre><code>[{
    ""chartPosition"":29,""artist"":""ABBA"",""genre"":""Pop"",""price"":4.39
},{
    ""chartPosition"":60,""artist"":""Amy Whinehouse"",""genre"":""Pop"",""price"":5.05
},{
    ""chartPosition"":10,""artist"":""BB King"",""genre"":""Blues"",""price"":5.5
},{
    ""chartPosition"":15,""artist"":""Kenny Rogers"",""genre"":""Country"",""price"":5.92
},{
    ""chartPosition"":17,""artist"":""Pearl Jam"",""genre"":""Rock"",""price"":6.29
}]
</code></pre>

<p>I am looking to assert the Json string as equal</p>
",https://stackoverflow.com/questions/55405391/c-unit-testing-assert-json-from-http-response,"['c#', 'unit-testing', 'asp.net-core', 'httpresponse']",729,False,0,0
How to mock Angular service outside unit testing?,"<p>I'm developing an Angular application, since the back-end is still very behind in the development I'm building alternative fake services which provides data from local JSON files allowing me to test the full front-end of the application on my local workstation without relying on any external resource. </p>

<p>The problem is that switching from fake services to real services every time I need to test the integration with the back-end is a waste of time so I wanted something which allows me to switch between fake and real services with a simple flag on the code or on the CLI.</p>
",https://stackoverflow.com/questions/58694208/how-to-mock-angular-service-outside-unit-testing,"['angular', 'typescript', 'dependency-injection']",1317,True,0,4
Swift unit testing a method that includes timer,"<p>I am new in swift and unit testing in swift. Here in the code in MyClass I am using timer to trigger some method ..
I need to do unit testing for that method that has timer count value..
I have checked few answers. nothing worked out.
I am unable to do that. Can anyone help me out with this.
Thanks in advance.</p>

<pre><code> class MyClass(){

func triggerSecondTimer() {
    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(repeatSecondTimer), userInfo: nil, repeats: true)
}

@objc func repeatSecondTimer(){
    timerCount += 1
    if isServiceCallComplete || timerCount == secondInterval {
        timer?.invalidate()
        finishedSecondTimer()
    }
}
}
   func testSecondTimer() {

    splashScreenMock.triggerSecondTimer()
   // I want to check the timer count here..

    XCTAssertEqual(self.splashScreenMock.timerCount, 20)


}
</code></pre>
",https://stackoverflow.com/questions/59321364/swift-unit-testing-a-method-that-includes-timer,"['ios', 'swift', 'nstimer', 'swift5']",738,False,0,2
Unit testing a Friend Class from another Assembly,"<p>I have a solution which contains two assemblies, both in VB.Net. One assembly contains my code, which mainly includes <code>Friend</code> Classes; and the other assembly contains code dedicated toe unit testing the first assembly. I rely on MSTest.</p>

<p>How can I Unit Test my <code>Friend</code> Classes?</p>

<p>I have seen across several tutorials and documentation that C# has the <code>&lt;Assembly(): InternalsVisibleTo(""AssemblyName"")&gt;</code>, but I understand this is not available for VB.</p>

<p>Whilst searching on SO, I only found <a href=""https://stackoverflow.com/questions/3576242/how-to-use-reflection-to-unit-test-an-internal-friend-in-vb-class-within-an-as"">one match</a>, which suggests an interesting workaround. I am willing to follow this alternative if there is no better option. I am however very surprised there is no clean way to achieve something I though was quite elementary.</p>
",https://stackoverflow.com/questions/55975433/unit-testing-a-friend-class-from-another-assembly,"['vb.net', 'unit-testing']",251,True,0,1
undefined object when defined in Angular Unit testing,"<p>I'm working through my test environment and am trying to get around an issue with a single user profile through <code>oidc-client</code> being undefined during unit testing. </p>

<p>I have tried making the <code>BeforeEach</code> methods <code>async</code> that has not helped, and I have also tried restructuring my <code>AuthService</code> as well. </p>

<p>This is the error that I am getting from the test components:</p>

<p><code>ResourcesCardComponent &gt; should create</code></p>

<p><code>Failed: Cannot read property 'profile' of undefined</code></p>

<p><strong>AuthService</strong> </p>

<pre><code>import { Injectable } from '@angular/core';
import { UserManager, User, WebStorageStateStore } from 'oidc-client';
import { BehaviorSubject } from 'rxjs';
import { ConfigAssetLoaderService } from '../config-asset-loader.service';
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private _userManager: UserManager;
  public _user: User;
  public isLoggedInSubject$ = new BehaviorSubject&lt;any&gt;(this._user);
  isLoggedIn = this.isLoggedInSubject$.asObservable();

  constructor(private configService: ConfigAssetLoaderService) {
    const config = {};
    this.configService.loadConfiguration().subscribe(response =&gt; {
      config['authority'] = response.authority;
      config['client_id'] = response.client_id;
      config['redirect_uri'] = response.redirect_uri;
      config['scope'] = response.scope;
      config['response_type'] = response.response_type;
      config['loadUserInfo'] = response.loadUserInfo;
      config['userStore'] = new WebStorageStateStore({store: window.sessionStorage});
      config['metadata'] = {
        issuer: response.issuer,
        authorization_endpoint: response.authorization_endpoint,
        userinfo_endpoint: response.userinfo_endpoint,
        jwks_uri: response.jwks_uri,
        end_session_endpoint: response.end_session_endpoint
      };
      config['signingKeys'] = response.signingKeys;
      config['extraQueryParams'] = {
        resource: response.claimsApiResourceId
      };
      this._userManager = new UserManager(config);
      this._userManager.getUser().then(user =&gt; {
        if (user &amp;&amp; !user.expired) {
          this._user = user;
          this.isLoggedInSubject$.next(user);
        }
      });
    });
  }
}
</code></pre>

<p>The <code>AuthService</code> is pretty standard, all the important pieces for this question are in the constructor. </p>

<p>The component in question using this service is the following: </p>

<pre><code>import { Component, Input } from '@angular/core';
import { ActionLink } from '../../shared/models/actionlink';
import { AuthService } from '../../core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'thrive-resources-card',
  templateUrl: './resources-card.component.html',
  styleUrls: ['./resources-card.component.scss']
})
export class ResourcesCardComponent {

  @Input() public actionLinks: ActionLink[];

  public firstName$: Observable&lt;string&gt;;

  constructor(private authService: AuthService) {
    this.firstName$ = this.authService.isLoggedInSubject$.pipe(
      map(response =&gt; response.profile.unique_name.replace(/\s+/, '').split(',')[1])
    );
  }
}
</code></pre>

<p>Here is the test component for the <code>ResourceCardComponent</code> as well:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ResourcesCardComponent } from './resources-card.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ActivatedRoute, RouterModule } from '@angular/router';
import { ResourcesCardContainerComponent } from './resources-card-container/resources-card-container.component';

const fakeRoute = {
  snapshot: {
      data: {
        actionLinks: []
      }
  }
};

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        ResourcesCardComponent,
        ResourcesCardContainerComponent
      ],
      imports: [
        RouterModule,
        HttpClientTestingModule
      ],
      providers: [
        {
          provide: ActivatedRoute,
          useFactory: () =&gt; fakeRoute
        }
      ]
    }).compileComponents();
  }));

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

  it('should create', () =&gt; {
    component.actionLinks = [];
    expect(component).toBeTruthy();
  });
});
</code></pre>
",https://stackoverflow.com/questions/58737675/undefined-object-when-defined-in-angular-unit-testing,"['angular', 'unit-testing', 'jasmine']",328,True,0,1
Unit Testing R Shiny App rhandsontable with shinytest,"<p>I am trying to test rhandsontable in R shiny app with shinytest package. But fail to access table3 and get a following error:</p>

<p>Error in session_makeRequest(self, private, endpoint, data, params, headers) : 
  undefined is not an object (evaluating 'HTMLWidgets.getInstance(table3).hot')</p>

<pre><code>##app.R

library(shiny)
library(rhandsontable)

create_df &lt;-function() {
  df &lt;-  data.frame(matrix(0.0, ncol = 2, nrow = 1))
  return(df)
}

ui &lt;- basicPage(
  navbarPage(""App"", id=""nav"",fluid = TRUE,
             tabPanel(""Table 1"", id=""t1"",
                      titlePanel(""Table 1""),
                      hr(),
                      fluidRow(column(12,
                                      tagList(
                                        tags$h3(""Table 1""),
                                        rHandsontableOutput(""table1"")
                                      )
                      )),
                      fluidRow(column(12,
                                      tagList(
                                        tags$h3(""Table 2""),
                                        rHandsontableOutput(""table2"")
                                      )))
                      ),

             tabPanel(""Table 3"",id=""t3"",
                      titlePanel(""Table 3""),
                      hr(),
                      fluidRow(column(12,
                                      tagList(
                                        tags$h3(""Table 3""),
                                        rHandsontableOutput(""table3"")
                                      )
                      )))



    )

)

server &lt;- function(input, output, session) {

  v = reactiveValues()


  observe({ input$table1
    if (!is.null(input$table1)) {
      v$table1&lt;- hot_to_r(input$table1)

    } else {
      v$table1&lt;-create_df()
    }
  })

  output$table1 &lt;- renderRHandsontable({
    rhandsontable(v$table1)
  })

  observe({ input$table2
    if (!is.null(input$table2)) {
      v$table2&lt;- hot_to_r(input$table2)

    } else {
      v$table2&lt;-create_df()
    }
  })

  # observeEvent(input$df,{  
  #   v$df2 &lt;- v$df * 2
  # })

  output$table2 &lt;- renderRHandsontable({
    rhandsontable(v$table2)
  })

  observe({ input$table3
    if (!is.null(input$table3)) {
      v$table3&lt;- hot_to_r(input$table3)

    } else {
      v$table3&lt;-create_df()
    }
  })



  output$table3 &lt;- renderRHandsontable({
    rhandsontable(v$table3)
  })



}

shinyApp(ui = ui, server = server)


#shinytest script

library(shinytest)

app &lt;- ShinyDriver$new(""path to app"")

app$snapshotInit(""mytest"")


app$snapshot(screenshot = FALSE)


script &lt;- paste0(
  ""var $table = HTMLWidgets.getInstance(table3).hot;"",
  ""$table.setDataAtCell([[0,0,'1'],[0,1,'1']]);""
)


app$executeScript(script)

app$snapshot(screenshot = FALSE)
</code></pre>

<p>My expectation of this script is that first two cells in first row will get values of 1 assigned to them, but it does not happen. Please advise how to solve it. Thank you.</p>
",https://stackoverflow.com/questions/57227169/unit-testing-r-shiny-app-rhandsontable-with-shinytest,"['r', 'unit-testing', 'shiny', 'rhandsontable']",291,False,0,1
Unit testing a method with no return value,"<p>What would be an elegant a way of unit testing a method like this ?</p>

<pre><code>from feedgen.feed import FeedGenerator

def generate_feed(file_list):
    fg = FeedGenerator()
    for f in file_list:
        fe = fg.add_entry()
    fg.rss_str(pretty=True)
    fg.rss_file('podcast.xml')
</code></pre>

<p>Obviously the method doesn't return any value, but writes an xml file instead . Is there an elegant way of unit testing this ? Or should I look into refactoring my method to make it more unit testing friendly and assert against something ?</p>
",https://stackoverflow.com/questions/58809028/unit-testing-a-method-with-no-return-value,"['python', 'unit-testing']",57,True,1,3
Angular unit testing form validation - control stays untouched,"<p>I've an Angular component which has form validation. I'm unit testing to make sure it displays an error message if the input is invalid.</p>

<p>But when I try to change the <code>&lt;input&gt;</code> box value, the control's state remains <code>untouched</code> and the error doesn't display.</p>

<p>Here's the code:</p>

<pre><code>&lt;form #zipForm=""ngForm""&gt;
&lt;label&gt;
    &lt;input type=""text"" id=""postalCode"" [(ngModel)]=""postalCode"" #postalCodeElem=""ngModel"" name=""postalCode"" [pattern]=""validationPattern"" required&gt;
    &lt;button type=""button"" (click)=""click(postalCodeElem.value)""&gt;Enroll&lt;/button&gt;
    &lt;div *ngIf=""postalCodeElem.invalid &amp;&amp; postalCodeElem.touched""&gt;
    &lt;span id=""required-postal-code"" *ngIf=""postalCodeElem?.errors?.required""&gt;
        zip/postal code is required
    &lt;/span&gt;
    &lt;span id=""invalidPostalCode"" *ngIf=""postalCodeElem?.errors?.pattern""&gt;
        zip postal code is invalid
    &lt;/span&gt;
    &lt;/div&gt;
&lt;/label&gt;
&lt;/form&gt;
</code></pre>

<p>Test file:</p>

<pre><code>it('should show error in case of invalid postal code', () =&gt; {
    const elem: HTMLElement = fixture.nativeElement;
    const inputElem: HTMLInputElement = elem.querySelector('input');

    inputElem.value = 'L5L2';
    inputElem.dispatchEvent(new Event('input', { bubbles: true }));

    fixture.detectChanges();

    const invalidErrorElem: any = elem.querySelector('span');

    console.log('elem', elem);
    console.log('invalidErrorElem', invalidErrorElem);

    expect(invalidErrorElem).not.toBeNull();
});
</code></pre>

<p>I've created a stackblitz to demo the issue: <a href=""https://stackblitz.com/edit/angular-testing-45zwkn?file=app%2Fapp.component.spec.ts"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/angular-testing-45zwkn?file=app%2Fapp.component.spec.ts</a></p>

<p>Any idea what am I doing wrong?</p>
",https://stackoverflow.com/questions/54442920/angular-unit-testing-form-validation-control-stays-untouched,"['angular', 'unit-testing', 'testing', 'jasmine']",2232,True,1,1
Angular Unit Testing - Mocking a REST service call,"<p>I'm writing unit tests for an Angular application to test frontend functionality and am trying to generate a way to mock a rest service call for the following scenario:</p>

<p>I have a class defined as follows:</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import {RestService} from ""../../../../../services/rest.service"";
import {ActivatedRoute, Router} from ""@angular/router"";

@Component({
  selector: 'app-example-class’,
  templateUrl: ‘./example-class.component.html',
  styleUrls: [‘./example-class.component.scss']
})
export class ExampleClass implements OnInit {

  myData: any = [];
  reloadInterval: any;
  constructor(private rest: RestService) {
    this.reloadInterval = setInterval(() =&gt; {
      this.getData();
    }, 10000);
  }

  ngOnInit() {
    this.getData();
  }

  ngOnDestroy(){
    clearInterval(this.reloadInterval);
  }

  getData() {
    this.rest.call(‘exampleClass’, this.rest.id).subscribe((data: {}) =&gt; {
      if (data['rows']) {
        this.myData = data['rows'].reduce((accumulator, currRow)=&gt; accumulator + currRow.value, 0);
      }
    });
  }
}
</code></pre>

<p>I want to specifically test my ""getData()"" method using Karma/Jasmine unit testing framework.  Here's what I've created:</p>

<pre><code>describe(‘ExampleClassComponent', () =&gt; {
  let component: ExampleClass;
  let fixture: ComponentFixture&lt;ExampleClass&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
      ],
      declarations: [ ExampleClass ]
    })
    .compileComponents();
  }));

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

  it('should create',
    inject(
      [HttpTestingController],
      (httpMock: HttpTestingController) =&gt; {
    expect(component).toBeTruthy();
  }));
});
</code></pre>

<p>This works.  The component gets created and the test passes.  However, when I try to do the following:</p>

<pre><code>it('should test number of elements', ()=&gt;{
    component.getData();
    expect(component.myData.length).toBe(1);
 });
</code></pre>

<p>This fails.  And it fails because it's trying to call the getData() method with a rest call to a service that's not running.  I want to somehow mock the rest call made in that function.  I've tried creating a MockRestService class in my test class as such:</p>

<pre><code>class MockRestService extends RestService {
  myData = [
    {myData: 1}
  ];

  call(endpoint: string, params?: Object, data?: any, queryString?: string, isCustomUri?: boolean): Observable&lt;any&gt; {
    return of(this.myData);
  }
}
</code></pre>

<p>and then modifying my test:</p>

<pre><code>  it('should test number of elements', ()=&gt;{
    let mockRestService = new MockRestService(null);
    component = new ExampleClass(mockRestService);
    component.getData();
    expect(component.myData.length).toBe(1);
  });
</code></pre>

<p>But this doesn't work.  Is it possible to mock the rest call made in getData for the purposes of testing, and if so how?  I really appreciate the help!</p>
",https://stackoverflow.com/questions/58984862/angular-unit-testing-mocking-a-rest-service-call,"['angular', 'unit-testing', 'karma-jasmine']",9222,True,1,1
How to write unit testing for alert service,"<p>I am new to writing unit test cases. I'm trying to write test cases for my alert service. I am using angular 7. My alert service and my alert model code like below.</p>

<p>My alert.service.ts</p>

<pre><code>import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { Alert, AlertType } from '../models/alert.model';

@Injectable({
  providedIn: 'root'
})
export class AlertService {
  private subject = new Subject&lt;Alert&gt;();

  constructor() {}

  onAlert(): Observable&lt;Alert&gt; {
    return this.subject
      .asObservable();
  }

  success(message: string) {
    this.alert(new Alert(message, AlertType.Success));
  }

  error(message: string) {
    this.alert(new Alert(message, AlertType.Error));
  }

  info(message: string) {
    this.alert(new Alert(message, AlertType.Info));
  }

  warn(message: string) {
    this.alert(new Alert(message, AlertType.Warning));
  }

  alert(alert: Alert) {
    this.subject.next(alert);
  }

  clear() {
    this.subject.next(null);
  }
}
</code></pre>

<p>My alert.model.ts</p>

<pre><code>export class Alert {
  constructor(public message: string, public type: AlertType) {}
}

export enum AlertType {
  Success,
  Error,
  Info,
  Warning
}
</code></pre>
",https://stackoverflow.com/questions/57973784/how-to-write-unit-testing-for-alert-service,"['angular', 'unit-testing']",1316,True,0,1
cannot get rid of date unit testing - javascript,"<p>I'm new to unit testing and I implementing a unit test for a function that returns date.</p>

<pre><code>const getLastHour = () =&gt; {
const date = new Date().getTime() - 3600000;
return date;
};
</code></pre>

<p>I made something like this but it deosn't work</p>

<pre><code>describe('getLastHour', () =&gt; {
        const getLastHour = mobileArticleService.__get__('getLastHour');
        const getTime = sinon.stub(2019052906);
        const Date = sinon.stub({ getTime });

        before(() =&gt; {
            mobileArticleService.__set__({
                Date,
                getTime,
            });
        });

        it('should return date with hours ', () =&gt; {
            expect(Date).to.be.called;
            expect(getTime).to.be.called;
        });
    });
</code></pre>
",https://stackoverflow.com/questions/56359325/cannot-get-rid-of-date-unit-testing-javascript,"['mocha.js', 'chai', 'sinon']",30,False,-1,1
Angular (8) - Unit testing service with private variables,"<p>I am wondering if my approach to the service I am building and testing is the right approach or not. I have always designed my classes to be as encapsulated as possible. So when it came to building my angular services, I built them the same way. </p>

<p>Below is a snippet of how my service looks:</p>

<pre class=""lang-js prettyprint-override""><code>private postUrl = 'https://localhost:44359/api/posts';
private currentGetPostsUrl = `${this.postUrl}?page=${this.pageNumber}&amp;pageSize=${this.pageSize}`;

private filteredPostListSource = new Subject&lt;IPostViewDto[]&gt;();
filteredPostList$ = this.filteredPostListSource.asObservable();

// post list returned from the api
private originalPostList: IPostViewDto[];
// filtered list that is displayed to user
private filteredPostList: IPostViewDto[];

//get a list of posts that are paginated
getPosts(): Observable &lt; IPostViewDto[] &gt; {
  const urlToFetch = `${this.postUrl}?page=${this.pageNumber}&amp;pageSize=${this.pageSize}`;

  // if the post list exists, return that post list
  if(this.originalPostList) {
  return of(this.originalPostList);
}

return this.http.get&lt;IPostViewDto[]&gt;(urlToFetch, { observe: 'response' })
  .pipe(
    map((response: HttpResponse&lt;IPostViewDto[]&gt;) =&gt; {
      const paginationHeader = JSON.parse(response.headers.get('X-Pagination'));
      this.totalCount = paginationHeader.totalCount;
      this.originalPostList = response.body;
      this.filteredPostList = [...this.originalPostList];
      return response.body;
    }),
    catchError(err =&gt; this.errorHandler(err))
  );
}
</code></pre>

<p>Per above, I don't allow components to directly access the private variables and instead have methods through which all interaction is done. The issue here is that unit testing is a bit of a mess. If I want to correctly test that my <code>getPosts()</code> method correctly returns the list of posts in my <code>originalPostList</code> if it exists, I'd have to run it once after creating a stub value for the http get to ensure the private field gets set, then run it again and compare my stub value equals the 2nd run of <code>getPosts()</code>.</p>

<p>This seems like its not only a bad unit test, but maybe the service itself is not built correctly to be tested. </p>

<p>What would be the best way to restructure this to be easily testable? Do I just create getters/setters and test against those? Or is my approach I described above valid?</p>

<hr>

<p>Do note that the reason why I designed it this way is because I didn't want child components / other components to accidentally update these properties without an explicit method call (so that I can write tests to ensure that is the case). Its not because a single component is the only one accessing this service.</p>
",https://stackoverflow.com/questions/57471110/angular-8-unit-testing-service-with-private-variables,"['angular', 'unit-testing', 'karma-jasmine']",3080,True,0,2
How do I mock JoinRow for unit testing,"<p>I have looked at code base of jdbi v3 but still can't figure out a way to mock <code>Stream&lt;JoinRow&gt;</code> returned by Dao class.</p>

<p>Constructor is package protected which is only invoked from <code>JoinRowMapper</code>'s specialize function which itself needs <code>StatementContext</code>. </p>

<p>Is there any way to mock <code>JoinRow</code> object for unit testing purposes?</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/54369553/how-do-i-mock-joinrow-for-unit-testing,"['unit-testing', 'jdbi']",391,False,0,1
Cannot set property &#39;paginator&#39; of undefined - Unit Testing,"<p>I'm doing a unit testing on one of my component in Angular. The test scenario is to check if a div element with a class <code>.div-container</code> is exists in the page.
So basically, a variable in my component.ts dictates whether the said div is visible or not using <code>*ngIf</code>.</p>

<p>Please see my codes below what I have so far.</p>

<p><strong>HTML</strong></p>

<pre><code>&lt;div *ngIf=""isAdmin""&gt;
    &lt;div class='div-container'&gt;
       &lt;table mat-table [dataSource]=""dataSource"" matSort matSortActive=""DisplayName""
        matSortDirection=""asc"" matSortDisableClear&gt;
        &lt;ng-container matColumnDef=""Firstname""&gt;
          &lt;th mat-header-cell *matHeaderCellDef mat-sort-header&gt;First Name&lt;/th&gt;
          &lt;td mat-cell *matCellDef=""let row""&gt;
            {{row.Firstname}}
          &lt;/td&gt;
        &lt;/ng-container&gt;

        &lt;ng-container matColumnDef=""Lastname""&gt;
          &lt;th mat-header-cell *matHeaderCellDef mat-sort-header&gt;Last Name&lt;/th&gt;
          &lt;td mat-cell *matCellDef=""let row""&gt;{{row.Lastname}}&lt;/td&gt;
        &lt;/ng-container&gt;

        &lt;ng-container matColumnDef=""Gender""&gt;
          &lt;th mat-header-cell *matHeaderCellDef mat-sort-header&gt;Gender&lt;/th&gt;
          &lt;td mat-cell *matCellDef=""let row""&gt;{{row.Gender}}&lt;/td&gt;
        &lt;/ng-container&gt;

        &lt;tr mat-header-row *matHeaderRowDef=""displayedColumns""&gt;&lt;/tr&gt;
        &lt;tr mat-row *matRowDef=""let row; columns: displayedColumns;""&gt;&lt;/tr&gt;
      &lt;/table&gt;
      &lt;mat-paginator [length]=""resultsLength"" [pageSizeOptions]=""[10, 25, 50, 100]"" showFirstLastButtons&gt;&lt;/mat-paginator&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p><strong>TS</strong></p>

<pre><code>@Component({
    ...
})
export class SampleComponent implements OnInit {
  @ViewChild(MatSort, { static: false }) set matSort(ms: MatSort) {
    if (ms !== undefined) {
      this.sort = ms;
      this.dataSource.sort = this.sort;
    }
  }

  @ViewChild(MatPaginator, { static: false }) set matPaginator(mp: MatPaginator) {
    if (mp !== undefined) {
      this.paginator = mp;
      this.dataSource.paginator = this.paginator;
    }
  }

  ngOnInit() {
    this.names$ = this.dataService.names$
      .pipe(
        tap(names =&gt; {
          this.isLoadingResults = false;
          this.resultsLength = names.value.length;

          this.dataSource = new MatTableDataSource(names.value);
        }),
        catchError(this.handleError)
      )
  }
}
</code></pre>

<p><strong>SPEC</strong></p>

<pre><code>describe('SampleComponent', () =&gt; {
  let component: SampleComponent;
  let fixture: ComponentFixture&lt;SampleComponent&gt;;

    beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [SharedModule,
        MatPaginatorModule,
        MatSortModule,
        BrowserAnimationsModule],
      declarations: [SampleComponent]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(SampleComponent);
    component = fixture.componentInstance;

    paginator = component.matPaginator;
    sort = component.matSort;

    fixture.detectChanges();
  });

  it(`should hide the div container if 'isAdmin' is false`, () =&gt; {
    component.isAdmin = false;
    fixture.detectChanges();

    expect(fixture.debugElement.query(By.css('.div-container'))).toBeNull();
  });

  it(`should show the div container if 'isAdmin' is true`, () =&gt; {
    component.isAdmin = true;

    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('.div-container'))).toBeTruthy();
  });
);
</code></pre>

<p>Unfortunately, I cannot make this test to pass due to this error.</p>

<pre><code>TypeError: Cannot set property 'paginator' of undefined.
</code></pre>

<p>Hope someone can guide me on how to properly address this error.</p>

<p>TIA!</p>
",https://stackoverflow.com/questions/58833593/cannot-set-property-paginator-of-undefined-unit-testing,"['angular', 'angular-material', 'karma-jasmine']",3991,False,0,1
Angular - Jest unit testing of method with parameter,"<p>I need to unit test the following method which takes one parameter. But I am unable to test.</p>

<p><strong>Component Method:</strong></p>

<pre><code>resetAdd(qa: qaModel) {
    const street = qa.children.find(temp =&gt; temp.token === 'street');
    const zip = qa.children.find(temp =&gt; temp.token === 'zip');
    const city = qa.children.find(temp =&gt; temp.token === 'city');
    this.fGroup.controls[street.pathway].callReset();
    this.fGroup.controls[zip.pathway].callReset();
    this.fGroup.controls[city.pathway].callReset();
}
</code></pre>

<p><strong>TestFile:</strong></p>

<pre class=""lang-js prettyprint-override""><code>it('resetAdd Method is called', () =&gt; {
  const param1= jest.fn();
  expect(component.resetAdd).toHaveBeenCalledWith(param1);
});
</code></pre>

<p>I am not sure what's wrong and also please let me know what else test case I can write.</p>
",https://stackoverflow.com/questions/58818402/angular-jest-unit-testing-of-method-with-parameter,"['javascript', 'angular', 'typescript', 'unit-testing', 'jestjs']",11696,True,0,2
Unit testing a method blocks indefinitely on CompletableFuture.join(),"<p>I want to use some async <code>CompletionStage</code> operations in a business logic method, using the methods from the <code>CompletableFuture</code> class. The chained calls are:</p>

<pre><code>return CompletableFuture.runAsync(() -&gt; firstOperation(), executor)
                        .thenRunAsync(() -&gt; secondOperation(), executor)
                        .thenApplyAsync(none -&gt; new MessageDTO(""OK""), executor)
                        .join();
</code></pre>

<p>While writing the unit tests for the method which ends with the above snippet, I have noticed that the unit test is blocking indefinitely. I have tried several approaches to circumvent/avoid the blocking (<a href=""https://dzone.com/articles/workaround-multi-threaded"" rel=""nofollow noreferrer"">this</a> is one of them, <code>@Mock</code>-ing and <code>@Spy</code>-ing the <code>Executor</code> object), but to no avail.</p>

<p>There are several aspects which elude me:</p>

<ul>
<li>where is the blocking coming from? is it from the <code>CompletableFuture</code> class or from Mockito?</li>
<li>why is it only blocking in the unit test and not in the service method?</li>
</ul>

<hr>

<p>Used libraries:</p>

<ul>
<li>Spring Boot v2.1.2 &amp; Spring Framework v5.1.4</li>
<li>Mockito v2.23</li>
<li>JUnit Jupiter v5.3.2</li>
</ul>
",https://stackoverflow.com/questions/54339792/unit-testing-a-method-blocks-indefinitely-on-completablefuture-join,"['java', 'unit-testing', 'spring-boot', 'mockito', 'completable-future']",477,False,0,0
Authenticate user without using factory in unit testing,"<p>I am new to unit testing. I want to authenticate a user without using Factory. I want my testing code to be simple. I don't know how to use the Factory. Here is my code : </p>

<pre><code>public function loginVerify()
{
     $user = factory('App\User')-&gt;create();
}
</code></pre>
",https://stackoverflow.com/questions/55471425/authenticate-user-without-using-factory-in-unit-testing,['laravel'],58,True,0,1
How should unit testing for desrialization be done?,"<p>I am using the library <a href=""https://github.com/lift/lift/tree/master/framework/lift-base/lift-json"" rel=""nofollow noreferrer"">lift json</a> in scala to deserialize some json configurations to my <code>Config</code> Case class. For deserializing I have a class called <code>Parser</code>. It has a get method which tries to deserialize the config and if successful then returns <code>scala.util.Success(Config)</code> otherwise <code>scala.util.Failure</code>. My question is what is the correct way to write unit test for Parser class ?</p>

<ol>
<li>Should I just keep various valid and invalid configuration jsons in test data and just assert <code>isFailure</code> and <code>isSuccess</code> from the result of the get method ?</li>
<li>Or for each test json configuration I have, I create an exact Config class by hand, and then assert <code>isFailure</code>,<code>isSuccess</code> and if <code>isSuccess</code> also assert that deserialized config and the one I created by hand are the same ?</li>
</ol>
",https://stackoverflow.com/questions/54304540/how-should-unit-testing-for-desrialization-be-done,"['scala', 'unit-testing', 'deserialization']",49,True,0,1
Unit testing spring cloud gateway filters with spock,"<p>I'm adding cookies in gateway response using reactive global filters as:</p>

<pre><code>chain.filter(exchange).then(&lt;a mono relevant to response&gt;)
</code></pre>

<p>When I'm trying to test this using spock <em>then</em> method is not invoked from the stubbed Mono.</p>

<p>The filter itself:</p>

<pre><code>@Override
public Mono&lt;Void&gt; filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    return chain.filter(exchange)
            .then(refreshCookiesMono(exchange));
}

private Mono&lt;Void&gt; refreshCookiesMono(ServerWebExchange exchange) {
    return Mono.fromRunnable(() -&gt; {
        //interactions with *exchange* and *chain*
    });
}
</code></pre>

<p>This test passes despite 0 * _ in the end:</p>

<pre><code>@Subject
CookieFilter cookieFilter = new CookieFilter(cookieHelper)
...
ServerWebExchange exchange = Mock ServerWebExchange
GatewayFilterChain chain = Mock GatewayFilterChain
Mono&lt;Void&gt; mono = Mock Mono

...

def ""cookieFilter refreshes the cookie with a new value""() {
    given:

    when:
    cookieFilter.filter(exchange, chain)

    then:
    1 * chain.filter(exchange) &gt;&gt; mono
    0 * _
}
</code></pre>

<p>But in the code I invoke <em>.then</em> from the  mono returned from <em>.filter</em> method.</p>

<p>Why isn't <em>mono.then()</em> taken into account? Of course when I try to test all the underlying logic - spock doesn't find interactions.</p>
",https://stackoverflow.com/questions/58787680/unit-testing-spring-cloud-gateway-filters-with-spock,"['java', 'unit-testing', 'groovy', 'spock', 'spring-cloud-gateway']",1876,True,0,2
How to reduce the unit testing running time?,"<p>I'm using Eclipse and doing java code unit testing, but my unit testing running time taking a long time. Is there is any way to reduce the unit testing running time????</p>

<p>My project based on AWS S3 buckets and java. I am using java 8 and junit5 and i did the function move, copy, delete the single file and multiple files transaction functions. So I was checked that functions were correctly worked or not using junit5. but my unit testing taking a long times.</p>
",https://stackoverflow.com/questions/58534816/how-to-reduce-the-unit-testing-running-time,"['java', 'eclipse', 'unit-testing', 'junit5']",208,False,0,0
How to write typescript? Unit Testing Vue Components,"<p>How to write following code in typescript?
This code is from <a href=""https://v2.vuejs.org/v2/cookbook/unit-testing-vue-components.html#Real-World-Example"" rel=""nofollow noreferrer"">Unit Testing Vue Components</a>.</p>
<p>Code:</p>
<pre><code>const factory = (values = {}) =&gt; {
  return shallowMount(Foo, {
    data: { ...values  }
  })
}
</code></pre>
<p>Error:</p>
<pre><code>Missing return type on function.
</code></pre>
",https://stackoverflow.com/questions/56642016/how-to-write-typescript-unit-testing-vue-components,"['typescript', 'vue.js', 'vue-component']",61,False,0,0
zf3 unit testing: getHeaders not accessible in onBootstrap,"<p>I am using <code>Module.php</code> <code>onBootstrap</code>function to check using authentication. on Postman and with browser everything works fine but when unittesting with <code>zend-test</code> it is not able to access the <code>getHeaders()</code> 
MY <code>Module.php</code></p>

<pre><code>     public function onBootstrap(MvcEvent $e)
      {
        $app = $e-&gt;getTarget();
        $locator = $app-&gt;getServiceManager();
        $this-&gt;authorize($e);
      }

      public function authorize($e){
        $sm = $e-&gt;getApplication()-&gt;getServiceManager();
        $request = $sm-&gt;get('Request');

       if($request-&gt;getHeaders('auth_token')){
            return;
        }
        $response = $e-&gt;getResponse();
    $model = new JsonModel(array(
        ""httpStatus"" =&gt; 401,
        ""title"" =&gt; ""Token Not Found"",
    ));
    $e-&gt;getResponse()-&gt;setStatusCode(401);
    $model-&gt;detail = ""Auth Token not provided"";

    $model-&gt;setTerminal(true);
    $e-&gt;setResult($model);
    $e-&gt;setViewModel($model);
}
</code></pre>

<p>Now i tried to follow <a href=""https://stackoverflow.com/questions/39075255/zf3-unit-test-authentication-onbootstrap"">this</a> but i couldn't because the code is so difficult to follow.</p>

<p>My test is something like that:</p>

<pre><code>public function testIndexIsAccessibleAction() {
    $headers = new \Zend\Http\Headers();
    $headers-&gt;addHeaders([
        ""auth_token"" =&gt; 'token' 
    ]);
    $this-&gt;getRequest()
            -&gt;setMethod('GET')
            -&gt;getHeaders()
            -&gt;addHeaders($headers);
         ;
    $this-&gt;dispatch('/action');
    $this-&gt;assertResponseStatusCode(200);
}
</code></pre>

<p>Now i am checking every request in <code>onBootstrap</code> because nothing is accessible if user is not authentic. How do i do my unit testing correctly. and how should i change it to using <code>Service</code> or <code>Factory</code>?</p>
",https://stackoverflow.com/questions/57951296/zf3-unit-testing-getheaders-not-accessible-in-onbootstrap,"['php', 'unit-testing', 'doctrine', 'zend-framework2', 'zend-framework3']",48,False,0,0
Unit Testing a view was dismissed in XCTestCase,"<p>I have an app using the <code>VIPER</code> pattern.</p>

<p>My <code>LoginViewController</code> is presented, some actions take place and the view is dismissed.</p>

<p>I'd like to assert that when <code>LoginPresenter</code> invokes <code>dismissViewController</code> within my <code>LoginRouter</code>, the view is dismissed.</p>

<p>I have a <code>UITest</code> that covers this behave however I have a code coverage issue within my CI Pipeline and a <code>UITest</code> is not enough to cut it.</p>

<p>I'd like to assert on the behaviour in code.</p>

<pre><code>  import UIKit

final class LoginRouter {

    private var delegate: LoginRouterDelegate?
    private let view: UIViewController

    init(_ delegate: LoginRouterDelegate?, view: UIViewController) {
        self.delegate = delegate
        self.view = view
    }
}

extension LoginRouter: LoginRouterType {

    func dismissViewController() {
        view.dismiss(animated: false, completion: nil)
    }
}
</code></pre>
",https://stackoverflow.com/questions/58271324/unit-testing-a-view-was-dismissed-in-xctestcase,"['swift', 'uinavigationcontroller', 'xctest', 'xctestcase']",652,True,0,1
How unit testing by using Codeception in codeigniter?,"<p>I have installed Codeception in Codeigniter 2.2 also working fine but how we can load the model in the unit test. I am beginner kindly share me any example related to this.
Thanks.</p>
",https://stackoverflow.com/questions/57225568/how-unit-testing-by-using-codeception-in-codeigniter,"['unit-testing', 'codeigniter', 'codeception']",269,False,0,0
http typed client in net core unit testing,"<p>How would i go about to unit test a service that makes calls to a http typed client?
the examples given at <a href=""https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2#typed-clients"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2#typed-clients</a> do not use interface.</p>

<pre><code>public GitHubService(HttpClient client)
</code></pre>

<p>Would creating interface for the typed client be needed for unit testing using xunit/moq? or wouldn't i need to unit test this service.</p>
",https://stackoverflow.com/questions/56527226/http-typed-client-in-net-core-unit-testing,['asp.net-core'],704,True,0,2
Unit testing using library &#39;unittest&#39; in Python 3,"<p>I need to write test cases using unit test in Python for testing circle creation.</p>
<blockquote>
<p>Define a class Circle with method init which initializes a circle with
attribute radius, having following restrictions.</p>
<ol>
<li>radius must be numeric value, if not raise type error with error message &quot;radius must be number&quot;.</li>
<li>radius must be between 0 to 1000 inclusive on both sides, if not raise the value error with error message &quot;radius must be between 0 and
1000 inclusive&quot;</li>
<li>Define a class method area and circumference which must return values rounded off to 2 decimals.</li>
</ol>
<p>Complete the definition of class TestingCircleCircumference which
tests the behaviour of circumference  method as specification below.</p>
<p>Define the test method test_circlecircum_with_random_numerical_radius
which creates circle c1 with radius 2.5 and check if its computed
circumference match the value 15.71</p>
<p>Define the test method test_circlecircum_with__min_radius which
creates circle c2 with radius 0 and check if its computed
circumference match the value 0</p>
<p>Define the test method test_circlecircum_with_max_radius  which
creates circle c3 with radius 1000 and check if its computed
circumference match the value 6283.19</p>
</blockquote>
<p>My code is:</p>
<pre><code>import inspect
import re
import unittest
import math

class Circle:

    def __init__(self, radius):

        try:
            if not isinstance(radius, (int, float)):
                raise TypeError
            elif 1000 &gt;= radius &gt;= 0:
                self.radius=radius
            else:
                raise ValueError
        except ValueError:
            raise ValueError(&quot;radius must be between 0 and 1000 inclusive&quot;)
        except TypeError:
            raise TypeError(&quot;radius must be a number&quot;)

def area(self):

    y = math.pi*(self.radius**2)
    return round(y, 2)

def circumference(self):

    x = math.pi*2*self.radius
    return round(x, 2)

class TestCircleArea(unittest.TestCase):

    def test_circlearea_with_random_numeric_radius(self):

        c1 = Circle(2.5)
        self.assertEqual(c1.area(), 19.63)


    def test_circlearea_with_min_radius(self):

        c2 = Circle(0)
        self.assertEqual(c2.area(), 0)

    def test_circlearea_with_max_radius(self):

        c3 = Circle(1000.1)
        self.assertEqual(c3.area(), 3141592.65)
</code></pre>
<p>The below code is generated by the system and I can't edit it. This code is from <a href=""https://en.wikipedia.org/wiki/HackerRank"" rel=""nofollow noreferrer"">HackerRank</a>.</p>
<pre><code>if __name__ == '__main__':

    fptr = open('output.txt', 'w')

    runner = unittest.TextTestRunner(fptr)

    unittest.main(testRunner=runner, exit=False)

    fptr.close()

    with open('output.txt') as fp:
        output_lines = fp.readlines()


    pass_count = [len(re.findall(r'\.', line)) for line in output_lines if line.startswith('.')
                     and line.endswith('.\n')]

    pass_count = pass_count[0]

    print(str(pass_count))

    doc1 = inspect.getsource(TestCircleArea.test_circlearea_with_random_numeric_radius)
    doc2 = inspect.getsource(TestCircleArea.test_circlearea_with_min_radius)
    doc3 = inspect.getsource(TestCircleArea.test_circlearea_with_max_radius)

    assert1_count = len(re.findall(r'assertEqual', doc1))

    print(str(assert1_count))

    assert1_count = len(re.findall(r'assertEqual', doc2))

    print(str(assert1_count))

    assert1_count = len(re.findall(r'assertEqual', doc3))

    print(str(assert1_count))
</code></pre>
<p>The error I am getting is:</p>
<pre class=""lang-none prettyprint-override""><code>Traceback (most recent call last):
  File &quot;main.py&quot;, line 75, in &lt;module&gt;
    pass_count = pass_count[0]
IndexError: list index out of range
</code></pre>
",https://stackoverflow.com/questions/57644593/unit-testing-using-library-unittest-in-python-3,"['python', 'python-3.x', 'unit-testing', 'python-3.6', 'python-unittest']",8568,False,-3,6
Jest - handling base class functions while unit testing,"<p>The code looks like this.</p>

<pre><code>class First extends TelemetryFramework&lt;FirstProps, FirstStates&gt;{
   public getData(){
     const data = this.getconfidentialData()
     this.telemetryInfo(""data fetched.."")
}
}
</code></pre>

<p>When I try to write the unit tests for the function, it fails with the error ""TypeError: Cannot read property 'telemetryInfo' of undefined"". TelemetryFramework class extends React.Component class and adds methods for handling telemetry. Can you please help me find out a way to mock the TelemetryFramework class or its methods? Or is there any other work around.</p>

<p>This is how the unit test looks like.</p>

<pre class=""lang-js prettyprint-override""><code>describe('Test for First', function() {
  test('getData test', async function() {
    const component = shallow(&lt;First {...props} {...state} /&gt;);
    const comp = component.instance();
    comp.getData();
  });
});
</code></pre>
",https://stackoverflow.com/questions/58049595/jest-handling-base-class-functions-while-unit-testing,"['reactjs', 'typescript', 'jestjs']",1127,True,0,1
Consumer not getting called when unit testing MassTransit,"<p>I'm trying to write unit tests using MassTransit. When looking online, I found the best way to access the Bus would be creating it using an <code>InMemoryTestHarness</code>. I add my consumers and a <code>PublishObserver</code> to get the resulting behavior.</p>

<p>In the example below, I send a <code>TestRequest</code> message to the bus, then my consumer reads the request and puts a <code>TestResponse</code> message back on the bus. Finally, an observer gets the response.</p>

<p>I don't know if the problem is with some configuration I'm missing, or if there is some task I'm not waiting, but the request message never even arrives at the consumer. </p>

<p>What am I missing?</p>

<p>The test</p>

<pre><code>[TestMethod]
public void RequestResponseBusTest()
{
    var harness = new InMemoryTestHarness();

    var consumer = new TestConsumer();
    harness.OnConfigureInMemoryBus += c =&gt;
    {
        c.ReceiveEndpoint(""testqueue"", e =&gt;
            e.Consumer(() =&gt; consumer));
    };

    var observer = new TestPublishObserver();
    harness.OnConnectObservers += c =&gt;
    {
        c.ConnectPublishObserver(observer);
    };

    harness.Start().Wait();
    var bus = harness.Bus;

    bus.Publish(new TestRequest() { X = 99 }).Wait();

    Assert.AreEqual(1, consumer.ConsumedMessages.Count, ""consumed"");
    Assert.AreEqual(1, observer.PublishedRequests.Count, ""requests"");
    Assert.AreEqual(1, observer.PublishedResponses.Count, ""responses"");

}
</code></pre>

<p>And supporting classes</p>

<pre><code>[Serializable]
public class TestRequest
{
    public int X { get; set; }
}

[Serializable]
public class TestResponse
{
    public int Y { get; set; }
}

public class TestConsumer : IConsumer&lt;TestRequest&gt;
{
    public List&lt;TestRequest&gt; ConsumedMessages { get; } = new List&lt;TestRequest&gt;();

    public Task Consume(ConsumeContext&lt;TestRequest&gt; context)
    {
        ConsumedMessages.Add(context.Message);
        context.Publish(new TestResponse() { Y = 123 }).Wait();
        return Task.CompletedTask;
    }
}

private class TestPublishObserver : IPublishObserver
{
    public List&lt;TestRequest&gt; PublishedRequests { get; } = new List&lt;TestRequest&gt;();
    public List&lt;TestResponse&gt; PublishedResponses { get; } = new List&lt;TestResponse&gt;();

    public Task PrePublish&lt;T&gt;(PublishContext&lt;T&gt; context) where T : class
    {
        return Task.CompletedTask;
    }

    public Task PostPublish&lt;T&gt;(PublishContext&lt;T&gt; context) where T : class
    {
        var msg = context.Message;

        if (msg is TestRequest)
            PublishedRequests.Add((TestRequest)(object)msg);

        if (msg is TestResponse)
            PublishedResponses.Add((TestResponse)(object)msg);

        return Task.CompletedTask;
    }

    public Task PublishFault&lt;T&gt;(PublishContext&lt;T&gt; context, Exception exception) where T : class
    {
        return Task.CompletedTask;
    }
}
</code></pre>
",https://stackoverflow.com/questions/56133926/consumer-not-getting-called-when-unit-testing-masstransit,"['c#', 'unit-testing', 'masstransit']",2572,True,0,1
Asp.Net Core Unit Testing Delete Method in controller,"<p>I'm unit testing controller logic in a asp.net core project with xUnit and Moq, and I'm having trouble with testing the delete method. I have tried to put together some ideas from different tutorials etc. but still struggling. </p>

<p>I have managed to test that the method returns NoContentResult, and the NotFoundResponse. What I am missing here is the test to see that the delete method actually has deleted an item from the Bygg Repository.</p>

<p>What I am trying to do here in this case is to retreive the list of Bygg, delete an item, and then use assert to check if the list now only contains 2 items. </p>

<p>fyi: bygg = building.</p>

<p>The project follows a repository pattern with generic and userspecific repositories. </p>

<p>This is the delete method in the controller:</p>

<pre><code>[HttpDelete(""{id}"")]
public async Task&lt;IActionResult&gt; DeleteBygg(int id)
{
    try
    {
        var bygg = await _byggRepository.GetByggByIdAsync(id);
        if (bygg == null)
        {
            return NotFound();
        }

        await _byggRepository.DeleteByggAsync(bygg);

        return NoContent();
    }
    catch (Exception ex)
    {
        return StatusCode(500, ""Internal Server Error"");
    }
}
</code></pre>

<p>This is the test method:</p>

<pre><code>[Fact]
public async Task DeleteBygg_ExistingIdPassed_RemovesOneItem()
{
    // Arrange
    _mockRepo.Setup(repo =&gt; repo.DeleteByggAsync(It.IsAny&lt;Bygg&gt;()));
    _mockRepo.Setup(repo =&gt; repo.GetAllByggAsync())
        .ReturnsAsync(GetTestBygg());

    // Act
    var actual = await _controller.GetAllBygg();
    var actual2 = actual as OkObjectResult;
    var noContentResponse = await _controller.DeleteBygg(1);


    // Assert
    var items = Assert.IsType&lt;List&lt;Bygg&gt;&gt;(actual2.Value);
    Assert.Equal(2, items.Count);
}
</code></pre>
",https://stackoverflow.com/questions/55223684/asp-net-core-unit-testing-delete-method-in-controller,"['c#', 'unit-testing', 'asynchronous', 'asp.net-core', 'moq']",3241,True,0,1
How to test function in laravel Unit testing,"<p>Using Unit Testing for the first time. </p>

<p>Ceated Test File by cmd:</p>

<pre><code>php artisan module:make-test ProjectTest Projects
</code></pre>

<p>I can test by cmd:</p>

<pre><code>./vendor/bin/phpunit
</code></pre>

<p>But I want to test my function, My function is like:</p>

<pre><code>public function update(Request $request, $id)
    {
        $project = Project::find($id);
        $project-&gt;project_name = request('project_name');
        $project-&gt;save();
        return response()-&gt;json([
            'message' =&gt;  ""Project Updated Successfully"",
            'updatedId' =&gt; $project-&gt;id
            ], 200);
    }
</code></pre>

<p>Can anyone please guide me on how to test this Controller in PHPUnit? </p>

<p>On PostMan testing the function like:</p>

<pre><code>URL:(POST method) http://localhost:8000/api/updateProject/1
</code></pre>

<p>On Body</p>

<pre><code>{
    ""project_name"":""school"",
}
</code></pre>

<p>How to use PHP Unit Testing in Laravel for the above Controller ?. Kindly explain to me with code Snippets.</p>
",https://stackoverflow.com/questions/58443921/how-to-test-function-in-laravel-unit-testing,"['api', 'unit-testing', 'testing', 'laravel-6']",1646,True,0,1
Having issues unit testing internal class in c#,"<p>So i'm having an issues unit testing the PermissionRequirementFilter below. This class was perviusly being DI'd into the unit test but something has changed and im unsure whats happend. Its complaining about the protection level of the class as its an internal based class. </p>

<p><strong>MainClass:</strong></p>

<pre><code>public class PermissionRequirementAttribute : TypeFilterAttribute
{
    public PermissionRequirementAttribute(string permissions) : base(typeof(PermissionRequirementFilter))
    {
        Arguments = new object[]
        {
            Regex.Split(permissions, @"",\s*"").ToList()
        };
    }
}

internal class PermissionRequirementFilter : IAuthorizationFilter
{
    private readonly IEnumerable&lt;string&gt; _requiredPermissions;
    private readonly IOrganisationsServiceProxy _organisationsProxy;

    public PermissionRequirementFilter(
        IOrganisationsServiceProxy organisationsProxy,
        IEnumerable&lt;string&gt; requiredPermissions)
    {
        _requiredPermissions = requiredPermissions;
        _organisationsProxy = organisationsProxy;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
    }
}
</code></pre>

<p><strong>TestConstructor</strong>:
The test class looks like the code below but the import isnt letting me DI the class into the test class.</p>

<pre><code>public class PermissionRequirementAttributeTests
{
    private readonly IEnumerable&lt;string&gt; _testPermissions;
    private readonly PermissionRequirementFilter _permissionRequirementFilter;
    private readonly Mock&lt;IOrganisationsServiceProxy&gt; _organisationProxy;

    public PermissionRequirementAttributeTests()
    {
        _organisationProxy = new Mock&lt;IOrganisationsServiceProxy&gt;();
        _testPermissions = new List&lt;string&gt; { ""myPermission"", ""mySecondPermission"", ""myThirdPermission"" };
        _permissionRequirementFilter = new PermissionRequirementFilter(_organisationProxy.Object, _testPermissions);
    }
}
</code></pre>

<p>Any help would be great thanks in advance.</p>
",https://stackoverflow.com/questions/58984865/having-issues-unit-testing-internal-class-in-c,"['c#', 'dependency-injection', 'xunit']",51,False,0,0
Triangle javascript problem/ Unit testing not working (Jasmine),"<p>I written code to determine if a triangle is equilateral, isosceles, or scalene. Next, I'm suppose to test it using Jasmine but my code keep failing. I am very new to unit testing. Please help me!</p>

<p>TriangleSpec:</p>

<pre><code>describe('Determine if a triangle is equilateral, isolene, scalene', 
function () {
  it('equilateral triangles have equal sides', function () {
    var triangle = new isTriangle (5, 5, 5)
    expect(triangle).toEqual(""Equilateral"");
  });
</code></pre>

<p>Triangle.js:</p>

<pre><code>function isTriangle(side1, side2, side3){
  if (side1 === 0 || side2 === 0 || side3 === 0) {
      console.log(""Error"");
  } else if (side1 &lt; 0 || side2 &lt; 0 || side3 &lt; 0) {
      console.log(""Error"");
  } else if (side1 + side2 &lt;= side3 || side1 + side3 &lt;= side2 || side2 +
    side3 &lt;= side1) {
    console.log(""Error"");
  }
  else if (side1 == side2 &amp;&amp; side2 == side3) {
    console.log(""Equilateral"");
  } else if (side1 === side2 || side2 === side3 || side1 === side3) {
    console.log(""Isosceles"");
  } else {
    console.log(""Scalene"");
  }
};

isTriangle(6, 6, 5);
</code></pre>
",https://stackoverflow.com/questions/56924241/triangle-javascript-problem-unit-testing-not-working-jasmine,"['javascript', 'unit-testing', 'jasmine']",202,False,0,1
e.preventDefault prevents me from unit testing with Enzyme,"<p>I have a reactJS application with a button.</p>

<p>When user presses the button, the user gets verificationCode on their cellphone.</p>

<p>At first, the form was refreshing randomly when user presses the button but I figured out that I have to use</p>

<pre><code>event.preventDefault();
</code></pre>

<p>to stop the button refreshing.</p>

<p>So in my onClick handler, I have the following structure.</p>

<p>CODE - 
const handleOnClick = async(event) => {
event.preventDefault();</p>

<p>logic.. (which includes async calls to backend API)</p>

<h2>}</h2>

<p>However, my problem is that when I create an unit test with Enzyme, the function returns in 'preventDefault()' and never executes the logic.</p>

<p>Is there anyway to test unit test in this case?</p>

<pre><code>
import React, {useState} from 'react';
import TextField from ""@material-ui/core/TextField"";
import Grid from ""@material-ui/core/Grid"";
import {
  isInputNumeric,
  processKoreaCellphone
} from '../../../../api/auth/authUtils';
import {requestMobileVerificationCode} from ""../../../../api/auth/authApiConsumer"";
import Select from ""@material-ui/core/Select"";
import OutlinedInput from ""@material-ui/core/OutlinedInput"";
import MenuItem from ""@material-ui/core/MenuItem"";
import {makeStyles} from ""@material-ui/core"";
import Button from '@material-ui/core/Button';
import Typography from ""@material-ui/core/Typography"";
import Box from ""@material-ui/core/Box"";
import Link from '@material-ui/core/Link';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import Collapse from '@material-ui/core/Collapse';

const useStyles = makeStyles(theme =&gt; ({

  cellphoneCountryCodeStyle: {
    marginTop: '8px',
    marginBottom: '4px'
  },
  requestVerificationMsgBtnStyle: {
    marginTop: '8px',
    marginBottom: '4px',
    minHeight: '40px',
  },
  txtLabel: {
    paddingTop: '0px',
    fontSize: '0.75rem',
    color: 'rgba(0, 0, 0, 0.54)'
  },
  txtLabelGrid: {
    paddingTop: '0px',
  },

}));

export const CellphoneTextField = props =&gt; {

  const {onStateChange} = props;
  const [state, setState] = useState({
    errors: [],
    onChange: false,
    pristine: false,
    touched: false,
    inProgress: false,
    value: {
      cellphoneCountryCode: '82',
      cellphone: '',
    },
    verificationCode: [],
    isLocked: false
  });
  const [open, setOpen] = useState(false);
  const [verificationCode, setVerificationCode] = useState('');
  const [isVerificationCodeError, setIsVerificationCodeError] = useState(false);


  const handleOnClick = async (event) =&gt; {
    const eventCurrentTarget = event.currentTarget.name;

    if (eventCurrentTarget === 'resendBtn' || eventCurrentTarget
        === 'resetBtn') {
      event.preventDefault();
    }

    if ((eventCurrentTarget === 'requestVerificationMsgBtn' &amp;&amp; state.isLocked
        === false) || eventCurrentTarget === 'resendBtn') {

      const updateState = {
        ...state,
        isLocked: true,
        inProgress: true,
      };
      setState(updateState);
      onStateChange(updateState);

      const lang = navigator.language;
      const cellphoneCountryCode = state.value.cellphoneCountryCode;
      const cellphone = state.value.cellphone;

      const response = await requestMobileVerificationCode(lang,
          cellphoneCountryCode, cellphone).catch(e =&gt; {});

      const updatedState = {
        ...state,
        isLocked: true,
        inProgress: false,
        verificationCode: state.verificationCode.concat(response),
      };

      setState(updatedState);
      onStateChange(updatedState);

    }


  };


  const classes = useStyles();

  return (
                &lt;Grid container spacing={1}&gt;
                       &lt;Grid item xs={12} p={0} className={classes.txtLabelGrid}&gt;
                    &lt;Typography className={classes.txtLabel} component=""h5"" id=""infoMsg""
                                name=""infoMsg""
                                variant=""caption""&gt;
                      &amp;nbsp;&amp;nbsp;&amp;nbsp;Did not receive the code? &amp;nbsp;&amp;nbsp;&lt;Link
                        component=""button""
                        variant=""body2""
                        id=""resendBtn""
                        name=""resendBtn""
                        to=""/""
                        className={classes.txtLabel}
                        onClick={handleOnClick}
                    &gt;
                      [resend VericationCode]
                    &lt;/Link&gt; 
                    &lt;/Typography&gt;
                    &lt;Box m={1}/&gt;
                  &lt;/Grid&gt;
            &lt;/Grid&gt;

  )

};

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

<p>My unit test code</p>

<pre><code>
jest.mock(""../../../../api/auth/authApiConsumer"");

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

describe('&lt;CellphoneTextField /&gt;', () =&gt; {
  const handleStateChange = jest.fn();
  let shallow;

  beforeAll(() =&gt; {
    shallow = createShallow();
  });
  let wrapper;
  beforeEach(() =&gt; {
    wrapper = shallow(&lt;CellphoneTextField onStateChange={handleStateChange}/&gt;);
  });

  it('should allow user to resend verification code', (done) =&gt; {


      act(() =&gt; {

        wrapper.find('#resendBtn').simulate('click', {
          currentTarget: {
            name: 'resendBtn'
          }
        });
      });
</code></pre>

<p>When I run the unit test, code beyond </p>

<pre><code>event.preventDefault();
</code></pre>

<p>is not executed.</p>
",https://stackoverflow.com/questions/57245772/e-preventdefault-prevents-me-from-unit-testing-with-enzyme,"['reactjs', 'jestjs', 'enzyme']",2488,True,0,1
beforeEach() function in Unit testing for Angular(Jasmine),"<p>In the following code, Will beforeEach() function execute also before each inner describe or it will only execute before each it() block?</p>

<p>describe('outer describe',()=>{</p>

<pre><code>beforeEach(() =&gt; {
});

describe('inner describe1',()=&gt;{
});

describe('inner describe2',()=&gt;{
 });

it('First It1',()=&gt;{
});

it('Second It2',()=&gt;{
});
</code></pre>

<p>});</p>
",https://stackoverflow.com/questions/55899796/beforeeach-function-in-unit-testing-for-angularjasmine,"['angular', 'unit-testing', 'jasmine']",2542,False,0,1
Unit testing a method blocks indefinitely on CompletableFuture.join(),"<p>I want to use some async <code>CompletionStage</code> operations in a business logic method, using the methods from the <code>CompletableFuture</code> class. The chained calls are:</p>

<pre><code>return CompletableFuture.runAsync(() -&gt; firstOperation(), executor)
                        .thenRunAsync(() -&gt; secondOperation(), executor)
                        .thenApplyAsync(none -&gt; new MessageDTO(""OK""), executor)
                        .join();
</code></pre>

<p>While writing the unit tests for the method which ends with the above snippet, I have noticed that the unit test is blocking indefinitely. I have tried several approaches to circumvent/avoid the blocking (<a href=""https://dzone.com/articles/workaround-multi-threaded"" rel=""nofollow noreferrer"">this</a> is one of them, <code>@Mock</code>-ing and <code>@Spy</code>-ing the <code>Executor</code> object), but to no avail.</p>

<p>There are several aspects which elude me:</p>

<ul>
<li>where is the blocking coming from? is it from the <code>CompletableFuture</code> class or from Mockito?</li>
<li>why is it only blocking in the unit test and not in the service method?</li>
</ul>

<hr>

<p>Used libraries:</p>

<ul>
<li>Spring Boot v2.1.2 &amp; Spring Framework v5.1.4</li>
<li>Mockito v2.23</li>
<li>JUnit Jupiter v5.3.2</li>
</ul>
",https://stackoverflow.com/questions/54339792/unit-testing-a-method-blocks-indefinitely-on-completablefuture-join,"['java', 'unit-testing', 'spring-boot', 'mockito', 'completable-future']",477,False,0,0
Authenticate user without using factory in unit testing,"<p>I am new to unit testing. I want to authenticate a user without using Factory. I want my testing code to be simple. I don't know how to use the Factory. Here is my code : </p>

<pre><code>public function loginVerify()
{
     $user = factory('App\User')-&gt;create();
}
</code></pre>
",https://stackoverflow.com/questions/55471425/authenticate-user-without-using-factory-in-unit-testing,['laravel'],58,True,0,1
How should unit testing for desrialization be done?,"<p>I am using the library <a href=""https://github.com/lift/lift/tree/master/framework/lift-base/lift-json"" rel=""nofollow noreferrer"">lift json</a> in scala to deserialize some json configurations to my <code>Config</code> Case class. For deserializing I have a class called <code>Parser</code>. It has a get method which tries to deserialize the config and if successful then returns <code>scala.util.Success(Config)</code> otherwise <code>scala.util.Failure</code>. My question is what is the correct way to write unit test for Parser class ?</p>

<ol>
<li>Should I just keep various valid and invalid configuration jsons in test data and just assert <code>isFailure</code> and <code>isSuccess</code> from the result of the get method ?</li>
<li>Or for each test json configuration I have, I create an exact Config class by hand, and then assert <code>isFailure</code>,<code>isSuccess</code> and if <code>isSuccess</code> also assert that deserialized config and the one I created by hand are the same ?</li>
</ol>
",https://stackoverflow.com/questions/54304540/how-should-unit-testing-for-desrialization-be-done,"['scala', 'unit-testing', 'deserialization']",49,True,0,1
Unit testing spring cloud gateway filters with spock,"<p>I'm adding cookies in gateway response using reactive global filters as:</p>

<pre><code>chain.filter(exchange).then(&lt;a mono relevant to response&gt;)
</code></pre>

<p>When I'm trying to test this using spock <em>then</em> method is not invoked from the stubbed Mono.</p>

<p>The filter itself:</p>

<pre><code>@Override
public Mono&lt;Void&gt; filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    return chain.filter(exchange)
            .then(refreshCookiesMono(exchange));
}

private Mono&lt;Void&gt; refreshCookiesMono(ServerWebExchange exchange) {
    return Mono.fromRunnable(() -&gt; {
        //interactions with *exchange* and *chain*
    });
}
</code></pre>

<p>This test passes despite 0 * _ in the end:</p>

<pre><code>@Subject
CookieFilter cookieFilter = new CookieFilter(cookieHelper)
...
ServerWebExchange exchange = Mock ServerWebExchange
GatewayFilterChain chain = Mock GatewayFilterChain
Mono&lt;Void&gt; mono = Mock Mono

...

def ""cookieFilter refreshes the cookie with a new value""() {
    given:

    when:
    cookieFilter.filter(exchange, chain)

    then:
    1 * chain.filter(exchange) &gt;&gt; mono
    0 * _
}
</code></pre>

<p>But in the code I invoke <em>.then</em> from the  mono returned from <em>.filter</em> method.</p>

<p>Why isn't <em>mono.then()</em> taken into account? Of course when I try to test all the underlying logic - spock doesn't find interactions.</p>
",https://stackoverflow.com/questions/58787680/unit-testing-spring-cloud-gateway-filters-with-spock,"['java', 'unit-testing', 'groovy', 'spock', 'spring-cloud-gateway']",1876,True,0,2
How to reduce the unit testing running time?,"<p>I'm using Eclipse and doing java code unit testing, but my unit testing running time taking a long time. Is there is any way to reduce the unit testing running time????</p>

<p>My project based on AWS S3 buckets and java. I am using java 8 and junit5 and i did the function move, copy, delete the single file and multiple files transaction functions. So I was checked that functions were correctly worked or not using junit5. but my unit testing taking a long times.</p>
",https://stackoverflow.com/questions/58534816/how-to-reduce-the-unit-testing-running-time,"['java', 'eclipse', 'unit-testing', 'junit5']",208,False,0,0
Unit Testing tls.LoadX509KeyPair fails if no certs provided,"<pre><code>cert, err := tls.LoadX509KeyPair(os.Getenv(""CERT""), os.Getenv(""KEY""))
if err != nil {
    return err
}
</code></pre>

<p>I want to write a unit test for a function that contains this snippet of code. However, my test environment will never have any content in <code>os.Getenv(""CERT"")</code>/<code>os.Getenv(""KEY"")</code>. This makes the code(<code>tls.LoadX509KeyPair()</code>) return an error, which doesn't let me test the function.
How should I go about mocking/modifying this snippet?</p>
",https://stackoverflow.com/questions/55052235/unit-testing-tls-loadx509keypair-fails-if-no-certs-provided,"['go', 'tls1.2']",375,True,-1,1
All ViewController Views are Nil in Unit Testing?,"<p>Sorry if this is a beginner question but I'm relatively new to Unit testing and didn't see this asked anywhere.   </p>

<p>When I start my unit tests in Swift, I setUp my tests by instantiating my viewController.</p>

<p>My code is set up using MVVM (Model - View - ViewModel).  So when I test some of my viewModel methods, they will update the Views (in the ViewController) in the UI.  The problem is, Xcode keeps crashing and says that the views in the ViewController are nil?  How do I prevent these views from being nil?  Am I doing something wrong?  How do I instantiate the views within the viewController?  I thought this would be automatic.  </p>

<pre><code>class WeirdFaceTests: XCTestCase {

    var viewController: ViewController?
    var tattooModel: ARModel?
    var tattooViewModel: ARViewModel?
    var mainUIModel: MainUIModel?
    var mainUIViewModel: MainUIViewModel?

    override func setUp() {
        // Put setup code here. This method is called before the invocation of each test method in the class.
        super.setUp()
        self.viewController = UIStoryboard(name: ""Main"", bundle: nil).instantiateViewController(withIdentifier: ""PrimaryViewController"") as! ViewController

        self.tattooModel = ARModel(imageName: ""blank"", tattooType: .new)
        self.tattooViewModel = ARViewModel(tattooModel: tattooModel!, delegate: viewController!)

        self.mainUIModel = MainUIModel()
        self.mainUIViewModel = MainUIViewModel(model: mainUIModel!, delegate: viewController!)
    }
</code></pre>
",https://stackoverflow.com/questions/57048166/all-viewcontroller-views-are-nil-in-unit-testing,"['swift', 'unit-testing']",362,False,0,1
Unit testing writing to a socket in scala,"<p>I have the following code that given a socket, writes content to the socket and based on that returns a <code>Right</code> or <code>Left</code></p>

<pre><code>class Gateway {
  def sendEvent(
                 str: String,
                 socket: Socket): Either[CustomException, String] = {
    Try {
      val writer =
        new BufferedWriter(new OutputStreamWriter(socket.getOutputStream))


      writer.write(s""${str}\n"")
      writer.flush()
    } match {
      case Success(_) =&gt; Right(str)
      case Failure(_) =&gt; Left(CustomException)
    }
  }
}
</code></pre>

<p>I am trying to unit test the <code>sendEvent</code> method. However the line </p>

<pre><code>new BufferedWriter(new OutputStreamWriter(socket.getOutputStream))
</code></pre>

<p>prevents me from doing so. Now, I cannot pass in BufferedWriter as a dependency as I need to open a new connection always. </p>

<p>I am using <code>Scalatest</code> and <code>Mockito</code> for testing. Any ideas on how to unit test this code will be highly appreciated. Thanks in advance !!!</p>
",https://stackoverflow.com/questions/58575252/unit-testing-writing-to-a-socket-in-scala,"['scala', 'sockets', 'mockito', 'serversocket', 'scalatest']",128,True,0,1
Angular Unit testing with Input decorator throw error,"<p>here is my component which i run testing:</p>

<pre><code>import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'shell-bread-crumbs',
    templateUrl: './shell-bread-crumbs.component.html',
    styleUrls: ['./shell-bread-crumbs.component.scss']
})
export class ShellBreadCrumbsComponent implements OnInit {

    @Input() breadCrumb;

    constructor() { }

    ngOnInit() {}

}
</code></pre>

<p>here is my spec file:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ShellBreadCrumbsComponent } from './shell-bread-crumbs.component';

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

  let component: ShellBreadCrumbsComponent;
  let fixture: ComponentFixture&lt;ShellBreadCrumbsComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ ShellBreadCrumbsComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ShellBreadCrumbsComponent);
    component = fixture.componentInstance;
    component.breadCrumb = """"; //i given empty declaration,
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>But still getting an error as :</p>

<pre><code>Template parse errors:
    Can't bind to 'breadCrumb' since it isn't a known property of 'bread-crumbs'.
    1. If 'bread-crumbs' is an Angular component and it has 'breadCrumb' input, then verify that it is part of this module.
    2. If 'bread-crumbs' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
    3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (""&lt;bread-crumbs [ERROR -&gt;][breadCrumb]=""breadCrumb""&gt;&lt;/bread-crumbs&gt;"")
</code></pre>

<p>how to fix this?</p>
",https://stackoverflow.com/questions/57883038/angular-unit-testing-with-input-decorator-throw-error,"['angular', 'angular8', 'angular-unit-test']",579,True,0,1
SpyOn TypeORM repository to change the return value for unit testing NestJS,"<p>I would like to unittest corner cases for my TypeORM database calls. I have already mocked all my TypeORM repositories with valid data. But I would like to SpyOn the repository and change the return value form TypeORM. How do I do that?</p>
<pre class=""lang-js prettyprint-override""><code>import {INestApplication} from '@nestjs/common';
import {Test} from '@nestjs/testing';
import {CommonModule} from '@src/common/common.module';
import {AuthService} from './auth.service';
import {Repository} from 'typeorm';
import {V3User} from '@src/database/entity/user.v3entity';
    
describe('AuthService', () =&gt; {
    let service: AuthService;
    let app: INestApplication;
        
    beforeEach(async () =&gt; {
        const module = await Test.createTestingModule({
            imports: [CommonModule.forRoot(`${process.env.DEV_ENV}`)],
            providers: [
                AuthService,     
                {provide: 'V3USER_REPOSITORY', useValue: mockRepositoryV3User()},
            ],
        }).compile();
    
        app = module.createNestApplication();
        await app.init();
    
        service = module.get&lt;AuthService&gt;(AuthService);
    });
    

    
    it('test auth service - with non existing user in v3 db', async () =&gt; {
                
        jest.spyOn(?????? , 'findOne').mockImplementation(() =&gt; undefined);
    
        const res = await service.loginUser(&quot;bad token&quot;);
    
        await expect(service.tokenBasedAuth('example bad token'))
            .rejects.toThrow('bad token exception');
    });
});
</code></pre>
<p>I mock the database like this for normal test cases:</p>
<pre class=""lang-js prettyprint-override""><code>export const mockRepositoryV3User = () =&gt; ({
    metadata: {
        columns: [],
        relations: [],
    },
    findOne: async () =&gt;
        Promise.resolve({
            id: 3,
            email: 'email@example.com',
            first_name: 'david',
            last_name: 'david',
            last_login: '2019-07-15',
            date_joined: '2019-07-15',
        }),
});
</code></pre>
",https://stackoverflow.com/questions/57099863/spyon-typeorm-repository-to-change-the-return-value-for-unit-testing-nestjs,"['nestjs', 'typeorm']",19303,True,25,1
Set up a mock database in Python for unit testing,"<p>I want to set up a mock database (as opposed to creating a test database if possible) to check if the data is being properly queried and than being converted into a Pandas dataframe. I have some experience with mock and unit testing and have set-up previous test successfully. However, I'm having difficulty in applying how to mock real-life objects like databases for testing.</p>

<p>Currently, I'm having trouble generating a result when my test is run. I believe that I'm not mocking the database object correctly, I'm missing a step involved or my thought process is incorrect. I put my tests and my code to be tested in the same script to simplify things. </p>

<ul>
<li>I've thoroughly read thorough the Python unittest and mock documentation so I know what it does and how it works (For the most part).</li>
<li>I've read countless posts on mocking in Stack and outside of it as well. They were helpful in understanding general concepts and what can be done in those specific circumstances outlined, but I could not get it to work in my situation.</li>
<li>I've tried mocking various aspects of the function including the database connection, query and using the 'pd_read_sql(query, con)' function to no avail. I believe this is the closest I got. </li>
</ul>

<h1>My Most Recent Code for Testing</h1>

<pre><code>import pandas as pd
import pyodbc
import unittest
import pandas.util.testing as tm

from unittest import mock

# Function that I want to test
def p2ctt_data_frame():
    conn = pyodbc.connect(
        r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};'
        r'DBQ=My\Path\To\Actual\Database\Access Database.accdb;'
    )

    query = 'select * from P2CTT_2016_Plus0HHs'

    # I want to make sure this dataframe object is created as intended
    df = pd.read_sql(query, conn) 

    return df


class TestMockDatabase(unittest.TestCase):

    @mock.patch('directory1.script1.pyodbc.connect')  # Mocking connection
    def test_mock_database(self, mock_access_database):

        # The dataframe I expect as the output after query is run on the 'mock database'
        expected_result = pd.DataFrame({
            'POSTAL_CODE':[
                'A0A0A1'
            ],
            'DA_ID':[
                1001001
            ],
            'GHHDS_DA':[
                100
            ]
        })

        # This is the line that I believe is wrong. I want to create a return value that mocks an Access table
        mock_access_database.connect().return_value = [('POSTAL_CODE', 'DA_ID', 'GHHDS_DA'), ('A0A0A1', 1001001, 100)]

        result = p2ctt_data_frame()  # Run original function on the mock database

        tm.assert_frame_equal(result, expected_result) 


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

<p>I expect that the expected dataframe and the result after running the test using the mock database object is one and the same. This is not the case. </p>

<p>Currently, if I print out the result when trying to mock the database I get:</p>

<p>Empty DataFrame
Columns: []
Index: [] </p>

<p>Furthermore, I get the following error after the test is run:</p>

<p>AssertionError: DataFrame are different;<br>
DataFrame shape mismatch
[left]:  (0, 0)
[right]: (1, 3)</p>
",https://stackoverflow.com/questions/55576527/set-up-a-mock-database-in-python-for-unit-testing,"['python-3.x', 'pandas', 'unit-testing', 'ms-access', 'mocking']",27186,True,12,1
Visual Studio 2019 Professional LiveShare not allowing Unit Testing,"<p>Our team works in C# and has recently updated to Visual Studio 2019 Professional. We are attempting to use Live Share for TDD.</p>
<p>While we can see one another typing, the remote user cannot build or run unit tests.</p>
<p>Am I missing a configuration?</p>
<p><strong>Edit 1</strong>
I know this is an old post at this point. It seems that Microsoft sacrificed usability for security. The only thing that you can do with LiveShare is write code together. The person coding tests cannot be remote (AFAIK). Also, to do pair programming it will kind of work in a bad way (i.e. the navigator can make changes but the driver will not necessarily see them especially if they are in another file unless explicitly told where to look). When it is time for the driver and navigator to switch, it almost seems easier to push the code to a repo, terminate the live share session and have the new driver pull it and start a new live share session.</p>
<p>As far as mob programming, this really seems to fail to scale.</p>
",https://stackoverflow.com/questions/57225037/visual-studio-2019-professional-liveshare-not-allowing-unit-testing,"['tdd', 'visual-studio-2019', 'visual-studio-liveshare']",308,False,6,0
Unit testing with external data file in Python,"<p>I am new to python and am trying to run unit tests injected with data from an external file:</p>

<pre><code>class TestIsEquivalent(unittest.TestCase):

    filename = os.getcwd() + '\\data\\test-data.txt'

    with open(filename) as f:
        testdata = f.readlines()

    for value in testdata:
        print(value)

        def test_0(self):
            result = isEquivalent(value, value, 0)
            self.assertEqual(result, True)
</code></pre>

<p>I am getting the following error on line isEquivalent() is called with in the test function:</p>

<pre><code>NameError: name 'value' is not defined 
</code></pre>

<p>This would seem to suggest a scoping issue but I cannot figure out how to pass the value in the for loop into the test method. Any suggestions would be much appreciated.</p>
",https://stackoverflow.com/questions/57403502/unit-testing-with-external-data-file-in-python,"['python', 'python-unittest']",421,True,-1,1
Nsb: Unit Testing Saga Handlers which call ReplyToOriginator,"<p>I'm writing simple Unit Tests for all my Saga Handlers, basically just making sure the Messages are being caught/handled at all.</p>

<p>However, one of the Saga Handlers calls ReplyToOriginator and right now it's throwing an Exception because the Test Context isn't recognized as a valid Originator. </p>

<p>More specifically, my relevant code looks like this:</p>

<pre><code>    [TestInitialize]
    public void Initialize()
    {
        _context = new TestableMessageHandlerContext();
        _process = new ActionProcess() { Data = new ActionProcess.ActionSagaData() };
    }

    [TestMethod]
    public async Task ActionProcess_ActionSentHandler_ShouldHandleMessage()
    {
        // Arrange
        var cmd = new ActionSent();

        // Act
        await _process.Handle(cmd, _context);

        // Assert
    }


    public async Task Handle(ActionSent message, IMessageHandlerContext context)
    {
        var actionProcessCompletedReply = new ActionProcessCompleted() 
        await ReplyToOriginator(context, actionProcessCompletedReply);
    }
</code></pre>

<p>And the Test fails with the following Exception being passed up:</p>

<blockquote>
  <p>System.Exception: Entity.Originator cannot be null. Perhaps the sender is a SendOnly endpoint.</p>
</blockquote>

<p>Can anyone offer some advice as to how to solve this problem? Am I perhaps testing the Saga Handlers in a way that's not appropriate?</p>
",https://stackoverflow.com/questions/55348303/nsb-unit-testing-saga-handlers-which-call-replytooriginator,['nservicebus'],251,True,0,1
How to do unit testing for getCurrentNavigation().extras.state in angular 7,"<p>I am trying to write unit test for getCurrentNavigation().extras.state using jasmine.</p>

<p>To solve the issue, I have tried to spy this router method.</p>

<p>My component file,</p>

<pre><code>@Component({
  selector: 'app-location-list',
  templateUrl: './location-list.component.html',
  styleUrls: ['./location-list.component.scss']
})
export class LocationListComponent implements OnInit{

  locationId;
  locationName;
  constructor(private activatedRoute: ActivatedRoute, private router: Router) {
    if (this.router.getCurrentNavigation().extras.state) {
      this.locationId = this.router.getCurrentNavigation().extras.state.locationId;
    }
    if (this.router.getCurrentNavigation().extras.state) {
      this.locationName = this.router.getCurrentNavigation().extras.state.locationName;
    }
  }
  ngOnInit() { }
}
</code></pre>

<p>My Spec file,</p>

<pre><code>describe('LocationListComponent ', () =&gt; {
  let component: LocationListComponent ;
  let fixture: ComponentFixture&lt;LocationListComponent &gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        LocationListComponent 
      ],
      providers: []
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(LocationListComponent );
    component = fixture.componentInstance;
    spyOn(Router.prototype, 'getCurrentNavigation').and.returnValues({ 'extras': { 'state': { 'locationId': 100, 'locationName': ""UK"" } } });
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>But I'm getting the following error,</p>

<pre><code>TypeError: Cannot read property 'extras' of null
</code></pre>

<p>Can anyone help me to resolve this issue. I'm using <code>Angular 7.2</code></p>
",https://stackoverflow.com/questions/57620180/how-to-do-unit-testing-for-getcurrentnavigation-extras-state-in-angular-7,"['angular', 'typescript', 'jasmine', 'karma-jasmine', 'angular7-router']",10017,True,19,4
Unit testing React click outside component using Jest and react testing library,"<p>I found this implementation here but its using enzyme.</p>

<p><a href=""https://stackoverflow.com/questions/45046728/unit-testing-react-click-outside-component"">Unit testing React click outside component</a></p>

<p>Adding an event to window does not work either:</p>

<pre><code>window.addEventListener('click', () =&gt; {
      console.log('click on window');
    });
</code></pre>

<p>Has anyone came across this issue above using jest and ""@testing-library/react""?</p>
",https://stackoverflow.com/questions/56978283/unit-testing-react-click-outside-component-using-jest-and-react-testing-library,"['unit-testing', 'jestjs', 'react-testing-library']",23499,True,24,2
Getting Cloud Functions url for unit testing with emulator,"<p>I have a couple of Cloud Functions that interact with Cloud Firestore. I've managed to start emulator for both (<code>firebase emulators:start --only functions,firestore</code>) and I run the request and it works. However, the URL for emulated functions is fairly long...</p>

<p><code>http://localhost:5001/my-app/us-central1/myFunc</code></p>

<p>I would like to either get a whole url or assemble it somehow. The <code>my-app</code> could be in theory read from <code>.firebaserc</code> where the default is specified. However, I am not sure about port or region.</p>
",https://stackoverflow.com/questions/58367758/getting-cloud-functions-url-for-unit-testing-with-emulator,"['firebase', 'unit-testing', 'google-cloud-firestore', 'google-cloud-functions', 'firebase-cli']",548,False,5,0
Is there a way to properly mock Reselect selectors for unit testing?,"<p>I'm having a pretty complex selectors structure in my project (some selectors may have up to 5 levels of nesting) so some of them are very hard to test with passing input state and I would like to mock input selectors instead. However I found that this is not really possible.</p>

<p>Here is the most simple example:</p>

<pre><code>// selectors1.js
export const baseSelector = createSelector(...);
</code></pre>

<p>-</p>

<pre><code>// selectors2.js
export const targetSelector = createSelector([selectors1.baseSelector], () =&gt; {...});
</code></pre>

<p>What I would like to have in my test suite:</p>

<pre><code>beforeEach(() =&gt; {
  jest.spyOn(selectors1, 'baseSelector').mockReturnValue('some value');
});

test('My test', () =&gt; {
  expect(selectors2.targetSelector()).toEqual('some value');
});
</code></pre>

<p>But, this approach won't work as <code>targetSelector</code> is getting reference to <code>selectors1.baseSelector</code> during initialization of <code>selectors2.js</code> and mock is assigned to <code>selectors1.baseSelector</code> after it.</p>

<p>There are 2 working solutions I see now:</p>

<ol>
<li>Mock entire <code>selectors1.js</code> module with <code>jest.mock</code>, however, it won't work if I'll need to change <code>selectors1.baseSelector</code> output for some specific cases</li>
<li>Wrap every dependency selectors like this:</li>
</ol>

<hr>

<pre><code>export const targetSelector = createSelector([(state) =&gt; selectors1.baseSelector(state)], () =&gt; {...});
</code></pre>

<p>But I don't like this approach a lot for obvious reasons.</p>

<p>So, the question is next: is there any chance to mock Reselect selectors properly for unit testing?</p>
",https://stackoverflow.com/questions/55696552/is-there-a-way-to-properly-mock-reselect-selectors-for-unit-testing,"['javascript', 'unit-testing', 'jestjs', 'reselect']",20154,True,25,4
How to perform Unit testing on Spark Structured Streaming?,"<p>I would like to know about the unit testing side of Spark Structured Streaming. My scenario is, I am getting data from Kafka and I am consuming it using Spark Structured Streaming and applying some transformations on top of the data.</p>

<p>I am not sure about how can I test this using Scala and Spark. Can someone tell me how to do unit testing in Structured Streaming using Scala. I am new to streaming.</p>
",https://stackoverflow.com/questions/56894068/how-to-perform-unit-testing-on-spark-structured-streaming,"['scala', 'apache-spark', 'spark-structured-streaming', 'spark-streaming-kafka']",5882,True,5,2
Unit testing in angular 6 with ngx-logger dependency,"<p>Is there a way to properly test classes that have <code>ngx-logger</code> as dependency in angular (Assuming we may be using some known framework for testing, like jasmine)? So far there isn't a resource that can help me to provide a use case where the <code>ngx-logger</code> was mocked or provided in unit tests for classes that have this dependency.</p>
",https://stackoverflow.com/questions/54249065/unit-testing-in-angular-6-with-ngx-logger-dependency,"['angular', 'typescript', 'jasmine']",2348,True,5,2
How to fix androidx.test.espresso.PerformException when Unit testing using Robolectric?,"<p>I'm doing unit test using Robolectric on local JVM.</p>

<p>When I perform click on a button I get androidx.test.espresso.PerformException: Error performing 'single click - At Coordinates.</p>

<pre><code>    @Test
    public void givenVerificationCodeEmpty_whenUserPressVerify_thenErrorMustAppear() {

        ActivityScenario.launch(VerifyAccountActivity.class);
        onView(withId(R.id.verify_account_verify_button)).perform(click());
        String error = context.getString(R.string.error_verification_code_empty);
        onView(withId(R.id.verify_code_input)).check(matches(hasErrorText(error)));
    }
</code></pre>

<p>I'm using Android Studio 3.3.2 and Robolectric 4.2.</p>

<p>The action which is binded to the button involves view.requestFocus() as shown in the code</p>

<pre><code>private void verify() {
        mVerificationCodeView.setError(null);
        String code = mVerificationCodeView.getText().toString();
        if(TextUtils.isEmpty(code)) {
            mVerificationCodeView.setError(getResources().getString(R.string.error_verification_code_empty));
            mVerificationCodeView.requestFocus();
        } else {
            showProgress(true);
        }
    }

</code></pre>

<p>Here's the full error stack</p>

<pre><code>androidx.test.espresso.PerformException: Error performing 'single click - At Coordinates: 159, 372 and precision: 16, 16' on view 'with id: com.syriail.aladdin:id/verify_account_verify_button'.

    at androidx.test.espresso.PerformException$Builder.build(PerformException.java:82)
    at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:79)
    at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:51)
    at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:312)
    at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:173)
    at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:114)
    at com.syriail.aladdin.useraccount.VerifyAccountUnitTest.givenVerificationCodeEmpty_whenUserPressVerify_thenErrorMustAppear(VerifyAccountUnitTest.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)
    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.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:256)
    at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at android.widget.PopupWindow.getDecorViewLayoutParams(PopupWindow.java:2201)
    at android.widget.PopupWindow.update(PopupWindow.java:2257)
    at android.widget.PopupWindow.update(PopupWindow.java:2235)
    at android.widget.Editor.setFrame(Editor.java:868)
    at android.widget.TextView.setFrame(TextView.java:6481)
    at android.view.View.layout(View.java:20669)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
    at com.google.android.material.textfield.TextInputLayout.onLayout(TextInputLayout.java:1885)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1915)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at androidx.appcompat.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at com.android.internal.policy.DecorView.onLayout(DecorView.java:753)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2792)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2319)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at org.robolectric.shadows.ShadowMessageQueue.dispatchMessage(ShadowMessageQueue.java:148)
    at org.robolectric.shadows.ShadowMessageQueue.access$200(ShadowMessageQueue.java:38)
    at org.robolectric.shadows.ShadowMessageQueue$1.run(ShadowMessageQueue.java:126)
    at org.robolectric.util.Scheduler$ScheduledRunnable.run(Scheduler.java:386)
    at org.robolectric.util.Scheduler.runOneTask(Scheduler.java:278)
    at org.robolectric.util.Scheduler.advanceTo(Scheduler.java:260)
    at org.robolectric.util.Scheduler.advanceBy(Scheduler.java:243)
    at org.robolectric.util.Scheduler.advanceBy(Scheduler.java:233)
    at org.robolectric.util.Scheduler.setIdleState(Scheduler.java:88)
    at org.robolectric.util.Scheduler.unPause(Scheduler.java:123)
    at org.robolectric.shadows.ShadowLooper.unPause(ShadowLooper.java:347)
    at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:398)
    at org.robolectric.shadows.ShadowViewGroup.addView(ShadowViewGroup.java:27)
    at android.view.ViewGroup.addView(ViewGroup.java)
    at android.view.ViewGroup.addView(ViewGroup.java:4822)
    at android.widget.PopupWindow.createDecorView(PopupWindow.java:1409)
    at android.widget.PopupWindow.preparePopup(PopupWindow.java:1356)
    at android.widget.PopupWindow.showAsDropDown(PopupWindow.java:1277)
    at android.widget.Editor.showError(Editor.java:565)
    at android.widget.Editor.onFocusChanged(Editor.java:1296)
    at android.widget.TextView.onFocusChanged(TextView.java:9991)
    at android.view.View.handleFocusGainInternal(View.java:6934)
    at android.view.View.requestFocusNoSearch(View.java:11546)
    at android.view.View.requestFocus(View.java:11520)
    at android.view.View.requestFocus(View.java:11487)
    at android.view.View.requestFocus(View.java:11429)
    at com.syriail.aladdin.VerifyAccountActivity.verify(VerifyAccountActivity.java:107)
    at com.syriail.aladdin.VerifyAccountActivity.access$000(VerifyAccountActivity.java:29)
    at com.syriail.aladdin.VerifyAccountActivity$1.onClick(VerifyAccountActivity.java:63)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at org.robolectric.util.Scheduler.runOrQueueRunnable(Scheduler.java:338)
    at org.robolectric.util.Scheduler.postDelayed(Scheduler.java:162)
    at org.robolectric.util.Scheduler.post(Scheduler.java:141)
    at org.robolectric.shadows.ShadowView.post(ShadowView.java:365)
    at android.view.View.post(View.java)
    at android.view.View.onTouchEvent(View.java:13787)
    at android.view.View$GeneratedProxy/243455390.onTouchEvent(Unknown Source)
    at org.robolectric.shadows.ShadowView.onTouchEvent(ShadowView.java:219)
    at android.view.View.onTouchEvent(View.java)
    at android.widget.TextView.onTouchEvent(TextView.java:10064)
    at android.view.View.dispatchTouchEvent(View.java:12513)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2719)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2719)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2719)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2719)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2719)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3052)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2719)
    at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:440)
    at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1830)
    at android.app.Activity.dispatchTouchEvent(Activity.java:3400)
    at androidx.appcompat.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:69)
    at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:398)
    at org.robolectric.android.internal.LocalUiController.injectMotionEvent(LocalUiController.java:41)
    at androidx.test.espresso.base.UiControllerModule$EspressoUiControllerAdapter.injectMotionEvent(UiControllerModule.java:64)
    at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:160)
    at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:137)
    at androidx.test.espresso.action.Tap.sendSingleTap(Tap.java:170)
    at androidx.test.espresso.action.Tap.access$100(Tap.java:31)
    at androidx.test.espresso.action.Tap$1.sendTap(Tap.java:47)
    at androidx.test.espresso.action.GeneralClickAction.perform(GeneralClickAction.java:136)
    at androidx.test.espresso.ViewInteraction$SingleExecutionViewAction.perform(ViewInteraction.java:356)
    at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:248)
    at androidx.test.espresso.ViewInteraction.access$100(ViewInteraction.java:63)
    at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:153)
    at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:150)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at org.robolectric.shadows.ShadowMessageQueue.dispatchMessage(ShadowMessageQueue.java:148)
    at org.robolectric.shadows.ShadowMessageQueue.access$200(ShadowMessageQueue.java:38)
    at org.robolectric.shadows.ShadowMessageQueue$1.run(ShadowMessageQueue.java:126)
    at org.robolectric.util.Scheduler.runOrQueueRunnable(Scheduler.java:338)
    at org.robolectric.util.Scheduler.postDelayed(Scheduler.java:162)
    at org.robolectric.util.Scheduler.postDelayed(Scheduler.java:151)
    at org.robolectric.shadows.ShadowMessageQueue.enqueueMessage(ShadowMessageQueue.java:133)
    at android.os.MessageQueue.enqueueMessage(MessageQueue.java)
    at android.os.Handler.enqueueMessage(Handler.java:745)
    at android.os.Handler.sendMessageAtTime(Handler.java:697)
    at android.os.Handler.sendMessageDelayed(Handler.java:667)
    at android.os.Handler.post(Handler.java:395)
    at androidx.test.espresso.base.BaseLayerModule$1.execute(BaseLayerModule.java:92)
    at androidx.test.espresso.ViewInteraction.runSynchronouslyOnUiThread(ViewInteraction.java:303)
    at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:161)
    at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:114)
    at com.syriail.aladdin.useraccount.VerifyAccountUnitTest.givenVerificationCodeEmpty_whenUserPressVerify_thenErrorMustAppear(VerifyAccountUnitTest.java:83)
</code></pre>

<p>Note the NullPointerException. I couldn't understand why!</p>

<p>When get rid of the following line of code it works as expected.</p>

<pre><code>mVerificationCodeView.requestFocus();
</code></pre>

<p>This problem only happens when I run the test on the local JVM, but when I user androidTest, i.e run the test on a real device or emulator, it works as expected without removing the above line of code. Like the following test</p>

<pre><code>    @Test
    public void givenVerificationCodeEmpty_whenUserPressVerify_thenErrorMustAppear() {
        onView(withId(R.id.verify_account_verify_button)).perform(click());
        String error = activityTestRule.getActivity().getString(R.string.error_verification_code_empty);
        onView(withId(R.id.verify_code_input)).check(matches(hasErrorText(error)));
    }
</code></pre>

<p>For more information about the libraries I use, here's part of my Gradle</p>

<pre><code>// JUnit 4 framework
    testImplementation 'junit:junit:4.12'

    /**
     * Unit Testing
     */

    // Core library
    testImplementation 'androidx.test:core:1.0.0'

    // AndroidJUnitRunner and JUnit Rules
    testImplementation 'androidx.test.ext:junit:1.1.0'

    // Robolectric
    testImplementation 'org.robolectric:robolectric:4.2'

    // Espresso
    testImplementation 'androidx.test.espresso:espresso-core:3.1.0'
</code></pre>
",https://stackoverflow.com/questions/55477022/how-to-fix-androidx-test-espresso-performexception-when-unit-testing-using-robol,"['android', 'android-espresso', 'robolectric']",678,False,5,0
Unit testing a RecyclerView Adapter throws NullPointerException when accessing mObservables,"<p>My view model holds a very simple recyclerview adapter</p>

<p>When I try to send it messages (which in turn calls <code>notifyDatasetChanged</code>) it throws an exception like so </p>

<pre><code>java.lang.NullPointerException
at androidx.recyclerview.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:11996)
at
</code></pre>

<p>the problem is that the <code>mObservers</code> variable from <code>AdapterDataObservable</code> is null</p>

<p>the thing is that this extends <code>Observable&lt;AdapterDataObserver&gt;</code> which in turn defines <code>mObservers</code> as </p>

<pre><code>protected final ArrayList&lt;T&gt; mObservers = new ArrayList&lt;T&gt;();
</code></pre>

<p>so basically the moment my adapter is instantiated , it will call</p>

<pre><code>private final AdapterDataObservable mObservable = new AdapterDataObservable();
</code></pre>

<p>(which is called by the way, mObservable is not null)</p>

<p>which in turn should call <code>mObservers = new ArrayList&lt;T&gt;();</code></p>

<p>can someone explain why this is never called? or if there is a way to get past this problem?</p>

<p>as a side note the adapter is not mocked it is a solid object.</p>

<p>Edit:</p>

<p>Here is the code of the tests I'm using:</p>

<pre><code>class LoginViewModelTest {

     private lateinit var vm: LoginViewModel

        @get:Rule
        val rule = InstantTaskExecutorRule()

        @Before
        fun setUp() {

            whenever(settings.hasShownWelcome).thenReturn(false)
            whenever(settings.serverIp).thenReturn(""http://127.0.0.1"")

            //this is where the crash happens
            vm = LoginViewModel(settings, service, app, TestLog, TestDispatchers) { p -&gt; permissionGranted }
        }
</code></pre>

<p>And below is the code that is tested:</p>

<pre><code>class LoginViewModel(private val settings: ISettings, private val service: AppService, application: Application, l: ILog, dispatchers: IDispatchers, val permissionChecker: (String) -&gt; Boolean) :  BaseViewModel(application, l, dispatchers)

    val stepAdapter :StepAdapter

    init {
        val maxSteps = calculateSteps()
        //after this assignment, during the normal run, the stepAdapter.mObservable.mObservers is an empty array
        //during unit tests, after this assignment it is null
        stepAdapter = StepAdapter(maxSteps) 
    }
</code></pre>
",https://stackoverflow.com/questions/58181002/unit-testing-a-recyclerview-adapter-throws-nullpointerexception-when-accessing-m,"['android', 'unit-testing', 'android-recyclerview']",1614,True,11,5
Unit testing for Spring Cloud Gateway Custom Filter Factory,"<p>I have implemented the custom filter factories for Cloud Gateway. However, I couldn't figure out the way to write unit testcases. 
While exploring the default Filter Factories test cases, I found that majority of factories test classes extends <a href=""https://github.com/spring-cloud/spring-cloud-gateway/blob/master/spring-cloud-gateway-core/src/test/java/org/springframework/cloud/gateway/test/BaseWebClientTests.java"" rel=""nofollow noreferrer"">BaseWebClientTests</a> and other classes which are in test package.  </p>

<p>My question is that shall I copy paste those intermediate test classes to my local test package? What's community recommendation here? </p>
",https://stackoverflow.com/questions/59431080/unit-testing-for-spring-cloud-gateway-custom-filter-factory,"['java', 'spring', 'spring-cloud', 'spring-cloud-gateway']",6670,True,4,1
Unit Testing the date function using Jasmine in Angular,"<p>I am trying to test a function using date as a argument in <strong>Angular</strong>. Angular uses <strong>jasmine</strong> as a testing Framework.</p>

<p>I have a function like below that involves date manipulation</p>

<pre><code>getDate(date) {
    const d = new Date(date);
    d.setHours(0, 0, 0, 0);
    return d;
  }
</code></pre>

<p>I want to write unit Test for the above function using jasmine I have written following test.</p>

<pre><code>describe('Service', () =&gt; {
  let testMockDate: Date;
  beforeEach(() =&gt; {
    jasmine.clock().uninstall();
    jasmine.clock().install();
    testMockDate = new Date('2019-09-15T05:00:00Z');
    jasmine.clock().mockDate(testMockDate);

    TestBed.configureTestingModule({
      imports: [RouterTestingModule, HttpClientTestingModule],
      providers: [Service]
    });
  });

  afterEach(function() {
    jasmine.clock().uninstall();
  });

  it('check date', inject(
      [Service],
      (service: Service) =&gt; {
        const dateString = service.getDate(testMockDate);
        expect(dateString).toEqual('2019-09-15T00:00:00Z');
      }
   ));
});
</code></pre>

<p>This test is passing in my local but on the server where timezone is different it is failing.
How can effectively test this function. I thought passing argument to date constructor would give me
same date in different timezone. but values depends upon the timezone. Although I am also mocking date using Jasmine but I am not sure it working correctly.</p>
",https://stackoverflow.com/questions/58041807/unit-testing-the-date-function-using-jasmine-in-angular,"['javascript', 'angular', 'unit-testing', 'date', 'karma-jasmine']",878,False,4,0
Python library default NullHandler causing error when unit testing,"<p>I'm trying to setup a default logger for an api library I'm writing. The Python documentation states to setup a NullHandler in the library and then let the developers who use the library determine how the logging should be handled.</p>

<blockquote>
  <p>Note It is strongly advised that you do not add any handlers other than NullHandler to your library’s loggers. This is because the configuration of handlers is the prerogative of the application developer who uses your library. The application developer knows their target audience and what handlers are most appropriate for their application: if you add handlers ‘under the hood’, you might well interfere with their ability to carry out unit tests and deliver logs which suit their requirements.</p>
</blockquote>

<p><a href=""https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial"" rel=""nofollow noreferrer"">https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial</a></p>

<pre><code>import logging
logging.getLogger('foo').addHandler(logging.NullHandler())
</code></pre>

<p>So, for a module such as myapi.py, I might have:</p>

<pre><code>log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler)

class MyApi: ...
</code></pre>

<p>And then in a unit test file, I would set the actual log handler.</p>

<pre><code>import logging
log = logging.getLogger('myapi')
log.handlers = []
log.addHandler(logging.StreamHandler(sys.stdout))
log.setLevel(logging.DEBUG)

class MyApiTests(unittest.TestCase): ...
</code></pre>

<p>The problem I'm having is that the NullHandler causes an error message to come up when running the unit tests.</p>

<pre><code>  File ""/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py"", line 1590, in callHandlers
  if record.levelno &gt;= hdlr.level:
  AttributeError: type object 'NullHandler' has no attribute 'level'
</code></pre>

<p>I've tried several things to remove the error. First, I've tried to remove the existing handler; log.handlers = []. That didn't seem to make any change. I also tried to set a log level; log.setLevel(logging.DEBUG). I still get the error.</p>

<p>I must be missing something. Can anyone explain how to remove the NullHandler or prevent the error message?</p>
",https://stackoverflow.com/questions/56709525/python-library-default-nullhandler-causing-error-when-unit-testing,"['python', 'python-3.x', 'unit-testing', 'logging']",1288,True,4,1
Unit testing Authorization header interceptor in angular not working,"<p><strong>error: Expected one matching request for criteria ""Match by function: "", found none.</strong>
I searched for many things and tried a few solutions. But none of them worked. This is my first project for unit testing. Here's my code.</p>

<p><strong>Auth Interceptor</strong></p>

<pre><code>export const API_URL = new InjectionToken&lt;string&gt;('apiUrl');
export class JwtInterceptor implements HttpInterceptor {
  constructor(@Inject(API_URL) private apiUrl: string) {
  }

  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {

request = request.clone({url: this.prepareUrl(request.url)});

let authToken = localStorage.getItem('auth_token');
if (authToken) {
  request = request.clone({
    setHeaders: {
      Authorization: `Bearer ${authToken}`
    }
  });
}
else {
  // use proxy url for cors error
  request = request.clone({url: this.prepareUrl('https://cors-anywhere.herokuapp.com/' + request.url)});
  // Encode the String
  let encodedString = btoa(`${environment.clientId}:${environment.clientSecret}`);
  request = request.clone({
    setHeaders: {
      Authorization: `Basic ${encodedString}`
    }
  });
}
return next.handle(request);

}

  private isAbsoluteUrl(url: string): boolean {
    const absolutePattern = /^https?:\/\//i;
    return absolutePattern.test(url);
  }

  private prepareUrl(url: string): string {
    url = this.isAbsoluteUrl(url) ? url : this.apiUrl + '/' + url;
    return url.replace(/([^:]\/)\/+/g, '$1');
  }

}
</code></pre>

<p><strong>Auth Interceptor Spec</strong></p>

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

let httpTestingController: HttpTestingController;
  let http: HttpClient;      

  beforeEach(()=&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [{
          provide: HTTP_INTERCEPTORS,
          useClass: JwtInterceptor,
          multi: true
        }]
    });

httpTestingController = TestBed.get(HttpTestingController);
http = TestBed.get(HttpClient);
 });

  it('should add Authorization header in each request', ()=&gt; {
http.get('/data').subscribe(response =&gt; {
  expect(response).toBeTruthy();
});

const req = httpTestingController.expectOne(
  req =&gt; req.headers.has('Authorization')
);
expect(req.request.headers.has('Authorization')).toEqual(true);
expect(req.request.method).toEqual('GET');

req.flush({hello: 'world'});
 });    
  afterEach(()=&gt; {
    httpTestingController.verify();
  });    
});
</code></pre>

<p>I also tried by setting authorization headers using mock service. Can anyone help me what I am missing here?</p>
",https://stackoverflow.com/questions/54129330/unit-testing-authorization-header-interceptor-in-angular-not-working,"['javascript', 'angular', 'unit-testing', 'karma-jasmine', 'angular-http-interceptors']",3480,True,4,2
Intermittent error cannot match any routes unit testing Angular,"<p>I've read many posts on the subject about using the router testing module and trying to spy on the router.navigate method but none have resolved the issue I have. Every 2nd run of my tests or so I will see the error, here's the first line in full </p>

<pre><code>Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'post/view'
</code></pre>

<p>To reiterate the error has not been seen when I run my app only when testing</p>

<p>It only appears once no matter how many tests are in the component and it's always the first test that it happens for, if I switch the order then it's the new first test that fails with this error</p>

<p>My component is as follows ( unrelated code removed for brevity ) </p>

<pre class=""lang-js prettyprint-override""><code>export class CreatePostComponent implements OnInit {

  constructor(private postService: PostService,
              private router: Router,
              private location: Location) {
  }

  submitPost() {
    this.validMessage = '';
    if (!this.createPostForm.valid) {
      this.validMessage = 'Please fill out the form before submitting!';
      return;
    }
    const post = this.createPostForm.value as IPost;
    this.postService.createPost(post)
      .pipe(first())
      .subscribe(
        data =&gt; {
          this.createPostForm.reset();

          //Here's the call that I believe causes the issues
          this.router.navigate(['post/view']);
        },
        error =&gt; {
          return throwError(error);
        }
      );
  }
}
</code></pre>

<p>Here's the spec, again unrelated tests removed </p>

<pre class=""lang-js prettyprint-override""><code>describe('CreatePostComponent', () =&gt; {
  let component: CreatePostComponent;
  let fixture: ComponentFixture&lt;CreatePostComponent&gt;;
  let http: HttpTestingController;
  let mockPostService;
  let mockLocationService;


  beforeEach(async(() =&gt; {
    mockPostService = jasmine.createSpyObj(['createPost']);
    mockLocationService = jasmine.createSpyObj(['back']);
    TestBed.configureTestingModule({
      declarations: [CreatePostComponent],
      imports: [ReactiveFormsModule,
        HttpClientTestingModule,
        RouterTestingModule],
      providers: [
        {provide: PostService, useValue: mockPostService},
        {provide: Location, useValue: mockLocationService}]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    http = TestBed.get(HttpTestingController);
    fixture = TestBed.createComponent(CreatePostComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
</code></pre>

<p>I have also tried spying on the router as below (rest of code unchanged)</p>

<pre class=""lang-js prettyprint-override""><code>  beforeEach(async(() =&gt; {
    mockPostService = jasmine.createSpyObj(['createPost']);
    mockLocationService = jasmine.createSpyObj(['back']);
    TestBed.configureTestingModule({
      declarations: [CreatePostComponent],
      imports: [ReactiveFormsModule,
        HttpClientTestingModule,
        RouterTestingModule],
      providers: [
        {provide: PostService, useValue: mockPostService},
        {provide: Location, useValue: mockLocationService}]
    })
      .compileComponents();

    spyOn&lt;any&gt;(component['router'], 'navigate').and.returnValue(true);
  }));
</code></pre>

<p>and I have tried injecting my own mock for navigate as below</p>

<pre class=""lang-js prettyprint-override""><code>  beforeEach(async(() =&gt; {
    mockPostService = jasmine.createSpyObj(['createPost']);
    mockLocationService = jasmine.createSpyObj(['back']);
    TestBed.configureTestingModule({
      declarations: [CreatePostComponent],
      imports: [ReactiveFormsModule,
        HttpClientTestingModule],
      providers: [
        {provide: PostService, useValue: mockPostService},
        {provide: Location, useValue: mockLocationService},
        {provide: Router, useValue: {navigate: () =&gt; true}}]
    })
      .compileComponents();
  }));
</code></pre>
",https://stackoverflow.com/questions/56092724/intermittent-error-cannot-match-any-routes-unit-testing-angular,"['angular', 'unit-testing', 'router']",5116,True,4,1
Unit testing middleware in Laravel mocking route with parameter,"<p>I am developing a Laravel application. I am now doing Unit testing on the Middleware. I am having a problem with mocking the route.</p>

<p>This is my middleware class</p>

<pre><code>class CheckIfDepartmentIdPresent
{
    public function handle($request, Closure $next)
    {
        if (! $request-&gt;route()-&gt;hasParameter('department')) {
            return abort(Response::HTTP_FORBIDDEN);
        }

        //check if the id is valid against the database, 
        //if it is valid then return $next($request)

        return abort(Response::HTTP_FORBIDDEN);
    }
}
</code></pre>

<p>I named the middleware as department.present.</p>

<p>In the unit test I write my first test like this.</p>

<pre><code>public function test_request_fail_if_id_parameter_is_missing_in_route()
{
    Route::middleware('department.present')
            -&gt;any('/department/test', function () {
                return 'OK';
            });
    $response = $this-&gt;get('/department/test');
    $this-&gt;assertEquals(Response::HTTP_FORBIDDEN, $response-&gt;getStatusCode());
}
</code></pre>

<p>The above test method is working fine. It is working as expected. Now I want to mock the route. In the middleware, I am getting the route parameter like this.</p>

<pre><code>$request-&gt;route('department');
</code></pre>

<p>So that I need to mock a route with parameter. If I mocked like this.</p>

<pre><code>$path = ""/department/{$department-&gt;id}"";
        Route::middleware('department.present')
            -&gt;any($path, function () {
                return 'OK';
            });
</code></pre>

<p>My middleware still not be able to fetch the department id using $request->route('department'). So I need to mock a route with a placeholder for the parameter and then the middleware will be able to fetch the route parameter value by name. How can I fake/mock that? Is there a way to do that?</p>
",https://stackoverflow.com/questions/54307167/unit-testing-middleware-in-laravel-mocking-route-with-parameter,"['laravel', 'unit-testing', 'laravel-routing', 'laravel-middleware']",521,False,3,0
Scroll action for ScrollView not working when unit-testing,"<p>I have the following problem. I'm making <em>unit-tests</em> for a custom <code>DialogFragment</code>. This dialog has a <code>Scrollview</code>. when reaching the end of which, a <code>ViewSwitcher</code> has to switch a view. </p>

<p>Here is the scroll listener:</p>

<pre class=""lang-java prettyprint-override""><code>ViewSwitcher vs = getDialog().findViewById(R.id.vs);
scrollView.getViewTreeObserver()
     .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
      @Override
      public void onScrollChanged() {
           if (scrollView.getChildAt(0).getBottom()
                &lt;= (scrollView.getHeight() + scrollView.getScrollY())) {
                vs.setDisplayedChild(1);
            } else {
                vs.setDisplayedChild(0);
            }
       }
 });
</code></pre>

<p>A test setup method:</p>

<pre class=""lang-java prettyprint-override""><code>@Before
public void setUp() throws Exception {
    activity = Robolectric
        .buildActivity(FragmentTestActivity.class)
        .create()
        .resume()
        .get();

    subject = MemberConsentModal.newInstance(""long text"");
    subject.show(activity.getSupportFragmentManager(), MemberConsentModal.TAG);
}
</code></pre>

<p>And the test method code:</p>

<pre class=""lang-java prettyprint-override""><code>@Test
public void onScrolledToTopBottom_showOptionButtons() {
    final ScrollView scrollView = subject.getDialog().findViewById(R.id.member_consent_content);
    ViewSwitcher vs = subject.getDialog().findViewById(R.id.vs);

    scrollView.fullScroll(ScrollView.FOCUS_DOWN);

    assertThat(vs.getDisplayedChild()).isEqualTo(1);
}
</code></pre>

<p>When debugging, I see that <code>addOnScrollChangedListener</code> is never called, though, when launching the application as on an emulator, as on a physical device, it is working correctly. How can I make the scroll view to be scrolled in testing mode? </p>

<p>PS.
I'm using <code>Robolectric</code> and <code>Mockito</code> for <em>unit-testing</em>.</p>
",https://stackoverflow.com/questions/56049505/scroll-action-for-scrollview-not-working-when-unit-testing,"['android', 'unit-testing', 'android-scrollview', 'viewswitcher']",729,False,3,0
DataService encountered a declaration exception FAILED-Angular Unit testing,"<p>I'm working on unit testing for a service layer. But I'm getting an error like 
DataService encountered a declaration exception FAILED
data.service.ts</p>

<pre><code> data: Data[];
  private url = ""http://localhost:8080/getdata"";

  constructor(
    private http: HttpClient,
     private processHTTPMsgService: ProcessHTTPMsgService
  ) {}

  getData(): Observable&lt;Data[]&gt; {
    return this.http
      .get&lt;Data[]&gt;(this.url)
      .pipe(map(data =&gt; (this.data = data)))
      .pipe(catchError(this.processHTTPMsgService.handleError));
  }
</code></pre>

<p>data.service.spec.ts</p>

<pre><code>describe(""DataService"", () =&gt; {
  let service: DataService;
  let httpMock: HttpTestingController;
  beforeEach(
    () =&gt;
      TestBed.configureTestingModule({
        imports: [HttpClientTestingModule, HttpClientModule],
        providers: [DataService,ProcessHTTPMsgService]
      }),
    (service = TestBed.get(DataService))(
      (httpMock = TestBed.get(HttpTestingController))
    )
  );
  afterEach(() =&gt; {
    httpMock.verify();
  });

  describe(""should retrieve data from the API"", () =&gt; {
    const dummyPosts: Data[] = [
      {
        effectivefrom: ""string"",
        effectiveto: ""string"",
        externalname: ""string"",
        id: 1,
        type: ""string"",
        name: ""string"",
        processstep: 1,
        status: ""string""
      }
    ];
    service.getData().subscribe(data =&gt; {
      expect(data.length).toBe(1);
      expect(data).toEqual(dummyPosts);
    });
    const request = httpMock.expectOne('http://localhost:8080/getdata');
    expect(request.request.method).toBe(""GET"");
    request.flush(dummyPosts);
  });

  describe(""should be created"", () =&gt; {
    const service: DataService = TestBed.get(DataService);
    expect(service).toBeTruthy();
  });
});
</code></pre>

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

<p>DataService encountered a declaration exception</p>

<p>Error: Cannot call Promise.then from within a sync test.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/55128813/dataservice-encountered-a-declaration-exception-failed-angular-unit-testing,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'angular7']",202,False,2,0
Netty - Unit testing idle state of handlers using IdleStateHandler,"<p>I'm attempting to test my own handlers, which listen to <code>io.netty.handler.timeout.IdleStateEvent</code> from <code>io.netty.handler.timeout.IdleStateHandler</code>. I'm don't see anyone else having this issue, but when I sleep in my code to trigger the idle events, the idle events are not triggering. I believe that's due to the embedded channel running on the same thread? Below is an example test.</p>

<pre class=""lang-java prettyprint-override""><code>@Test
public void userEventTriggered_IdleStateEvent() throws Exception {
    // given
    IdleStateHandler idleStateHandler = new IdleStateHandler(
            1L,0L,0L, TimeUnit.SECONDS);
    EmbeddedChannel channel = new EmbeddedChannel(idleStateHandler, myHandler);

    // when
    TimeUnit.SECONDS.sleep(2);

    // then
    assertFalse(channel.isActive());

    channel.finish();
}
</code></pre>

<p>I have noticed in the <a href=""https://github.com/netty/netty/blob/4.1/handler/src/test/java/io/netty/handler/timeout/IdleStateHandlerTest.java"" rel=""nofollow noreferrer"">unit tests for IdleStateHandler</a> that a testable handler has been created which makes use of <a href=""https://github.com/netty/netty/blob/4.1/handler/src/main/java/io/netty/handler/timeout/IdleStateHandler.java#L335-L347"" rel=""nofollow noreferrer"">package-scoped methods</a> to test the handler.</p>

<p>Is there any way to test the idle events from outside the package? I need to ensure coverage for these events. Any tips are appreciated. Thanks!</p>
",https://stackoverflow.com/questions/54990459/netty-unit-testing-idle-state-of-handlers-using-idlestatehandler,"['java', 'netty']",441,True,2,1
Creating instances for RoleManager and UserManager for unit testing?,"<p>I am currently trying to make a test in C# which is relied on UserManager and RoleManager. I mocked them but that did not help, additionally I got an exception which illustrates that a mock object cannot be converted to User or RoleManager. </p>

<p>My question is: do you have any idea how to make instances of UserManager and RoleManager without passing augments in their parameters? So that instances will be used for testing purposes?</p>

<pre><code>public Object MockedUserManager()
{
    var mockUserManager = new Mock&lt;UserManager&lt;User&gt;&gt;(
    new Mock&lt;IUserStore&lt;User&gt;&gt;().Object,
    new Mock&lt;IOptions&lt;IdentityOptions&gt;&gt;().Object,
    new Mock&lt;IPasswordHasher&lt;User&gt;&gt;().Object,
    new IUserValidator&lt;User&gt;[0],
    new IPasswordValidator&lt;User&gt;[0],
    new Mock&lt;ILookupNormalizer&gt;().Object,
    new Mock&lt;IdentityErrorDescriber&gt;().Object,
    new Mock&lt;IServiceProvider&gt;().Object,
    new Mock&lt;ILogger&lt;UserManager&lt;User&gt;&gt;&gt;().Object);
    return mockUserManager.Object;
}
</code></pre>

<p>Thank you in advance!</p>
",https://stackoverflow.com/questions/57291677/creating-instances-for-rolemanager-and-usermanager-for-unit-testing,"['c#', 'authentication', 'asp.net-identity', 'owin']",336,True,2,1
How to bypass login for unit-testing Oracle APEX?,"<p>According to the Cypress best practices, I should avoid using my login UI before each test. I'm struggling to do this using <a href=""https://apex.oracle.com/en"" rel=""nofollow noreferrer"">Oracle APEX</a> because it appears the login process requires a lot more than just username and password.</p>

<p>I have used chrome's <code>tamper data tool</code> and <code>Jmeter</code> to inspect the mechanics of the Oracle APEX login process and, essentially, the login process has 2 steps:<br>
(1) the login page redirects to a login page with a valid session id in the URL, seeded with dozens of time-sensitive unique ids.<br>
(2) Upon submitting your username and password, a POST request is made to /ords/wwv_flow.accept with the username, the password and several other time-sensitive unique identifiers.</p>

<p>It appears that APEX requires something similar to following for a successful login:   </p>

<pre><code>p_json : {""salt"":""108222855956905007172773085768141257328"",""pageItems"":{""itemsToSubmit"":[{""n"":""P101_USERNAME"",""v"":""jsmith""},{""n"":""P101_PASSWORD"",""v"":""Password123""}],""protected"":""unDCYO1qmj_OAwtyYNo_yA"",""rowVersion"":""""}},
p_flow_id : 4000250,
p_flow_step_id: 101,
p_instance: 6589106753596,
p_page_submission_id: 108222855…,
p_request : LOGIN,
p_reload_on_submit : A
</code></pre>

<p>All of these variables (besides the username and password) are available in the login page but to get them I'd have to visit the login UI, which is what I'm trying to avoid. Am I thinking about this the wrong way?</p>
",https://stackoverflow.com/questions/54432666/how-to-bypass-login-for-unit-testing-oracle-apex,"['oracle-apex', 'cypress']",841,False,2,2
Unit Testing SQLite Repository generating No Such Table Error,"<p>I have recently built a quiz application for Xamarin.Android, and want to dome some Unit Testing on the shared library.</p>

<p>I am using a repository pattern with the following files.</p>

<p>SQLiteMyAppRepository.cs</p>

<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SQLite;

namespace MyApp.DataLayer
{
    public class MyAppRepository : IMyAppRepository
    {
        public static string DatabaseName = ""MyApp.sqlite"";

        private SQLiteConnection _dbConnection;

        public MyAppRepository()
        {
            string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string dbFilePath = Path.Combine(docFolder, DatabaseName);
            _dbConnection = new SQLiteConnection(dbFilePath);
        }
</code></pre>

<p>I have then created a new project to test some of these elements.</p>

<p>The primary issue I am having, is that when I try and run the test, I am getting the following exception:</p>

<pre><code>MyApp.Tests.RepositoryTests.AddQuestion threw 
exception: 
SQLite.SQLiteException: no such table: Questions
</code></pre>

<p>I have been messing about with it for a few hours now and can't seem to find what is wrong, any help would be appreciated. I thought Mocking the repository would get around any issues like this. </p>
",https://stackoverflow.com/questions/56823628/unit-testing-sqlite-repository-generating-no-such-table-error,"['c#', '.net', 'moq', 'repository-pattern']",737,True,2,1
Dependency injecting an ASP.NET Identity user (and unit testing),"<p>I don't fully understand how to refactor my app to make it more testable.</p>

<p>I am using ASP.NET Core 3.0 (Razor Pages, if that matters).</p>

<p><strong>Current State:</strong></p>

<p>I have razor pages models that inject in my context (inherited from IdentityDbContext) and userManager:</p>

<pre><code>public class DashboardModel : PageModel
{

    private readonly ApplicationDbContext _context;
    private readonly UserManager&lt;AVUser&gt; _userManager;

    public DashboardModel(ApplicationDbContext context, UserManager&lt;AVUser&gt; userManager)
    {
        _context = context;
        _userManager = userManager;
    }
    public async Task&lt;IActionResult&gt; OnGetAsync()
    {
        AVUser = await _userManager.GetUserAsync(User);
        MyRepository myRepository = new MyRepository(_context, AVUser);

        // omitted - just getting data from the repository for use on the page

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

<p>I have repositories created who have constructors as the following:</p>

<pre><code>public MyRepository(ApplicationDbContext context, AVUser user) 
</code></pre>

<p>I never use the context directly in my Model classes and instead create repositories in the Model classes using the context passed in. In this case ApplicationDbContext is my EF Core context, and AVUser is my type of Identity User, defined as:</p>

<pre><code>public class AVUser : IdentityUser
</code></pre>

<p>My DI is set up as:</p>

<pre><code>// DB Setup
        services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
            options.UseSqlServer(
                Configuration.GetConnectionString(""DefaultConnection"")));


// Identity Setup
        services.AddDefaultIdentity&lt;AVUser&gt;(config =&gt;
        {
            config.SignIn.RequireConfirmedEmail = true; 
        })
        .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;();
</code></pre>

<p><strong>What I don't understand</strong></p>

<p>I want to make my razor pages model classes unit testable without relying on the database or repository classes, mocking up the repository class, so I expect I have to remove the context from the constructor and instead created interfaces for my repositories and DI them. </p>

<p>However, I don't know how to DI in the user parameter for the Repository - how do I set up my service in Startup.cs so this can get passed in? Today to get the value for this, I run:</p>

<pre><code>AVUser = await _userManager.GetUserAsync(User);
</code></pre>
",https://stackoverflow.com/questions/58864059/dependency-injecting-an-asp-net-identity-user-and-unit-testing,"['c#', 'dependency-injection', 'asp.net-identity', 'razor-pages']",1153,True,2,1
"vuejs unit testing, default installation says no test specified","<p>On Windows 7. Installed a fresh vue project using the VueJS UI utility. Set unit testing / Jest enabled. Added babel. </p>

<p>running ""npm test"" at the command line returns <code>'Error: no test specified'</code>. </p>

<p>I have the typical <code>""scripts"": { ""vue-cli-service test:unit"" }</code> set up in my package.json file. </p>

<p>jest.config.js has the expected matching pattern:</p>

<pre><code>{  testMatch: [
    '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
  ] }
</code></pre>

<p>So, it's not finding even the example file located in tests/unit/example.spec.js.</p>

<p>Curiously, I CAN get it to find tests I run directly from the node_modules directory, using <code>vue-cli-service</code>:</p>

<pre><code>node_modules\.bin\vue-cli-service test:unit
</code></pre>

<p>from there I get a babel transpile problem (it fails to recognize the ES6 <code>import</code> command in the <code>example.spec.js</code> file) .. which is another nightmare, perhaps not for this post.</p>

<p>Tried updating npm (using <code>6.9.2</code>). Vue cli version is <code>3.8.2</code>. Tried deleting the node_modules directory. 
Any help is most appreciated. </p>

<p>After running <code>npm test</code>, the error looks like this:</p>

<pre><code>&gt; testing_research@0.1.0 test C:\Users\allan.luchenitser\sandbox\testing_research
&gt; echo 'Error: no test specified'

'Error: no test specified'
</code></pre>

<p>thanks again,</p>
",https://stackoverflow.com/questions/56836435/vuejs-unit-testing-default-installation-says-no-test-specified,"['javascript', 'node.js', 'unit-testing', 'vue.js', 'babeljs']",2029,True,2,1
Unit testing around DateTime windows in NUnit &amp; Moq,"<p>I am following along with the TDD <a href=""https://github.com/wix/tdd-katas"" rel=""nofollow noreferrer"">Kata 'Greeter'</a>, wherein I have to create a class with a method which returns a different output depending on the time of day it was called. So I have this class Greeter</p>

<pre><code>public class Greeter : Greeter
{
    public DateTime time
    {
        get
        {
            return DateTime.Now;
        }
    }

    public Greeter() { }

    public string greet(string name)
    {
        string greeting = ""Hello "";

        name = name.Substring(0, 1).ToUpper() + name.Substring(1);

        if(name.Length &gt; 36)
        {
            name = name.Substring(0, 35);
        }

        if(time.Hour &gt;= 6 &amp;&amp; time.Hour &lt;= 12)
        {
            greeting = ""Good morning"";
        } else if (time.Hour &gt;= 18 &amp;&amp; time.Hour &lt;= 22)
        {
            greeting = ""Good evening"";
        } else if (time.Hour &gt;=22 || time.Hour &lt; 6)
        {
            greeting = ""Good night"";
        }

        return $""{greeting} {name}"";
   }

}
</code></pre>

<p><code>Greeter</code> implements <code>IGreeter</code></p>

<pre><code>    public interface IGreeter
    {
        DateTime time
        {
            get;
        }
        string greet(string name);
    }
</code></pre>

<p>Now on the unit testing side of things, I have to test given different times of day to see the response: <code>Good morning ~</code> in the AM, <code>Good evening ~</code> in the evening, <code>Good night ~</code> at night, and <code>Hello ~</code> in the default case. </p>

<p>So my question is, how do I design these unit tests with these time constraints in mind without too much modifying of the class? From what I've been told, changing the class just to enable unit tests is considered code smell. Is there a way I can achieve this using NUnit and Moq? The best solution I've seen so far is to DI a time provider in the constructor, but I'd rather not have to supply the generic time provider in every instantiation just to enable the tests. </p>

<p>Any guidance would be greatly appreciated.   </p>
",https://stackoverflow.com/questions/55938644/unit-testing-around-datetime-windows-in-nunit-moq,"['c#', '.net', 'nunit', 'moq']",395,True,2,2
Unit testing a kafka topology that&#39;s using kstream joins,"<p>I have a topology that does two kstream joins, the problem im facing is when trying to unit test with the TopologyTestDriver sending a couple of ConsumerRecords with pipeInput and then readOutput. It seems not to be working. </p>

<p>Im thinking this might be because the joins is using the internal rocksdb in the actual kafka which we dont use in the tests.</p>

<p>So i've been looking around for a solution for this but cant find any.</p>

<p>Note: This method of testing works perfectly fine when removing the kstream-kstream joins.</p>
",https://stackoverflow.com/questions/55063686/unit-testing-a-kafka-topology-thats-using-kstream-joins,"['java', 'unit-testing', 'join', 'apache-kafka', 'apache-kafka-streams']",1213,True,2,2
Unit testing a method that update only some properties,"<p>I want to unit test a method that set the property active of the class Person to True.</p>

<p>The class Person have many other properties :</p>

<pre><code>public class Person{
    private int id;
    private Boolean active;
    private Boolean adult;
    ... more properties

    ... getters and setters
}
</code></pre>

<p>The method to test will look something like :</p>

<pre><code>public void updatePersonStatus(int personId){
    Person person = getPersonById(personId);
    person.setActive(true);

    repository.save(person);
}
</code></pre>

<p>Is it sufficent to test only that the method save is called with an object person that have the property active true (Example using mockito):</p>

<pre><code>    @Test
    public void activateTest() {
        ArgumentCaptor&lt;Person&gt; argument = ArgumentCaptor.forClass(Person.class);
        Person testPerson = new Person();
        testPerson.setActif(true);

        responsableExamenService.updatePersonStatus(1);

        verify(theClass, times(1)).save(argument.capture()); //verify that the method save is called one time with a class Person as a parameter
        assertTrue(argument.getValue().getActive()); //and that the Object person have a property active to true.
    }
</code></pre>

<p>Or do I also need to test that every other property of Person have not bean altered ?</p>

<p>So in other words, does a unit test need to validate ""what a method should do"",
or does does it need to validate only what a method should do without verifying possible side effects ? Here an example of side effect would be besides of setting <code>active</code> to true, a developper can also set the property <code>adult</code> to true.</p>

<p>PS : The example is in Java, but the question is valid for nearly every programming language</p>
",https://stackoverflow.com/questions/55422951/unit-testing-a-method-that-update-only-some-properties,"['java', 'unit-testing']",1230,True,2,3
Live Unit Testing &quot;Unable to open configSource file&quot; error,"<p>I have a Helper project <strong>H</strong>, with a config file that is to be used as a shared <em>configSource</em> file from other projects. 
The code in file (<em>SharedConnectionString.config</em>):</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
&lt;connectionStrings&gt;
  &lt;add name=""myConn"" connectionString=""Data Source=MyServer;Initial Catalog=MyDb;Persist Security Info=True;User ID=Username; password=PW;"" providerName=""System.Data.SqlClient"" /&gt;
&lt;/connectionStrings&gt;
</code></pre>

<p>I have a test project <strong>A</strong> that have it's own <em>App.config</em> and the <em>SharedConnectionString.config</em> added as file link</p>

<p>Config files in project <strong>A</strong>:</p>

<p><img src=""https://i.stack.imgur.com/SVZGw.png"" alt=""Config files in project **A**""></p>

<p>On the <em>App.config</em> I have:</p>

<pre><code> &lt;connectionStrings configSource=""SharedConnectionStrings.config"" /&gt;
</code></pre>

<p>Now, the test project compiles, the unit tests run successfully but the Live Unit Test feature from Visual Studio presents an error:</p>

<p><img src=""https://i.stack.imgur.com/7nsl7.png"" alt=""Live Unit Testing error""></p>

<p>I tried the solution in <a href=""https://stackoverflow.com/questions/34186420/unable-to-open-configsource-file-that-was-added-as-link#39768847"">here</a> and <a href=""https://stackoverflow.com/questions/34186420/unable-to-open-configsource-file-that-was-added-as-link#50981657"">here</a>. None of there fixed the problem.</p>

<p>Opened an <a href=""https://developercommunity.visualstudio.com/content/problem/635096/live-unit-testing-unable-to-open-configsource-file.html"" rel=""nofollow noreferrer"">issue</a> with Microsoft to see if help comes from somewhere..</p>
",https://stackoverflow.com/questions/56778105/live-unit-testing-unable-to-open-configsource-file-error,"['c#', 'unit-testing', 'live-unit-tests', 'shared-config']",420,False,2,0
Unity Framework Unit Testing undefined reference to &quot;setUp&quot; and &quot;tearDown&quot;,"<p>I copied the simplest code from the <a href=""http://www.throwtheswitch.org/unity"" rel=""noreferrer"">Unity for C Unit Testing library</a> and set up a very basic test, which I copied and pasted from the site:</p>
<pre><code>#include &quot;unity/src/unity.h&quot;

int main(void)
{
    UNITY_BEGIN();
    int a = 1;
    TEST_ASSERT( a == 1 ); //this one will pass
    TEST_ASSERT( a == 2 ); //this one will fail
    return UNITY_END();
}
</code></pre>
<p>What I typed into terminal:</p>
<pre><code>gcc TestDumbExample.c ./unity/src/unity.c -o Test
</code></pre>
<p>I am getting this error message in Terminal:</p>
<pre><code>/tmp/ccqgFGn8.o: In function `UnityDefaultTestRun':
unity.c:(.text+0x26af): undefined reference to `setUp'
unity.c:(.text+0x26ca): undefined reference to `tearDown' collect2:
error: ld returned 1 exit status

Unsure why this error is occurring and it has undefined references.
</code></pre>
",https://stackoverflow.com/questions/57573905/unity-framework-unit-testing-undefined-reference-to-setup-and-teardown,"['c', 'unit-testing', 'gcc', 'compiler-errors', 'unity-test-framework']",3506,True,8,3
Mock of IBinder fails when unit testing Activity Function,"<p>I am trying to test an activity function which has the following definition:</p>

<pre><code>[FunctionName(nameof(LoadReferenceFromBlobStorage))]
public static async Task&lt;string&gt; Run([ActivityTrigger] string blobName,
    IBinder binder,
    ILogger log)
{
    StorageAccountAttribute storageAccountAtt = new StorageAccountAttribute(""AzureWebJobsStorage"");
    CloudStorageAccount storageAccount = await binder.BindAsync&lt;CloudStorageAccount&gt;(storageAccountAtt, CancellationToken.None);
    CloudBlobClient client = storageAccount.CreateCloudBlobClient();

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

<p>I mock the <code>IBinder</code> in the unit test as:</p>

<pre><code>[TestMethod]
public async Task GetReference()
{
    var attribute = new StorageAccountAttribute(""UseDevelopmentStorage=true;"");
    var mock = new Mock&lt;IBinder&gt;();
    CloudStorageAccount mockedResult = null;
    CloudStorageAccount.TryParse(""UseDevelopmentStorage=true;"", out mockedResult);
    mock.Setup(x =&gt; x.BindAsync&lt;CloudStorageAccount&gt;(attribute, CancellationToken.None))
            .ReturnsAsync(mockedResult);

    ILogger logger = NullLoggerFactory.Instance.CreateLogger(""log"");
    var res = await LoadReferenceFromBlobStorage.Run(""name"", mock.Object, logger);

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

<p>The test calls the activity successfully but the result of <code>binder.BindAsync</code> is always <em>null</em>.</p>

<p>Am I missing something?</p>
",https://stackoverflow.com/questions/54812373/mock-of-ibinder-fails-when-unit-testing-activity-function,"['c#', 'unit-testing', 'moq', 'azure-functions', 'azure-durable-functions']",712,True,2,1
Expected &#39;^169.254$&#39; to be /^169.254$/ in jasmine unit testing,"<p>I am new to Angular, Karma, Jasmine test framework. I am getting the following error. It was working fine. After upgrade to angular 7, I am getting the below error.</p>

<blockquote>
  <p>[1A[2K[31mElectron 2.0.2 (Node 8.9.3) HostComponent should call
  ipAddressPattern and check IP bad IP FAILED[39m   Expected '^169.254$'
  to be /^169.254$/.
        at 
        at UserContext.it (karma-test-shim.js:298475:34418)
        at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke
  (karma-test-shim.js:295054:26)
        at ProxyZoneSpec../node_modules/zone.js/dist/proxy.js.ProxyZoneSpec.onInvoke
  (karma-test-shim.js:294539:39)
        at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke
  (karma-test-shim.js:295053:52)
        at Zone../node_modules/zone.js/dist/zone.js.Zone.run (karma-test-shim.js:294813:43)
        at runInTestZone (karma-test-shim.js:294104:34)
        at UserContext. (karma-test-shim.js:294119:20)
        at </p>
</blockquote>

<p>My code is given below.</p>

<p>In unit test</p>

<pre><code>it(""should call ipAddressPattern and check IP bad IP"", () =&gt; {
    expect(component.ipAddressPattern(""169.254.11.11"")).toBe(new RegExp(CommonConstants.BAD_IP_ADDRESS_PATTERN));
  });
</code></pre>

<p>Earlier code was like this <code>expect(component.ipAddressPattern(""169.254.11.11"")).toBe(CommonConstants.BAD_IP_ADDRESS_PATTERN);</code> and it was working. After upgrade it gave compilation issue. So I changed to <code>expect(component.ipAddressPattern(""169.254.11.11"")).toBe(new RegExp(CommonConstants.BAD_IP_ADDRESS_PATTERN))</code>
In the common constant class, the code is given below.</p>

<pre><code>public static readonly BAD_IP_ADDRESS_PATTERN: string = ""^169\.254$"";
</code></pre>

<p>In other classes, the code is given below.</p>

<pre><code>public ipAddressPattern(ipAddress: string): RegExp {
    return CommonUtil.isBadIPAddress(ipAddress);
  }
</code></pre>

<p>In CommonUtil class, the code is given below.</p>

<pre><code>public static isBadIPAddress(ipAddress: string): any {
        if (ipAddress) {
            if (ipAddress.startsWith(CommonConstants.BAD_IP_ADDRESS)) {
                return CommonConstants.BAD_IP_ADDRESS_PATTERN;
            } else {
                return ValidationPatterns.IP_ADDRESS;
            }
        }
    }
</code></pre>

<p>Please suggest me how to fix this issue.</p>
",https://stackoverflow.com/questions/59273004/expected-169-254-to-be-169-254-in-jasmine-unit-testing,"['javascript', 'angular', 'typescript', 'unit-testing', 'karma-jasmine']",67,True,2,3
Unit Testing ref structs with private fields via Reflection,"<p>I implemented a pair of ref structs and wanted to write some unit tests for them. Naturally, all the fields are private. How do I test that the fields have correct values after certain operations assuming that the API is not supposed to reveal the internal workings of the class? I'd like to avoid modifying the ref structs themselves just to accomodate the tests.</p>

<p>My first go-to was reflection, to access the private fields, but the issue with this approach is that there's no way I can make it access the ref struct because i'd either have to box it in an object at some point, or use it as a generic type argument (which is also illegal for ref structs).</p>

<p>Is there maybe some code-gen library or something that can do this, or am I missing some other approach/solution?</p>
",https://stackoverflow.com/questions/55878525/unit-testing-ref-structs-with-private-fields-via-reflection,['c#'],330,True,2,2
Grails 3: Unit Testing Interceptors: Doesn&#39;t halt in interceptor,"<p>For demo purposes I have set up a fresh grails application with these files:</p>



<pre><code>class HalloController {

    def index() {
        String heading = request.getAttribute(""heading"")
        render ""${heading}""
    }
}
</code></pre>



<pre><code>class HalloInterceptor {

    boolean before() {
        request.setAttribute(""heading"", ""halloechen"") // *** set breakpoint here***
        true
    }

    boolean after() { true }

    void afterView() {
        // no-op
    }
}
</code></pre>

<p>When I got to <a href=""http://localhost:8080/hallo"" rel=""nofollow noreferrer"">http://localhost:8080/hallo</a> ""halloechen"" gets printed as this was set as an request attribute in the interceptors <code>before()</code> method, just like I wanted it to be.
Now I want to have a unit test for the interceptor:
</p>

<pre><code>class HalloInterceptorSpec extends Specification implements InterceptorUnitTest&lt;HalloInterceptor&gt; {

    def setup() {
    }

    def cleanup() {

    }

    void ""Test hallo interceptor matching""() {
        when:""A request matches the interceptor""
            withRequest(controller:""hallo"")

        then:""The interceptor does match""
            interceptor.doesMatch() &amp;&amp; request.getAttribute(""heading"") == ""halloechen""
    }
}
</code></pre>

<p>This test fails as the <code>heading</code> attribute does not get set to the request (which is a mocked request anyway). In fact, when running the unit test it seems as the interceptor doesn't even get called. I have set a breakpoint in the <code>before()</code> method and when debugging the test I never get there. Which is odd because I would expect a Interceptor test to call the interceptor at least.
I know I could rewrite the test as described <a href=""https://testing.grails.org/latest/guide/index.html#unitTestingInterceptors"" rel=""nofollow noreferrer"">here</a> but my point is that the interceptor doesn't get called at all.
Is that right? Another thing: calling <code>getModel()</code> in the test alway returns <code>null</code>. How do I get the model in my test?</p>
",https://stackoverflow.com/questions/54537918/grails-3-unit-testing-interceptors-doesnt-halt-in-interceptor,"['java', 'unit-testing', 'grails', 'grails-3.0', 'grails-3.3.x']",708,True,2,3
Unit Testing functions to check dispatch to be called,"<p>store.js</p>

<pre><code>const store = createStore(state,...) 
export default store;
</code></pre>

<p>myfunction.js</p>

<pre><code>import store from './store'

const myFunction = async ()=&gt;{
  store.dispatch(...some actions);
};

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

<p>mytest.js</p>

<pre><code>import store from './store';
import myFunction from './myfunction';

describe(""myFunction"", ()=&gt;{
  it(""should call dispatch"" ()=&gt;{

    await myFunction()

    // test something like below
    expect(store.dispatch).toBeCalled();

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

<p>Hi I would like to have a unit test on my helper function in react/redux application. I have created a sample functions above to give you some context. </p>

<p>As you can see, <code>myFunction</code> imports <code>store</code> and uses <code>store.dispatch</code> inside. I would like to check if <code>store.dispatch</code> has been called or not, but I am hard time achieving this. Mocking does not seem to be working because it only mocks the instance that was imported in <code>mytest.js</code> not the one in <code>myFunction.js</code> </p>

<p>I have tried to spy on it like</p>

<pre><code>const spyStore = jest.spyOn(store, ""dispatch"");
</code></pre>

<p>and I am getting error that says dispatch is undefined.</p>

<p>Any clues for this kind of situation?</p>

<p>I would greatly appreciate your input.</p>
",https://stackoverflow.com/questions/59041954/unit-testing-functions-to-check-dispatch-to-be-called,"['reactjs', 'unit-testing', 'testing', 'redux', 'jestjs']",2287,True,2,1
Unit testing Decodable: what&#39;s your approach for invalid data?,"<p>Let's say you have a JSON with several fields:</p>

<pre><code>Students: [
  student: {
    name: ""Harry""
    surname: ""Smith""
    age: 24
  },
 ...
]
</code></pre>

<p>and decodables:</p>

<pre><code>struct Students : Decodable {
    let student: [Student]
}

struct Student : Decodable {
    let name: String
    let surname: String
    let age: Int
}
</code></pre>

<p>If you want to test invalid data, do you write a sequence of tests with te following fake data?</p>

<p>Test1 data:</p>

<pre><code>{
name: null
surname: ""Smith""
age: 24
}
</code></pre>

<p>Test2 data:</p>

<pre><code>{
name: ""Harry""
surname: null
age: 24
}
</code></pre>

<p>Test3 data:</p>

<pre><code>{
name: ""Harry""
surname: ""Smith""
age: null
}
</code></pre>

<p>And maybe a test with a wrong type?</p>

<pre><code>{
name: ""Harry""
surname: ""Smith""
age: ""24"" //&lt;- string
}
</code></pre>

<p>So do you write all these tests, one for each of the above jsons or does this not make sense to you?</p>
",https://stackoverflow.com/questions/58491392/unit-testing-decodable-whats-your-approach-for-invalid-data,"['swift', 'unit-testing']",1471,True,2,3
Unit testing of DAO classes using JUnit and Mockito,"<p>I have DaoImpl class:</p>

<pre><code>public class MessageTypeDaoImpl implements MessageTypeDao{

    public int[] createMessageTypes(final List&lt;MessageType&gt; messageTypes){
        String sql = ""INSERT INTO MSG_TYPE VALUES(?, ?)"";
        return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                MessageType messageType = messageTypes.get(i);
                ps.setString(1, messageType.getMessageId());
                ps.setString(2, messageType.getMessageName());
            }

            public int getBatchSize(){
                return messageTypes.size();
            }
    });
}
</code></pre>

<p>And my test:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class MessageTypeDaoImplTest {

@Mock
private JdbcTemplate jdbcTemplate;

@Spy
@InjectMocks
MessageTypeDaoImpl messageTypeDaoImpl;
@Before
public void setUp(){
    MockitoAnnotations.initMocks(this);
}
@Test
public void createMessageTypes() {
    int[] returnCount = new int[1];
    List&lt;MessageType&gt; messageTypeList = new ArrayList&lt;MessageType&gt;();
    messageTypeList.add(getSampleMessageType());
    messageTypeDaoImpl.createMessageTypes(messageTypeList);
    doReturn(returnCount).when(messageTypeDaoImpl).createMessageTypes(messageTypeList);
    assertEquals(returnCount, messageTypeDaoImpl.createMessageTypes(messageTypeList));
}
}

public MessageType getSampleMessageType(){
    return new MessageType(""messageTypeId"", ""messageTypeName"");
}
</code></pre>

<p>Test is successful but when I run junit test with coverage it shows <code>public void setValues()</code> method is not being covered, hence my overall unit test line coverage is below the requirements. Can we cover that part? And if yes then how we do it? Thanks.</p>
",https://stackoverflow.com/questions/57964399/unit-testing-of-dao-classes-using-junit-and-mockito,"['java', 'unit-testing', 'mockito', 'junit4', 'dao']",1435,True,2,1
AlertDialog unit testing - java.lang.VerifyError: Bad type on operand stack,"<p>I have an activity <code>MyActivity.java</code> in which I am generating an <code>AlertDialog</code> using <code>AlertDialog.Builder(this);</code>.<br>
Now I am trying to write a unit test (<code>junit</code>) for <code>MyActivity.java</code> by treating is as a simple java class and creating shadow classes for Android's framework classes.
When I try to run the test, I get an error while trying to instantiate the class : <code>java.lang.VerifyError: Bad type on operand stack</code></p>

<pre><code>java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    com/domain/myApp/MyActivity.myMethod()V @31: invokespecial
  Reason:
    Type 'com/domain/myApp/MyActivity' (current frame, stack[2]) is not assignable to 'android/content/Context'
  Current Frame:
    bci: @31
    flags: { }
    locals: { 'com/domain/myApp/MyActivity', 'android/content/res/Resources' }
    stack: { uninitialized 26, uninitialized 26, 'com/domain/myApp/MyActivity' }
  Bytecode:
    0x0000000: 120f 123a b800 112a b400 03c6 000a 120f
    0x0000010: 123b b800 3c2a b600 184c bb00 3d59 2ab7
    0x0000020: 003e 4d2a 2c2b 123f b600 40b6 0041 2b12
    0x0000030: 42b6 0040 b600 432b 1244 b600 402a b700
    0x0000040: 45b6 0046 2b12 47b6 0040 bb00 4859 2ab7
    0x0000050: 0049 b600 4abb 004b 592a b700 4cb6 004d
    0x0000060: b600 4eb5 0003 2ab4 0003 b600 4f2a b400
    0x0000070: 0312 51b6 0052 c000 534e 2db6 0054 57b1
    0x0000080:                                        
  Stackmap Table:
    same_frame(@21)


    at com/domain/myApp/MyActivityTest.before(MyActivityTest.java:93)
    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(Unknown Source)
    at org.mockito.internal.runners.DefaultInternalRunner.run(Unknown Source)
    at org.mockito.junit.MockitoJUnitRunner.run(Unknown Source)
    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>From what I researched, this error is happening because I am trying to reference <code>this</code> in a static context (<code>AlertDialog.Builder</code>). So basically I am trying to reference <code>MyActivity</code> before it has been fully constructed.
<br><br>
I figured if in my <code>AlertDialog</code>'s shadow class I made <code>AlertDialog.Builder</code> class non-static, the problem would not occur during test. But that is not the case. Does anyone have any clue how can I get a workaround for this ?</p>
",https://stackoverflow.com/questions/55720762/alertdialog-unit-testing-java-lang-verifyerror-bad-type-on-operand-stack,"['android', 'junit', 'static', 'android-alertdialog']",487,True,2,1
Test Class Not Found when Unit Testing on Scala,"<p>I am trying to run the following Unit Test on Scala. I am getting error test class not found: mainFolder.TestDictionary</p>

<p>Here is what my directory looks like:</p>

<pre><code>src
  |_ mainFolder
  |     |_ Dictionary.scala
  |_ testing
        |_ TestDictionary.scala
</code></pre>

<p>Here is my <code>TestDictionary.scala</code> Unit Testing Code</p>

<pre><code>package testing

import org.scalatest._
import mainFolder.Dictionary

class TestDictionary extends FunSuite {
test(""Use many test cases for many category""){
    val test1 = ""CAT""
    val test2 = ""BAT""
    val test3 = ""DIAMOND""
    val test4 = ""THOUSAND""
    val test5 = """"
    val test6 = ""HALF""
    val test7 = ""PHOTOGRAPH""
    val test8 = ""STAFF""

    assert(Dictionary.isSounds(test1, test2) == true)
    assert(Dictionary.isSounds(test5, test7) == true)
    assert(Dictionary.isSounds(test4, test5) == true)
    assert(Dictionary.isSounds(test5, test8) == true)
    assert(Dictionary.isSounds(test3, test2) == true)
    assert(Dictionary.isSounds(test4, test1) == true)
    assert(Dictionary.isSounds(test1, test8) == true)
    assert(Dictionary.isSounds(test8, test3) == true)
    assert(Dictionary.isSounds(test5, test6) == true)
    assert(Dictionary.isSounds(test8, test2) == true)
}
}
</code></pre>
",https://stackoverflow.com/questions/54700878/test-class-not-found-when-unit-testing-on-scala,"['java', 'scala', 'unit-testing', 'intellij-idea']",2557,True,2,2
for loop not working in unit testing in django?,"<p>I am running a Simple Django Unit test of my model(User) to check the type of attribute of my model. I have a username attribute which is of CharField.
When I am running the below code it showing my test case passed with no errors and also the username is not getting printed, which is inside the for loop as following.</p>

<pre><code> class UserModelTest(TestCase):
      def test_fields(self):
          ob=User.objects.all()
          for object in ob:
              print(object.username)
              self.assertIsInstance(object.username,int)
</code></pre>

<p>I think the output should be an error since I am checking with an Integer type and the usernames should get printed.</p>

<p>Can anyone please tell me where I am doing wrong.</p>
",https://stackoverflow.com/questions/54919223/for-loop-not-working-in-unit-testing-in-django,"['django', 'python-3.x', 'unit-testing']",230,False,2,0
Unit testing: TypeError: Cannot read property &#39;pipe&#39; of undefined,"<p>I am trying to write a unit test for one of the functions in my component, in this example, it is 'setup'. 'setup' calls another function, 'additionalSetup' which subscribes to the store while doing a pipe(take(1)), and takes the first emission:</p>

<pre><code>private setup() {
    // ...declares/assigns a few variables in the component
    this.additionalSetup() ;
}

private additionalSetup() {
    this.store.pipe(take(1)).subscribe(/*logic here, but you get the idea*/);
}
</code></pre>

<p>My unit test seems to fail with the error: </p>

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

<p>Within the 'setup' unit test, I've tried to mock the 'additionalSetup':</p>

<pre><code>component.additionalSetup = jest.fn();
</code></pre>

<p>This doesn't seem to work. I am fairly new to jest and I am still learning. What approach would I take to resolve this error?</p>
",https://stackoverflow.com/questions/57960028/unit-testing-typeerror-cannot-read-property-pipe-of-undefined,"['typescript', 'unit-testing', 'jestjs', 'observable', 'ngrx']",3969,False,2,1
How to await an async Command for unit testing?,"<p>I'm trying to unit test a command but because its an async command, the test method goes into the assertions before the command is finished. I have looked up solutions to this problem and they all talk about creating an AsyncCommand interface etc which I don't want to do as I only need to await the commands for the unit tests purposes. So is there another solution to this which is simpler and doesn't require creating another interface etc?</p>

<p>this is my Command class:</p>

<pre><code>   public class Command : ICommand
    {
        public void Execute(object parameter)
        {
          //exeute...
        }

        //other stuff....
    }
</code></pre>

<p>Thats the tested class:</p>

<pre><code>pubic class MyClass
{
    private Command commandForTest;
    public Command CommandForTest
            {
                get
                {
                    if (commandForTest == null)
                    {
                        commandForTest = new Command(async (o) =&gt;
                        {
                            if(someCondition)
                               await SomeMethod();
                             else
                               await AnotheMrthod();   

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

<p>This is the test Method:</p>

<pre><code>[TestMethod]
        public async Task Test()
{
    MyClass myclass = new MyClass();
    await Task.Run( () =&gt;  myclass.CommandForTest.Execute());
    //Assert....
}
</code></pre>
",https://stackoverflow.com/questions/56425469/how-to-await-an-async-command-for-unit-testing,"['c#', 'multithreading', 'unit-testing', 'async-await', 'icommand']",1012,True,1,1
Unit testing store.mapDispatchToProps in Stencil with Redux using Jest,"<p>I am struggling to unit test the store in the componentWillLoad() lifecycle.</p>

<p>I have tried following this guide: <a href=""https://github.com/dmitry-zaets/redux-mock-store"" rel=""nofollow noreferrer"">https://github.com/dmitry-zaets/redux-mock-store</a></p>

<p>component.tsx</p>

<pre><code>  @Prop({ context: ""store"" }) store: Store;

  componentWillLoad() {
    this.store.mapDispatchToProps(this, { updateStep });
  }
</code></pre>

<p>spec.ts</p>

<pre><code>   const middlewares = [thunk];
   const mockStore = configureStore(middlewares);

   const mapDispatchToProps = () =&gt; ({ type: updateStep});

   it('should test componentWillLoad', () =&gt; { 

    const initialState = {};
    const store = mockStore(initialState);

    store.dispatch(mapDispatchToProps());
    const actions = store.updateStep();
    const expectedPayload = { type: updateStep};
    expect(actions).toEqual([expectedPayload]);

});
</code></pre>

<p>I get the following error atm: TypeError: mockStore is not a function</p>
",https://stackoverflow.com/questions/56273400/unit-testing-store-mapdispatchtoprops-in-stencil-with-redux-using-jest,"['redux', 'jestjs', 'stenciljs']",193,False,1,0
Unit Testing a fluent API with mocking in Spock,"<p>Spock makes a strong distinction between a Stub and Mock. Use a stub when what to change want comes back from a class your class under test uses so that you can test another branch of an if statement.  Use a mock, when you don't care what comes back your class under test just call another method of another class and you want to ensure you called that.  It's very neat. However suppose you have a builder with a fluent API that makes people.  You want to test a method that calls this Builder.</p>

<pre><code>Person myMethod(int age) {
     ...
     // do stuff
     ...
     Person tony = 
            builder.withAge(age).withHair(""brown"").withName(""tony"").build();
     return tony; 
}
</code></pre>

<p>So originally, I was thinking just mock the builder and then the unit test for myMethod() should check withAge(), withHair() with the right parameters.</p>

<p>All cool.</p>

<p>However -- the mock methods return null.  Meaning you can't use the fluent API.</p>

<p>You could do.</p>

<pre><code>Person myMethod(int age) {
     ...
     // do stuff
     ...

     builder.withAge(age);
     builder.withHair(""brown"");
     builder.withName(""tony"");
     builder.build();
     return tony; 
}
</code></pre>

<p>which works.  You test will work but it defeats the purpose of using the fluent API.</p>

<p>So, if you are using fluent APIs, do you stub or mock or what?</p>
",https://stackoverflow.com/questions/57298557/unit-testing-a-fluent-api-with-mocking-in-spock,"['unit-testing', 'mocking', 'spock']",787,True,1,1
"Trouble unit-testing &quot;Imperative shell, functional core&quot; in Python","<p>I am creating a class that inherits from <code>NamedTuple</code> (for immutability, specifically) that contains three pieces of data in the tuple. I am overriding the <code>__repr__()</code> to provide a pretty, human-recognizable representation of the class. However, the custom <code>__repr__</code> has to do a few expensive calculations with the data in the tuple in order to provide the pretty representation. As such, my <code>__repr__</code> function is organized in the following manner:   </p>

<pre><code>class MyClass(NamedTuple):
   data1: float
   data2: MyOtherClass
   data3: float


def __repr__():
    exp_1 = self.expensive_function1(self.data1, self.data2, self.data3)
    exp_2 = self.expensive_function2(self.data1, self.data2, self.data3)

    repr_component_1 = MyClass.static_func1(self.data1, exp_1, exp_2)
    repr_component_2 = MyClass.static_func2(self.data2, exp_1, exp_2)
    repr_component_3 = MyClass.static_func2(self.data3, exp_1, exp_2)

    return f""{repr_component_1} {repr_component_2}{repr_component_3}""
</code></pre>

<p>There is no problem with the code itself. It runs great and works fine. The problem I am having is how to effectively <strong>unit test</strong> the static methods <code>repr_component_1</code>, <code>repr_component_2</code>, and <code>repr_component_3</code>.</p>

<p>If <code>MyClass</code> did not specifically need to be immutable, I could throw <code>exp_1</code> and <code>exp_2</code> into private class attributes and have no problems. However, <code>MyClass</code> must be immutable for various reasons. </p>

<p>The trouble is that <code>exp_1</code> and <code>exp_2</code> are <strong>instance specific</strong> results that are then going into <strong>static methods</strong> as inputs. </p>

<p>As such, the only way I can think of testing this (with <code>pytest</code>) is as follows:</p>

<pre><code>def test_repr_component_1():
    a = MyClass(data1, data2, data3)
    exp_1 = a.expensive_function1(self.data1, self.data2, self.data3)
    exp_2 = b.expensive_function2(self.data1, self.data2, self.data3)
    result1 = MyClass.static_func1(a.data1, exp_1, exp_2)
    assert result1 == ""expected result""
</code></pre>

<p>However, that's many lines per test scenario (my actual code has more than five lines)! Of course, I wish to test many scenarios. I have heard of set-up and tear-down stuff before but I don't know if that stuff applies in this situation.</p>

<p>Would like to get some thoughts on a ""professional"" and pythonic way of writing these unit tests.</p>

<p><strong>EDIT:</strong> It did occur to me to use a Python 3.7 <code>dataclass</code> (because of its ability to be 'frozen') which would allow me to set <code>exp_1</code> and <code>exp_2</code> as private attributes during the <code>__post_init__</code> step but I plan on making this a public library and didn't want to have to rely on users having only Python >= 3.7 to make it work.</p>
",https://stackoverflow.com/questions/56173577/trouble-unit-testing-imperative-shell-functional-core-in-python,"['python', 'unit-testing', 'pytest']",153,True,1,1
Can we modify Vuex action for jest unit testing?,"<p>I've created a store in my test file</p>

<pre><code>import {
shallowMount,
createLocalVue
} from '@vue/test-utils'
import Vuex from 'vuex'
import Actions from '../../../src/components/Actions'

const localVue = createLocalVue()

localVue.use(Vuex)

describe('Actions.vue', () =&gt; {
  let actions
  let store

beforeEach(() =&gt; {
    actions = {
        actionClick: jest.fn(() =&gt; Promise.resolve({}))
    }
    store = new Vuex.Store({
        actions
    })
})

it('should go to then block', () =&gt; {
    const wrapper = shallowMount(Actions, {
        store,
        localVue
    })
    //goes to then block
})

it('should go to catch block', () =&gt; {
    actions.actionClick = jest.fn(() =&gt; Promise.reject(new Error()))
    const wrapper = shallowMount(Actions, {
        store,
        localVue
    })
    //still goes to then block and not the catch block
  })
})
</code></pre>

<p>As per the code above the im not able to achieve the second test block means it is not modifying the actionClick function in store.</p>
",https://stackoverflow.com/questions/56043992/can-we-modify-vuex-action-for-jest-unit-testing,"['vue.js', 'vuejs2', 'jestjs', 'vuex', 'vue-test-utils']",1116,True,1,1
unit testing with nunit with integration with jenkins C#,"<p>To preface, I've already installed the Jenkins plugin for NUnit, I'm using the following plugins :</p>

<ul>
<li>NUnit v3.12.0</li>
<li>NUnit3TestAdaptor</li>
<li>Microsoft.NET.Test.Sdk </li>
<li>Microsoft.NETcore.App</li>
</ul>

<p>All installed via NuGet on Visual Studio 2017.</p>

<p>This is the batch command I'm using to try to run the unit test after being committed to Jenkins.</p>

<pre><code>""C:\ProgramData\chocolatey\bin\nunit3-console.exe""
testCSharpe\bin\Debug\netcoreapp2.1\testCSharpe.dll
</code></pre>

<p>When I build the project, it keeps showing me this error.</p>

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

<p>Any idea how to go about this? </p>
",https://stackoverflow.com/questions/56219785/unit-testing-with-nunit-with-integration-with-jenkins-c,"['jenkins', 'nunit']",86,False,1,1
Unit Testing on Java&#39;s ListenableFuture and the addListener callback,"<p>I have a module that has a method which writes data to a Kinesis stream. We call it the Feedback stream.</p>

<p>i want to run a verify unit test on my analytics service's functions that are invoked on ListenableFuture's result, i have tried setting up mocks but am getting a ClassCast exception. I think I may be setting up the mocks incorrectly.</p>

<p>method i want to unit test:</p>

<pre><code>public void writeData(KinesisRecord kinesisRecord, Response response) {

    FeedbackRecord feedbackRecord = new 
    FeedbackRecord(kinesisRecord.getVersion(), kinesisRecord.getNotificationId(), response.name(), 
kinesisRecord.getDestination());

    Gson g = new Gson();
    byte[] dataBytes = g.toJson(feedbackRecord).getBytes(StandardCharsets.UTF_8);
    ListenableFuture&lt;UserRecordResult&gt; future = kinesisProducer.addUserRecord(streamName, kinesisRecord.getNotificationId(), ByteBuffer.wrap(dataBytes));

    future.addListener(() -&gt; {
    try {
        UserRecordResult userRecordResult = future.get();
        analyticsService.trackSuccess(AnalyticsConstants.FeedbackProducer.WRITE_SUCCESS, AnalyticsConstants.FeedbackProducer.WRITEDATA_LOCATION + "" "" + userRecordResult.getSequenceNumber());
        log.debug(""Write to Kinesis Feedback successful, record sequence number: "" + userRecordResult.getSequenceNumber());
    } catch (InterruptedException e) {
        e.printStackTrace();
        analyticsService.trackError(AnalyticsConstants.FeedbackProducer.WRITE_ERROR, AnalyticsConstants.FeedbackProducer.WRITEDATA_LOCATION);
        log.error(""Feedback Kinesis Write failed: "" + e);
    } catch (ExecutionException e) {
        e.printStackTrace();
        analyticsService.trackError(AnalyticsConstants.FeedbackProducer.WRITE_ERROR, AnalyticsConstants.FeedbackProducer.WRITEDATA_LOCATION);
        log.error(""Feedback Kinesis Write failed: "" + e);
    }
}, MoreExecutors.directExecutor());
</code></pre>

<p>}
unit test attempt:</p>

<pre><code>@Test
public void addUserRecordFutureTest() throws ExecutionException, InterruptedException {

    ListenableFuture&lt;UserRecordResult&gt; responseFuture = mock(ListenableFuture.class);

    Attempt attempt = new Attempt(1, 2, ""AttemptError"", ""5xx"", true);
    List&lt;Attempt&gt; attempts = new ArrayList&lt;&gt;();
    attempts.add(attempt);
    UserRecordResult mockUserRecordResult = mock(UserRecordResult.class);

    when(kinesisProducer.addUserRecord(any(), any(), any())).thenReturn(responseFuture);
    doAnswer(invocation -&gt; {
        ListenableFutureCallback listenableFutureCallback = invocation.getArgument(0);
        listenableFutureCallback.onSuccess(mockUserRecordResult);
    // do asserts here
        return null;
    }).when(responseFuture).addListener(any(), any());

    feedbackProducer.writeData(mockRecord, FeedbackProducer.Response.invalid_channel);
}
</code></pre>

<p>STACK TRACE:</p>

<p><a href=""https://i.stack.imgur.com/q2cxE.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/q2cxE.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/57380417/unit-testing-on-javas-listenablefuture-and-the-addlistener-callback,"['java', 'unit-testing', 'java-8', 'mockito', 'future']",2266,False,2,0
D3js in a React Component Unit Testing using Jest/Enzyme,"<p><strong>Problem:</strong> When I run my code, the SVG appends to the outer div on the component and renders on the page perfectly. However, during testing, the SVG is not appended to the outer div.</p>

<p><strong>Stack:</strong> I am trying to test my d3js element wrapped in a React component using Jest/Enzyme.</p>

<p><strong>Research I did so far:</strong> Looked up a bunch of guides/posts on testing d3js using google and on stackoverflow. Used a guide on unit testing d3js and React with Jasmine. I have also read that testing 3rd party libraries may be difficult with Enzyme so this may be a limitation of the testing framework.</p>

<p>I have included a basic sample of code to test.</p>

<p><strong>Component:</strong></p>

<pre><code>import React from ""react"";
import * as d3 from ""d3"";

export default class Circle extends React.Component {

    componentDidMount = () =&gt; {
        return this.renderCircle();
    }

    renderCircle = () =&gt; {
        d3.select(""#outerDiv"")
            .append(""svg"")
            .attr(""width"", 600)
            .attr(""height"", 300)
            .append(""circle"")
            .attr(""id"", ""d3-el"")
            .attr(""cx"", 300)
            .attr(""cy"", 150)
            .attr(""r"", 30)
            .attr(""fill"", ""#ff0000"")
            .on(""click"", function (d, i) {
                var item = d3.select(this);
                item.attr(""fill"", ""#00ff00"");
            });
    }

    render() {
        return &lt;div id=""outerDiv"" /&gt;;
    }

}
</code></pre>

<p><strong>Test:</strong></p>

<pre><code>import React from ""react"";
import * as d3 from ""d3"";
const jsdom = require(""jsdom"");
const ReactJSDOM = require('react-jsdom');
const { JSDOM } = jsdom;
import Circle from ""./Circle.js"";
import { mount } from ""enzyme"";
import sinon from 'sinon';

describe(""Circle"", () =&gt; {
    it(""d3js element should be appended to outer div"", () =&gt; {
        let wrapper = mount(&lt;Circle /&gt;);
        let instance = wrapper.instance();
        const jsdomElem = ReactJSDOM.render(&lt;html&gt;&lt;body&gt;&lt;p&gt;&lt;Circle /&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;);
        console.log(jsdomElem.querySelector(""#d3-el"")); // returns null
        console.log(wrapper.find(""d3-ele"").get(0));; // returns undefined
        console.log(d3.select(""d3-el"")); // returns null
        expect(wrapper.find(""d3-el"").exists()).toEqual(true);
    }
}
</code></pre>

<p>Doing a find on the d3 element that is supposed to be rendered using wrapper.find(), document.querySelector(), and d3.select() all return undefined or null.</p>

<p><strong>Things I have tried but does not append the SVG element to the outer div:</strong></p>

<ol>
<li><p>Using mount() on the component.</p></li>
<li><p>Using instance() of the mounted component and calling the renderCircle() method directly.</p></li>
<li><p>Using ReactJSDOM to render a whole DOM from top to bottom.</p></li>
<li><p>A bunch of other stuff that probably makes no sense including sinon.spy() and mocking a jest.fn().</p></li>
</ol>

<p>None of these methods work and if I do a find on the outer div, it does not show that the div has any children elements. Doing a debug on the wrapper shows the same thing.</p>

<p>Would love some help to get this SVG appended to the div during testing. Any solutions or other strategies would be greatly appreciated. Please let me know if you have any questions or if I should add more information. Thanks!</p>
",https://stackoverflow.com/questions/55104250/d3js-in-a-react-component-unit-testing-using-jest-enzyme,"['reactjs', 'd3.js', 'jestjs', 'enzyme', 'jsdom']",3493,True,7,2
Unit Testing a method containing Environment.Exit() call within it,"<p>I have a public method say, </p>

<pre><code>public void ErrorEncounter()
{
//Global Error Counter
gblErrorCount++;

//Process tremination
Environment.Exit();
}
</code></pre>

<p>This method terminates whenever it is called. However, it will update the <strong>Global Error Count</strong> which i'm suppose to test. Is there any way to perform Unit Testing on this method?</p>

<p>I'm Using <strong>NUnit</strong> Framework for Unit Testing.</p>
",https://stackoverflow.com/questions/55467019/unit-testing-a-method-containing-environment-exit-call-within-it,"['c#', 'unit-testing', 'nunit']",1618,True,1,2
C++ unit testing framework with type and value parametrisation,"<p>I am looking for a unit testing framework that allows passing type and value parameters to test function at the same time. </p>

<p>Example: let's say I have a few template sorting functions:</p>

<pre><code>template&lt;class ITERATOR, class COMPARATOR = std::less&lt;typename std::iterator_traits&lt;ITERATOR&gt;::value_type&gt;&gt;
void selectionSort(const ITERATOR first,const ITERATOR last, const COMPARATOR comparator = COMPARATOR ()){ ... };

template&lt;class ITERATOR, class COMPARATOR = std::less&lt;typename std::iterator_traits&lt;ITERATOR&gt;::value_type&gt;&gt;
void insertionSort(const ITERATOR first,const ITERATOR last, const COMPARATOR comparator = COMPARATOR ()) { ... }
</code></pre>

<p>and I want to test these functions with different input types as:</p>

<pre><code>template&lt;class T&gt;
vector&lt;T&gt; makeRandomVector(int size){ ... }

vector&lt;int&gt; intVec = makeRandomVector&lt;int&gt;(10);  //10 is vector size
someSort(intVec.begin(),intVec.end())
vector&lt;MyCustomStruct&gt; structVec = makeRandomVector&lt;MyCustomStruct&gt;(10);  
someSort(structVec.begin(),structVec.end())
</code></pre>

<p>and with different size arguments for <code>makeRandomVector</code> to test these function if vector size is 0,1,10 etc.</p>

<p>So I am looking for C++ unit testing framework that allows creating test that would accept type (int,MyCustomStruct) and value parameters (0,1,10) at the same time and perform the test for each element of the cartesian product of Types x Values. </p>
",https://stackoverflow.com/questions/55023264/c-unit-testing-framework-with-type-and-value-parametrisation,"['c++', 'unit-testing']",239,True,1,1
Unit Testing Razor Pages that inherit from a BasePageModel,"<p>I have a Razor Pages app where several services are used by all pages in the site and have added those services to a <code>BasePageModel</code>, that I inherit from on each Razor Page. My <code>BasePageModel</code> looks something like this:</p>

<pre><code>public abstract class BasePageModel : PageModel
{
    private IUserClaimsService _userClaims;
    private IAuthorizationService _authService;

    protected virtual IUserClaimsService UserClaimsService =&gt; _userClaims ?? (_userClaims = HttpContext.RequestServices.GetService&lt;IUserClaimsService&gt;());
    protected virtual IAuthorizationService AuthService =&gt; _authService ?? (_authService = HttpContext.RequestServices.GetService&lt;IAuthorizationService&gt;()); 
}
</code></pre>

<p>The Razor Page itself would look something like this:</p>

<pre><code>public class IndexModel : BasePageModel
{
    public async Task&lt;ActionResult&gt; OnGet()
    {
        var HasAccess = (await AuthService.AuthorizeAsync(User, ""PermissionName"")).Succeeded;
        if (!HasAccess)
        {
            return new ForbidResult();
        }
        return Page();
    }
}
</code></pre>

<p>I am creating unit tests to test authorization on my Razor Pages. My authorization has policies that depend on user claims. What I'd like to do is to mock the user claims and test whether authorization succeeds or fails accordingly, depending on the page. However, I am not able to get to the <code>UserClaimsService</code> to mock it from my test. I instantiate the pageModel but am unable to get to any of the <code>BasePageModel</code> values (e.g. <code>UserClaimsService</code>). Any idea how I might go about doing this?</p>
",https://stackoverflow.com/questions/56652711/unit-testing-razor-pages-that-inherit-from-a-basepagemodel,"['c#', 'unit-testing', 'asp.net-core', 'razor-pages']",1677,True,1,1
Mock Http get request for unit testing angular service,"<p>I want to know how I can test my service function that has a http get and post calls. I could configure the spec file where I could create an instance of the service, also followed few sites for creating a mockhttp service, It says ""httpMock.expectOne is not a function""</p>

<p>reference from here: <a href=""https://alligator.io/angular/testing-http-interceptors/"" rel=""nofollow noreferrer"">https://alligator.io/angular/testing-http-interceptors/</a></p>

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

class AppLookupServiceStub {
    //some functions
}

UserSearchService = new UserSearchService(httpMock,
    appLookUpService);

beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        imports: [
            HttpClientTestingModule
          ],
    providers: [
        AppHttpService,
        HttpClient,
        AppCookieService,
        CookieService,
        { provide: AppLookupService, useClass: AppLookupServiceStub },
        AppConstants
    ]
    });
});

beforeEach(async() =&gt; {
    service = TestBed.get(UserSearchService);
    httpMock = TestBed.get(AppHttpService);

    selectedCriteria = [
        //some data
    ]
    UserSearchOptions = {
        //some data
    }
});

it('should have a service instance', () =&gt; {
    expect(service).toBeDefined();
});
it('should make expected calls to getUserSerachOptions', inject(
    [AppHttpService, UserSearchService],
    (
      httpMock: AppHttpService,
      dataService: UserSearchService
    ) =&gt; {
    // let spy = spyOn(service, 'getUserSerachOptions');
    // UserSearchService.getUserSerachOptions();
    // expect(spy).toBeDefined();

    dataService.getUserSerachOptions().subscribe(UserSearchOptions =&gt; {
        expect(UserSearchOptions).toEqual(UserSearchOptions);
    });

    const req = httpMock.expectOne(`AppConstants.ADMIN_CENTRAL_SELECTION_CRITERIA_URL`);
    expect(req.request.method).toBe(""GET"");
    req.flush(UserSearchOptions);
}));
it('should get the data successful', () =&gt; {
    service.getUsersBySelectionCriteria(selectedCriteria[0]).subscribe((data: any) =&gt; {
        console.log(data);
      expect(data.country.name).toBe('Australia');
    });
});

})
</code></pre>

<p>test spec for service:</p>

<pre><code>getUserSerachOptions(): Observable&lt;UserSearchOptions&gt; {
if (!this.userSearchCriteriaOptions) {

    return this.appHttpService.get('{apiUrl}/xyzproject/{devKey}/userSelectionCriteria').pipe(map(
      (data: UserSearchOptions) =&gt; {
        this.userSearchCriteriaOptions = data;
        return  this.userSearchCriteriaOptions;
      }
    ));
}

return of( this.userSearchCriteriaOptions);
}
</code></pre>

<p>How do I mock the get call, I am unable to find any sources in this case.</p>
",https://stackoverflow.com/questions/56558452/mock-http-get-request-for-unit-testing-angular-service,"['angular', 'typescript', 'rxjs', 'mocking', 'jasmine']",5092,True,1,1
Unit Testing LiveData returned from Room inside a method,"<p>I have a method which gets a LiveData object from from the DAO layer of Room and then does some operations on the LiveData object. </p>

<p>Whenever I try to do <code>dataStorage.getAllSections()</code> it returns a LiveData object, and the value is always null. (My DB is prepopulated) </p>

<p>I have declared the JUnit Rule for LiveData</p>

<pre><code>@get:Rule
val rule = InstantTaskExecutorRule()
</code></pre>

<p>In my actual class if I create a extension function to wait on the LiveData like this, </p>

<pre><code>private fun &lt;T&gt; LiveData&lt;T&gt;.blockingObserve(): T? {
    var value: T? = null
    val latch = CountDownLatch(1)

    val observer = Observer&lt;T&gt; { t -&gt;
        value = t
        latch.countDown()
    }

    observeForever(observer)

    latch.await(2, TimeUnit.SECONDS)
    return value
}
</code></pre>

<p>and do,</p>

<pre><code>dataStorage.getAllSections.blockingObserve()
</code></pre>

<p>The unit test runs fine. I do not get a null pointer exception. 
I have even tried running the test with <code>runBlocking</code> but that does not help either. </p>

<pre><code>This is my method I am trying to test: 

@VisibleForTesting
fun buildDataFromDB(): LiveData&lt;List&lt;SectionModel&gt;&gt; {

    Logger.d(TAG, ""Building data from DB"")

    val sections = dataStorage.getAllSections() 
    // sections.value is always null even though my DB is populated 
    sections.value?.forEach { section -&gt;
        // Do something 
        }
    }

    Logger.d(TAG, ""Building data from DB completed"")

    return sections
}
</code></pre>

<p>This is my test case: </p>

<pre><code>@Test
fun test_buildDataFromDb() = runBlocking {
    val result = appDataProvider.buildDataFromDB().blockingObserve()
    // asserts
}
</code></pre>
",https://stackoverflow.com/questions/55963569/unit-testing-livedata-returned-from-room-inside-a-method,"['android', 'junit', 'android-room', 'android-livedata', 'android-instrumentation']",352,False,1,0
How emphasize restrictions for input data in unit testing?,"<p>I have parametrized test, for example:</p>

<pre><code>import pytest
from datetime import time


def get_next_hour(time_str: str):
    t = time(*map(int, time_str.split(':')))
    new_t = time((t.hour + 1) % 24, t.minute)
    return new_t.strftime('%H:%M')


@pytest.mark.parametrize(
    ""t_str, result_str"",
    [
        ('10:30', '11:30'),
        ('11:30', '12:30'),
    ]
)
def test_good_input(t_str, result_str):    
    result = get_next_hour(t_str)
    assert result == result_str
</code></pre>

<p>Test <code>test_good_input</code> must work only with valid time strings (for invalid data I have another test <code>test_bad_input</code>). How I can emphasize it - in docstring, or using assert for input data?</p>

<p>With docstring</p>

<pre><code>def test_good_input(t_str, result_str):
    """"""for t_str allowed only time-valid strings""""""

    result = get_next_hour(t_str)
    assert result == result_str
</code></pre>

<p>With validation input</p>

<pre><code>def test_good_input(t_str, result_str):

    assert ':' in t_str, 'input data is not time'

    result = get_next_hour(t_str)
    assert result == result_str
</code></pre>

<p>Or there is another ways?</p>
",https://stackoverflow.com/questions/54588510/how-emphasize-restrictions-for-input-data-in-unit-testing,"['python', 'unit-testing', 'pytest', 'design-by-contract']",68,True,1,2
Cypress unit testing: how to check for script errors?,"<p>Is there a way to check if there are any script errors in the JavaScript console after page load when testing with Cypress testing framework?</p>

<p>I know I can check for visibility of certain dom elements, but I was curious if there is a more generalized check? </p>

<p>Thanks</p>
",https://stackoverflow.com/questions/54200436/cypress-unit-testing-how-to-check-for-script-errors,"['javascript', 'unit-testing', 'cypress']",770,False,1,0
F# Using Pose to Shim printfn for unit testing,"<p>I'm trying to use Pose (<a href=""https://github.com/tonerdo/pose"" rel=""nofollow noreferrer"">https://github.com/tonerdo/pose</a>) to shim out <code>printfn</code> so I can unit test what is passed to it. I've managed to get it working if I'm passing a <code>TextWriterFormat</code> that doesn't take additional arguments, but when I  try to shim one that does take additional arguments I get a Mismatched instance types exception</p>

<p>This works:</p>

<pre><code>let workingPrintfTest () =
    let a = Printf.TextWriterFormat&lt;unit&gt;(""herp"")
    Printf.printfn a

let workingShim =
    Shim
        .Replace(fun () -&gt;
            Printf.printfn(Is.A&lt;Printf.TextWriterFormat&lt;unit&gt;&gt;())
        )
        .With(Func&lt;Printf.TextWriterFormat&lt;unit&gt;, unit&gt;(fun s -&gt;
            Console.WriteLine(""Hijacked: "" + s.ToString())
        ))

    PoseContext.Isolate ((fun () -&gt;
        Program.workingPrintfTest ()   // Hijacked: herp
    ), workingShim)
</code></pre>

<p>However, when I change <code>herp</code> to <code>herp: %s</code> and the <code>TextWriterFormat</code> becomes <code>TextWriterFormat&lt;string -&gt; unit&gt;</code> is when I get the mismatched instance types exception.</p>

<p>This throws exception:</p>

<pre><code>let printfTest toPrint =
    let a = Printf.TextWriterFormat&lt;string -&gt; unit&gt;(""herp: %s"")
    Printf.printfn a toPrint

let shim =
    Shim
        .Replace(fun () -&gt;
            let a = Is.A&lt;Printf.TextWriterFormat&lt;string -&gt; unit&gt;&gt;()
            Printf.printfn a (Is.A&lt;string&gt;())
        )
        .With(Func&lt;Printf.TextWriterFormat&lt;string -&gt; unit&gt;, unit&gt;(fun s -&gt;
                Console.WriteLine(""Hijacked: "" + s.ToString())
                ()
            )
        )

PoseContext.Isolate ((fun () -&gt;
    Program.printfTest ""www""
), shim)
</code></pre>

<p>And the accompanying Exception: <code>Pose.Exceptions.InvalidShimSignatureException: Mismatched instance types</code></p>

<p>I'm running this in .Net Core 2.2</p>

<p>Any help would be appreciated.</p>
",https://stackoverflow.com/questions/55985219/f-using-pose-to-shim-printfn-for-unit-testing,"['unit-testing', '.net-core', 'f#']",171,False,1,0
Unit testing .net project by Asserting Status Code returning,"<p>I am new to unit testing and <code>xunit</code>. I am writing unit tests that assert status codes returning. Is this something in the scope of Integration test or is it meeting unit testing logic?</p>

<p>For example I am asserting a get function's response like this: </p>

<pre class=""lang-cs prettyprint-override""><code>[Fact]
public async Task MyTest()
{
    SearchParam searchParam = new SearchParam() { };
    var bool= false;
    var bool2 = false;
    var actionResult = await _controller.Myfunction(searchParam, bool, bool2).ConfigureAwait(false);
    var okResult = actionResult.Result as OkObjectResult;
    Assert.True(okResult.StatusCode == 200, ""Ok"");
}
</code></pre>
",https://stackoverflow.com/questions/58435144/unit-testing-net-project-by-asserting-status-code-returning,"['c#', '.net', 'unit-testing', 'xunit.net']",406,True,1,1
Replace a class within a Dll for unit testing,"<p>My target is to check DLL using unit testing.
I already have a project that loads the DLL and checks it using Google tests.
Now I want to replace one of the classes within the DLL with a mock and repeat the tests.</p>

<p>Is is possible? How can I do it?</p>
",https://stackoverflow.com/questions/54178558/replace-a-class-within-a-dll-for-unit-testing,"['c++', 'unit-testing', 'dll', 'mocking', 'googletest']",137,False,1,1
How to show code coverage on Unity3D unit testing?,"<p>I wrote some unit tests to my scripts in Unity3D. Is there any way to show code coverage? I run tests with Unity Test Runner and working on VS for Mac.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/55608349/how-to-show-code-coverage-on-unity3d-unit-testing,"['c#', 'visual-studio', 'unit-testing', 'unity-game-engine', 'rider']",621,False,1,1
Unit Testing to see if JSON file is null,"<p>I am currently trying to unit test a container that pulls in a static JSON file of phone numbers and passes it to the component to display, however I am not sure how I should go about testing it. The code for the container is as follows: </p>

<pre><code>import React from 'react';
import data from *JSON file location*
import CountryInfo from *component for the country information* ;

class CountryInfoContainer extends React.Component {
 constructor(props, context) {
   super(props, context);
   this.state = {
     numbersJson: null
   };
 }

 async componentWillMount() {
   const numbersJson = data;
   this.setState({ numbersJson });
 }

 render() {
   return (
       &lt;CountryInfo json={this.state.numbersJson} showText={this.props.showText} /&gt;
   );
 }
}

export default CountryInfoContainer;

</code></pre>

<p>I currently have my unit test to look like this</p>

<pre><code>import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import { mount, configure } from 'enzyme';
import { MemoryRouter } from 'react-router-dom';
import CountryInfoContainer from './CountryInfoContainer';

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

describe('Successful flows', () =&gt; {
  test('checks if json has null entries', () =&gt; {
    const wrapper = mount(&lt;MemoryRouter&gt;&lt;CountryInfoContainer /&gt;&lt;/MemoryRouter &gt;);
    const data = wrapper.find(numbersJson);
    // eslint-disable-next-line no-console
    console.log(data.debug);
  });
});
</code></pre>

<p>Obviously, it doesn't work now because I am not sure how to use the variable numbersJson in the container in the test file or how to check if it is null.</p>
",https://stackoverflow.com/questions/58753339/unit-testing-to-see-if-json-file-is-null,"['json', 'reactjs', 'enzyme']",356,True,1,1
Unit Testing In Network With Using Volley in Android,"<p>I am trying to test functions from my Presenter Class. In below, I can reach <code>getSomeThing()</code> function however, I cannot reach the <code>getData()</code> and <code>getError()</code> functions. </p>

<p>Volley functions are not working in unit tests. Further help would be highly appreciated as I am struggling with this for over a week. </p>

<p>Below is my Presenter Class, Presenter Listener and Test Function.</p>

<p>my Presenter Class:</p>

<pre><code>public abstract class SomePresenter implements BasePresenterListener {

    private static final String sTAG = SomePresenter.class.getSimpleName();

    private Context context;
    private Integer testInteger;

    protected SomePresenter(Context context, Integer testInteger) {
        this.context = context;
        this.testInteger = testInteger;
        onResponse();
    }

    @Override
    public void onResponse() {
        try {
            Thread.sleep(1000);
            getSomeThing();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        final GetRequest&lt;SomeResponse&gt; someResponseRequest =
                ApiRequests.getSomeResponse(
                        new Response.Listener&lt;SomeResponse&gt;() {
                            @Override
                            public void onResponse(SomeResponse response) {
                                getData(response);
                            }
                        }
                        ,
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                ErrorResponse errorResponse = new ErrorResponse();
                                errorResponse.setMessage(Constant.NETWORK_ERROR);
                                getError(errorResponse);
                            }
                        }
                );

        NetworkInstance.addRequest(context, poiResponseGetRequest, sTAG);
    }

    public static void cancelRequest(Context context) {
        NetworkInstance.cancelAllRequests(context, sTAG);
    }

    protected abstract void getSomeThing();

    protected abstract void getData(SomeResponse response);

    protected abstract void getError(ErrorResponse response);
}
</code></pre>

<p>my BasePresenter Class: </p>

<pre><code>public interface BasePresenterListener {
    void onResponse();
}

</code></pre>

<p>my Unit Test Function:</p>

<pre><code>    @Test
    public void test() throws InterruptedException {
        new SomePresenter(mockContext, 107){

            @Override
            protected void getData(PoiResponse response) {
                SomeLogger.debug(""getData works"");//this is not called.
            }

            @Override
            protected void getSomeThing() {
                SomeLogger.debug(""getSomeThing works!"");//this is called.
            }

            @Override
            protected void getError(ErrorResponse response) {
                SomeLogger.debug(""ErrorResponse works!""); //this is not called.
            }
        };
    }

</code></pre>

<p>I have looked below links none of them solved my problem.</p>

<p><a href=""https://stackoverflow.com/questions/37032558/unit-testing-a-network-response-works-when-debugging-not-when-actually-running"">Unit testing a network response. Works when debugging, not when actually running</a></p>

<p><a href=""https://stackoverflow.com/questions/24399423/android-unit-test-with-volley"">Android Unit test with Volley</a><a href=""https://stackoverflow.com/questions/24399423/android-unit-test-with-volley""></a></p>

<p>In my case is I can reach the <code>getSomething()</code> function from unit test  but I cannot reach the <code>getData()</code> nor <code>getError()</code> functions because Volley does not seem to work in unit tests. </p>

<p>All, <code>getSomething()</code>, <code>getData()</code>, <code>getError()</code> functions are callback functions, I can reach the <code>getSomeThing()</code> function but I cannot reach the <code>getData()</code> and <code>getError()</code> functions.</p>
",https://stackoverflow.com/questions/58389841/unit-testing-in-network-with-using-volley-in-android,"['java', 'android', 'unit-testing', 'junit', 'android-volley']",123,False,1,0
"Trying unit testing store, How to make it work?","<p>I have this store.js file</p>

<pre><code>import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const mutations = {
  increment: state =&gt; state.count++,
  Changeloading(state, status) { state.loading = status },
  ChangeUserGroup(state, newGroup) { state.userGroup = newGroup; },
  ChangeOriginalRole(state, newRole) { state.originalRole = newRole; }
}
export default new Vuex.Store({
  state: {
    count: 0,
    loading: false, //header, TeamLead, TeamMember
    listUserGroup: [],
    userRole: """",
    originalRole: """",
    userGroup: {}
  },
  mutations,
 ...
})
</code></pre>

<p>In my testing file store.spec.js</p>

<pre><code>import { expect } from 'chai'
import mutations from '@/store'

// destructure assign `mutations`
const { increment } = mutations

describe('mutations', () =&gt; {
  it('INCREMENT', () =&gt; {
    // mock state
    const state = { count: 0 }
    // apply mutation
    increment(state)
    // assert result
    expect(state.count).to.equal(1)
  })
})

</code></pre>

<p>This is the result i am getting:</p>

<p>mutations
    1) INCREMENT</p>

<p>0 passing (75ms)
  1 failing</p>

<p>1) mutations
       INCREMENT:
     TypeError: increment is not a function</p>

<h1>      at Context.increment (dist\webpack:\tests\unit\store.spec.js:13:5)</h1>

<p>EDIT (4/16/2019)</p>

<p>I walk down one more step. I saw here that I should ""export"" all the components in my store.js like:</p>

<pre><code>import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export const mutations = {...};

export const state = {...};

export const actions = {...};

export const getters = {...};

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
});
</code></pre>

<p>But even in that way... I'm getting the ugly (testing fail message)</p>

<p>0 passing (61ms)
  1 failing</p>

<p>1) mutations
       increment:
     TypeError: increment is not a function
      at Context.increment (dist\webpack:\tests\unit\store.spec.js:12:5)</p>
",https://stackoverflow.com/questions/55700186/trying-unit-testing-store-how-to-make-it-work,"['javascript', 'unit-testing', 'vue.js', 'vuex']",144,True,1,1
Unexpected error when unit testing nested JNA Structure objects,"<p>The following unit test is intended to verify that a nested JNA data structure is properly parsed based on the data that gets passed into the constructor. The unit test properly checks when JNA initializes the 'parent' structure. However, the test fails when testing member variables of a nested structure. I suspect the problem to be that the unit test sets a pointer to a memory location that contains the data for the nested structure. Perhaps the Java Pointer isn't translating one-to-one to how C does it.</p>

<p>I tried placing the WlanBssEntry at the start of WlanBssEntry[] but that didn't provide any different results than how it is currently implemented. When I tried placing it contiguously, I did not call <code>pointerToMem.setPointer(8, ...)</code></p>

<p>This is the unit test:</p>

<pre class=""lang-java prettyprint-override""><code>package com.sevensignal.EyeQAgent.Util.win32.struct;

import com.sevensignal.EyeQAgent.Models.Platform;
import com.sevensignal.EyeQAgent.Util.Utils;
import com.sun.jna.Memory;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.WinDef;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeThat;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Utils.class})
public class WlanBssListTest {

    Pointer pWlanBssList;

    private final static long OFFSET_TO_FIRST_WLAN_BSS_ENTRY = 1024;

    @Before
    public void setUp() {
        assumeThat(Utils.getPlatform(), equalTo(Platform.WINDOWS));
        pWlanBssList = allocateMemory(65536);
        initWlanBssEntryMemory(pWlanBssList, OFFSET_TO_FIRST_WLAN_BSS_ENTRY, 50);
        initWlanBssListMemory(pWlanBssList, 12, 1, OFFSET_TO_FIRST_WLAN_BSS_ENTRY);
    }

    @Test
    public void shouldSetTotalSize() {
        WlanBssList subject = new WlanBssList(pWlanBssList);
        assertEquals(""should set total size"", new WinDef.DWORD(12), subject.dwTotalSize);
    }

    @Test
    public void shouldSetNumberOfItems() {
        WlanBssList subject = new WlanBssList(pWlanBssList);
        assertEquals(""should set number of items"", new WinDef.DWORD(1), subject.dwNumberOfItems);
    }

    @Test
    public void shouldInitWlanBssEntries() {
        WlanBssList subject = new WlanBssList(pWlanBssList);
        assertEquals(""should init WLAN BSS Entries"", 1, subject.wlanBssEntries.length);
        assertEquals(""should init WLAN BSS Entry data struct"", new WinDef.LONG(50), subject.wlanBssEntries[0].uPhyId);
    }

    @Test
    public void shouldInitWlanBssEntriesWhenNoEntriesExist() {
        pWlanBssList.setInt(4, 0);
        WlanBssList subject = new WlanBssList(pWlanBssList);
        assertEquals(""should init WLAN BSS Entries when no entries exist"", 0, subject.wlanBssEntries.length);
    }

    private Pointer allocateMemory(long size) {
        return new Memory(size).share(0);
    }

    private void initWlanBssListMemory(Pointer pointerToMem, int dwTotalSize, int dwNumberOfItems, long offsetToWlanBssEntry) {
        pointerToMem.setInt(0, dwTotalSize);
        pointerToMem.setInt(4, dwNumberOfItems);
        pointerToMem.setPointer(8, pointerToMem.share(offsetToWlanBssEntry));
    }

    private void initWlanBssEntryMemory(Pointer pointerToMem, long offsetToWlanBssEntry, long uPhyId) {
        final int PHY_ID_OFFSET = 40;
        pointerToMem.setLong(offsetToWlanBssEntry + 0, 3);
        pointerToMem.setByte(offsetToWlanBssEntry + 8, (byte)'T');
        pointerToMem.setByte(offsetToWlanBssEntry + 9, (byte)'S');
        pointerToMem.setByte(offsetToWlanBssEntry + 10, (byte)'T');
        pointerToMem.setLong(offsetToWlanBssEntry + PHY_ID_OFFSET, uPhyId);
    }
}
</code></pre>

<p>This is the WlanBssList class which is the highest level structure:</p>

<pre class=""lang-java prettyprint-override""><code>package com.sevensignal.EyeQAgent.Util.win32.struct;

import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.WinDef.DWORD;

import java.util.Arrays;
import java.util.List;

public class WlanBssList extends Structure {

    public DWORD dwTotalSize;
    public DWORD dwNumberOfItems;
    public WlanBssEntry[] wlanBssEntries;

    public static class ByReference extends WlanBssList implements Structure.ByReference
    {
        public ByReference()
        {

        }

        public ByReference(Pointer p)
        {
            super(p);
        }
    }

    public WlanBssList() {
        wlanBssEntries = new WlanBssEntry[1];
    }

    public WlanBssList(Pointer p) {
        super(p);
        dwTotalSize = new DWORD(p.getInt(0));
        dwNumberOfItems = new DWORD(p.getInt(4));
        if(dwNumberOfItems.intValue() &gt; 0) {
            wlanBssEntries = new WlanBssEntry[dwNumberOfItems.intValue()];
            readField(""wlanBssEntries"");
        } else {
            wlanBssEntries = new WlanBssEntry[0];
        }
    }

    @Override
    protected List&lt;String&gt; getFieldOrder() {
        return Arrays.asList(""dwTotalSize"", ""dwNumberOfItems"", ""wlanBssEntries"");
    }
}
</code></pre>

<p>And these are the nested structures:</p>

<pre class=""lang-java prettyprint-override""><code>package com.sevensignal.EyeQAgent.Util.win32.struct;

import com.sevensignal.EyeQAgent.Models.InformationElementGetter;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.WinDef.LONG;
import com.sun.jna.platform.win32.WinDef.ULONG;
import com.sun.jna.platform.win32.WinDef.ULONGLONG;
import com.sun.jna.platform.win32.WinDef.USHORT;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;

import java.util.Arrays;
import java.util.List;

@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WlanBssEntry extends Structure implements InformationElementGetter {

    public DOT11_SSID dot11Ssid;
    public ULONG uPhyId;
    public DOT11_MAC_ADDRESS dot11Bssid;
    public int dot11BssType;
    public int dot11BssPhyType;
    public LONG lRssi;
    public ULONG uLinkQuality;
    public boolean bInRegDomain;
    public USHORT usBeaconPeriod;
    public ULONGLONG ullTimestamp;
    public ULONGLONG ullHostTimestamp;
    public USHORT usCapabilityInformation;
    public ULONG ulChCenterFrequency;
    public WlanRateSet wlanRateSet;
    public ULONG ulIeOffset;
    public ULONG ulIeSize;

    @Override
    protected List&lt;String&gt; getFieldOrder()
    {
        return Arrays.asList(""dot11Ssid"",
                ""uPhyId"",
                ""dot11Bssid"",
                ""dot11BssType"",
                ""dot11BssPhyType"",
                ""lRssi"",
                ""uLinkQuality"",
                ""bInRegDomain"",
                ""usBeaconPeriod"",
                ""ullTimestamp"",
                ""ullHostTimestamp"",
                ""usCapabilityInformation"",
                ""ulChCenterFrequency"",
                ""wlanRateSet"",
                ""ulIeOffset"",
                ""ulIeSize"");
    }

    public byte[] getInformationElement() {
        return this.getPointer()
                .getByteArray(this.ulIeOffset.intValue(), this.ulIeSize.intValue());
    }
}
</code></pre>

<pre class=""lang-java prettyprint-override""><code>package com.sevensignal.EyeQAgent.Util.win32.struct;

import com.sun.jna.Structure;
import com.sun.jna.platform.win32.WinDef.*;

import java.util.Arrays;
import java.util.List;

public class DOT11_SSID extends Structure
{
    public static class ByReference extends DOT11_SSID implements Structure.ByReference
    {

    }

    public static int DOT11_SSID_MAX_LENGTH = 32;

    /**
     * The length, in bytes, of the ucSSID array.
     */
    public ULONG uSSIDLength;

    /**
     * The SSID. DOT11_SSID_MAX_LENGTH is set to 32.
     */
    public byte[] ucSSID;

    public DOT11_SSID()
    {
        ucSSID = new byte[DOT11_SSID_MAX_LENGTH];
    }

    @Override
    protected List&lt;String&gt; getFieldOrder()
    {
        return Arrays.asList(""uSSIDLength"", ""ucSSID"");
    }

    @Override
    public String toString() {
        if(uSSIDLength != null) {
            int ssidArrayLength = uSSIDLength.intValue();
            if (ssidArrayLength &gt; DOT11_SSID_MAX_LENGTH) {
                ssidArrayLength = DOT11_SSID_MAX_LENGTH;
            }

            return new String(Arrays.copyOfRange(ucSSID, 0, ssidArrayLength));
        } else {
            return """";
        }
    }
}
</code></pre>

<p>The results of the unit test are:</p>

<pre><code>java.lang.AssertionError: should init WLAN BSS Entry data struct 
Expected :50
Actual   :0
</code></pre>

<p>The assertion that fails is:         </p>

<p><code>assertEquals(""should init WLAN BSS Entry data struct"", new WinDef.LONG(50), subject.wlanBssEntries[0].uPhyId);</code></p>
",https://stackoverflow.com/questions/55385907/unexpected-error-when-unit-testing-nested-jna-structure-objects,"['java', 'windows', 'junit', 'jna']",210,True,1,1
IntelliJ Kotlin/JS Mocha Unit Testing Unavailable via Plugin,"<p>I am experiencing some difficulty getting IntelliJ to recognize my Kotlin Tests as mocha tests and generating the green play button in the gutter allowing me to run Kotlin/JS unit tests in the IDE via the Mocha Plugin. Now, I somehow managed to get this working after some trial and error and then inexplicable earlier today it just stopped working and the green play buttons vanished from the gutter. I have tried all the normal stuff such as invalidating the IDE cache, removing .idea/*.iml files and reimporting project. Nothing seems to work.</p>

<p><strong>Image of Working Environment</strong></p>

<p>here is an image of the setup working as expected that I luckily took a snapshot of while I had the chance because I had so much difficulty getting it working.</p>

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

<p>You can also see that the mocha run configuration is accurately picking up on the fact that the actual file being ran is going to be the output file in my build directory. </p>

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

<p>My initial instinct led me to believe that this was due to IntelliJ picking up on my map.js files being generated as well, however this is not the case as did not (and do not) have my compile options set to with <em>sourceMap = true</em> or <em>sourceMapEmbedSources = ""always""</em>, as you can see from this snippet from my build.gradle.kts</p>

<pre><code>compileKotlin2Js {
    kotlinOptions {
        moduleKind = ""commonjs""
    }
}
compileTestKotlin2Js {
    kotlinOptions {
        moduleKind = ""commonjs""
    }
}
</code></pre>

<p>For the record, my gradle build compiles and tests run successfully. To clarify, I am specifically trying to get IntelliJ to recognize the project structure in such a way that the run configurations can make these education decisions for me and speed up my workflow.</p>
",https://stackoverflow.com/questions/54797767/intellij-kotlin-js-mocha-unit-testing-unavailable-via-plugin,"['intellij-idea', 'kotlin', 'mocha.js']",164,False,1,0
Angular unit testing in routing and routerLink using Jasmine,"<p>I am new in Angular and unit testing. I create a new project for testing the routing in Angular.I follow the guide in <a href=""https://angular.io/guide/testing#components-with-routerlink"" rel=""nofollow noreferrer"">Angular official doc</a>.It does work in testing the routerLink.</p>

<p>but here is a problem. I forgot creating a route in the app.routing.module.ts, 
but the test still pass.</p>

<p>here is the code
in routing.module.ts</p>

<p><code>const routes: Routes = [];</code></p>

<p>and in html
<code>
&lt;a routerLink=""/order""&gt;Order&lt;/a&gt;&lt;br/&gt;
&lt;a routerLink=""/creditCard""&gt;Credit Card&lt;/a&gt;
</code></p>

<p>in spec.ts</p>

<pre><code>describe('AppComponent', () =&gt; {
  let fixture: ComponentFixture&lt;AppComponent&gt;;
  let app: any;
  let compiled: any;
  let linkDes:any;
  let routerLinks:any;
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent,
        RouterLinkDirectiveStub
      ]
    }).compileComponents().then(() =&gt; {
      fixture = TestBed.createComponent(AppComponent);
      app = fixture.debugElement.componentInstance;
      fixture.detectChanges();
      compiled = fixture.debugElement.nativeElement;

      // find DebugElements with an attached RouterLinkStubDirective
      linkDes = fixture.debugElement
        .queryAll(By.directive(RouterLinkDirectiveStub));

      // get attached link directive instances
      // using each DebugElement's injector
      routerLinks = linkDes.map(de =&gt; de.injector.get(RouterLinkDirectiveStub));
    })
  }));

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

  it(`should have as title 'unitTesting'`, () =&gt; {
    expect(app.title).toEqual('unitTesting');
  });

  it('should render title in a h1 tag', () =&gt; {
    expect(compiled.querySelector('h1').textContent).toContain('Welcome to unitTesting!');
  });

  it('can get RouterLinks from page', () =&gt; {
    expect(routerLinks.length).toBe(2, 'should have 2 routerLinks');
    expect(routerLinks[0].linkParams).toBe('/order');
    expect(routerLinks[1].linkParams).toBe('/creditCard');
  });

}); 
</code></pre>

<p>I understand the unit testing should be isolated.
but in some case, it should have connection in order to test.</p>

<p>I googled. but lot of answers just compare with static path.</p>

<p>and my question is, how to test in scenario like below:</p>

<ol>
<li><p>in routing.module.ts</p>

<p>const routes: Routes = [</p>

<p>{path:""order"",component:OrderComponent},
  {path:""creditCard"",component:CreditcardComponent}</p>

<p>];</p></li>
</ol>

<p>2.in two or more pages have same anchor tag 
<code>
&lt;a routerLink=""/order""&gt;Order&lt;/a&gt;&lt;br/&gt;
&lt;a routerLink=""/creditCard""&gt;Credit Card&lt;/a&gt;
</code></p>

<p>3.if someone change the path in routing.module.ts,like</p>

<p><code>{path:""orderDetail"",component:OrderComponent},</code></p>

<p>and forgot to change the path of routerLink in all or one of html file, test case will still pass for those component that forgot to change the path of routerLink.</p>

<p>Therefore, what to do to fix it to show failure in test case.</p>
",https://stackoverflow.com/questions/57422418/angular-unit-testing-in-routing-and-routerlink-using-jasmine,"['angular', 'unit-testing', 'routes', 'jasmine']",334,False,1,0
Unit Testing - Ensure all repositories pass through the constructor,"<p>I want to create a unit test method to ensure that all repositories are being passed through the constructor. </p>

<p>I believe that using Moq repositories may be the best solution here, but so far I have not been able to verify that the test method passes. </p>

<p>Controller:</p>

<pre class=""lang-cs prettyprint-override""><code>public AgentsController(ICallBoardStatsRepo callBoardRepo)
{
    _callBoardRepo = callBoardRepo;
}
</code></pre>

<p>Interface:</p>

<pre class=""lang-cs prettyprint-override""><code>public interface ICallBoardStatsRepo:IDisposable
{
    CallBoardStats ById(int clientId);
    ClientCalls ByIdNavStats(int clientId);
}
</code></pre>

<p>My current test method for the repository constructor looks like the following: </p>

<pre class=""lang-cs prettyprint-override""><code>[TestMethod]
public void AgentController_Test()
{
    var myCallBoard = new Mock&lt;AgentCallStats&gt;();
    var myTestCallBoard = new Mock&lt;AgentCallStats&gt;();

    var callBoardList = new List&lt;AgentCallStats&gt;() { myCallBoard.Object, myTestCallBoard.Object };
    var ICallBoard = new Mock&lt;IAgentCallStatsRepo&gt;();
    ICallBoard.Setup(x =&gt; x.ById(2)).Returns(callBoardList);

    myCallBoard.Verify(x =&gt; x.Equals(It.IsAny&lt;int&gt;()), Times.Once());
    myTestCallBoard.Verify(x =&gt; x.Equals(It.IsAny&lt;int&gt;()), Times.Once());
 }
</code></pre>

<p>When running the individual test method, I get an error looking something like:</p>

<blockquote>
  <p>Expected invocation on the mock once, but was 0 times</p>
</blockquote>

<p>I am not very experienced in writing unit tests, and this is really throwing me for a loop. Would anyone be willing to help point me in the right direction? I feel like I am close to solving this, but maybe an extra set of eyes may be able to highlight the problem. Thank you.</p>
",https://stackoverflow.com/questions/56946390/unit-testing-ensure-all-repositories-pass-through-the-constructor,"['c#', 'unit-testing', 'moq']",50,False,1,0
How to inject Nginx fastcgi_param to Laravel Unit testing,"<p>I have setup Laravel application which use  <code>fastcgi_param XXX YYY</code> from Nginx to initialize domain based functionalities. I can not find a way to inject <code>fastcgi_param</code> data into my Unit Test.</p>

<p>I have registered Laravel provider and I am getting <strong>fastcgi_param</strong> data from getenv('XXX'). Which is perfectly working on browser, but my challenge it inject them into Unit Tests.</p>

<p>I tried to update </p>

<pre><code>&lt;server name=""XXX"" value=""YYY""/&gt;
</code></pre>

<p>But unfortunatly it wont work.</p>

<p>When I do <code>dump($request-&gt;server())</code> it has no not found any reference for <strong>XXX</strong> </p>

<p>If you have any suggestions, I am so glad.</p>
",https://stackoverflow.com/questions/59388978/how-to-inject-nginx-fastcgi-param-to-laravel-unit-testing,"['laravel', 'nginx', 'phpunit']",54,True,1,1
Corda - Unit Testing Flows That End Up In Hospital,"<p>I am unit testing a flow that I know will fail.</p>
<pre><code>assertFailsWith&lt;JdbcSQLIntegrityConstraintViolationException&gt; {
    nodeA.issueState(...) // Note, issueState is an extension on StartedMockNode
}
</code></pre>
<p>The reason for the failure is that the state being output in the transaction cannot be duplicated due to a unique key/index violation on the schema:</p>
<blockquote>
<p>org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation</p>
</blockquote>
<p>When this happens in a unit test the output displays:</p>
<blockquote>
<p>[INFO] 12:41:22,600 [Mock network] statemachine.StaffedFlowHospital. - Flow error kept for overnight observation by [net.corda.node.services.statemachine.StaffedFlowHospital$TransitionErrorGeneralPractitioner@49a4216e] (error was org.hibernate.exception.ConstraintViolationException: could not execute statement) {actor_id=Only For Testing, actor_owning_identity=O=PartyA, L=London, C=GB, actor_store_id=TEST, fiber-id=10000012, flow-id=932a7d4e-e695-4096-b3d8-efbcdbfa5b21, invocation_id=fcf25c8a-6bf1-4dce-8e65-3c84c96b8523, invocation_timestamp=2019-12-28T12:41:22.402Z, origin=Only For Testing, session_id=fcf25c8a-6bf1-4dce-8e65-3c84c96b8523, session_timestamp=2019-12-28T12:41:22.402Z, thread-id=1309}</p>
<p>[WARN] 12:42:18,805 [FlowHospitalJobTimer] statemachine.StaffedFlowHospital. - There are 1 flows kept for overnight observation. Affected flow ids: 932a7d4e-e695-4096-b3d8-efbcdbfa5b21</p>
<p>[WARN] 12:43:18,804 [FlowHospitalJobTimer] statemachine.StaffedFlowHospital. - There are 1 flows kept for overnight observation. Affected flow ids: 932a7d4e-e695-4096-b3d8-efbcdbfa5b21</p>
</blockquote>
<p>The problem is that the test hangs and never completes. I've managed to get the test to fail by adding a duration to the <code>getOrThrow</code> function on the resulting <code>CordaFuture</code>, but this seems wrong to me, as the flow is failing due to a timeout, rather than because of the underlying exception.</p>
<pre><code>.getOrThrow(Duration.ofSeconds(10))
</code></pre>
<blockquote>
<p>java.lang.AssertionError: Expected an exception of class org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException to be thrown, but was java.util.concurrent.TimeoutException</p>
</blockquote>
<p>What is the correct way to test flows that end up being sent to the flow hospital?</p>
",https://stackoverflow.com/questions/59511061/corda-unit-testing-flows-that-end-up-in-hospital,['corda'],266,True,1,1
Unit testing that code runs without exception in ScalaTest,"<p>TL;DR I have a Task[Unit], in ScalaTest/FlatSpec what is the proper way to test if the task succeeded in a given time frame?</p>

<p>I have an application with a server-client architecture, the interaction between client and server is non blocking.  This is implemented by calls on the client returning a future which completes when the server has finished the work.  Importantly this future does not return back the result, it is just used to indicate that the server has finished:</p>

<pre><code>val notification: Task[Unit] = myServer.alterState(""do this"")
Await.result(notification.runAsync, 20.seconds)
</code></pre>

<p>What I want to test here is that the server is correctly sending notifications of completion to the client.  I'm testing this with FlatSpec from ScalaTest, and to me it seems that the following should be a valid test:</p>

<pre><code>""Server"" should ""notify client upon completion"" in {
    val notification: Task[Unit] = myServer.alterState(""do this"")
    Await.result(notification.runAsync, 20.seconds)
}
</code></pre>

<p>If the server takes longer than 20 seconds to reply, Await.result will throw an exception, which the test will catch, and fail.</p>

<p>Is this the correct way to perform this sort of test in flatspec?  All of the matching framework seems to be geared around testing the value of results, and catching expected exceptions, but I don't have a result returned, I just want to test that the future ends successfully.</p>
",https://stackoverflow.com/questions/56061229/unit-testing-that-code-runs-without-exception-in-scalatest,"['scala', 'scalatest']",981,True,1,2
How to mock LocalCache in unit testing with Mockito,"<p>My base class uses java library responsible for auditing. This Library uses Builder pattern to retrieve objects from my Java Project for Auditing Operations (<em>Inserts into Multiple tables by creating keys on it's own.</em>)
This Library uses <code>com.google.common.cache</code> to manage cache values. i.e. String and Value. 
<code>LoadingCache&lt;String, Long&gt;</code></p>

<p><strong>sample Example of how my project uses library</strong></p>

<pre class=""lang-java prettyprint-override""><code>auditOperation = LibraryAuditBuilder.builder()
//some param
.build()
LibraryAuditingService.process(auditOperation);
</code></pre>

<p>My base application and Library runs on Oracle Database and my unit tests uses HSQL database. Given all necessary scripts in <code>@Before</code> I would want to unit test execution of my code.</p>

<p><code>@Before</code> method</p>

<pre class=""lang-java prettyprint-override""><code>@Before
    public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
//create db scrips and other declarations
}
</code></pre>

<p><strong>I have tried 2 approach so far</strong></p>

<p>1) Created <code>LoadingCache</code> and put sample values in it so that UnitTest can use it later in execution.</p>

<pre class=""lang-java prettyprint-override""><code>longLoadingCache.put(""4028eeb0-1d2d-daba-011d-2e36e4b2110e"",(long)203);
longLoadingCache.put(""4028ee14-24b4-5221-0124-b47bbb1d1232"",(long)102);
</code></pre>

<p>2) <code>@Mock</code> object of <code>LoadingCache</code> and values in it to be used later in Tests</p>

<pre class=""lang-java prettyprint-override""><code>when(longLoadingCache.get(""4028eeb0-1d2d-daba-011d-2e36e4b2110e"")).thenReturn((long)203);     
when(longLoadingCache.get(""4028ee14-24b4-5221-0124-b47bbb1d1232"")).thenReturn((long)102);
</code></pre>

<p>Current output with both of above approach</p>

<pre class=""lang-java prettyprint-override""><code>- com.google.common.cache.CacheLoader$InvalidCacheLoadException: CacheLoader returned null for key 4028ee14-24b4-5221-0124-b47bbb1d1232.
</code></pre>

<p>So my question is, <strong>How Can I Pass/Mock values of Cache so that UnitTests don't have to look for values in Library class.</strong></p>
",https://stackoverflow.com/questions/55972811/how-to-mock-localcache-in-unit-testing-with-mockito,"['java', 'spring', 'mockito']",3348,True,1,2
Angular Service Unit Testing - faking nested methods or not?,"<p>I have very simple question. </p>

<p>If i have in one service methods like this one </p>

<pre><code>generateObjectBasedOnName(name: string): SomeObject {
  if(this.isNameValid(name)) {
    const {namePart1, namePart2} = this.getNameParts(name);
    const baseObjectOne = this.getBaseObjectOne(namePart1);
    const baseObjectTwo = this.getBaseObjectTwo(namePart2);

    baseObjectOne.someDataNeededToSetHere = false;
    baseObjectTwo.someDataNeededToSetHere = true;

    return this.generateSomeObject(baseObjectOne, baseObjectTwo);
  }

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

<p>Should I, in unit tests, fake methods that are used in this method or should I just leave them to execute normally?</p>

<p>Thanks for any answers :)</p>
",https://stackoverflow.com/questions/59202946/angular-service-unit-testing-faking-nested-methods-or-not,"['angular', 'unit-testing', 'testing', 'service', 'mocking']",62,True,0,1
"Type Error exception while unit testing (zend-test, PHPUnit)","<p>I am trying to test a simple controller action in Zend FrameWork and I am not 100% sure why my mocks are not working.</p>

<p><strong>Original Action:</strong></p>

<pre><code> public function overviewAction()
    {
        $page = $this-&gt;params()-&gt;fromQuery('page', 1);
        $count = 10;

        $user = $this-&gt;authenticationService-&gt;getIdentity();

        return new ViewModel([
            'paginator' =&gt; $this-&gt;agentService-&gt;getAgentsOwnedByUser($page, $count, $user),
        ]);
    }
</code></pre>

<p><strong>My Test for this action</strong></p>

<pre><code>    /**
     * Set Rbac Role and route
     */
    $url = ""cp/agent"";
    $this-&gt;setRbacGuards(['admin']);
    //Nb Rbac class code is here

    /**
     * Objects required in this test
     */
    $user = $this-&gt;createMock(User::class);
    $paginator = $this-&gt;createMock(Paginator::class);

    /**
     * Mock classes and their methods to be called
     */
    $authentication = $this-&gt;createMock(AuthenticationService::class);
    $authentication
        -&gt;expects($this-&gt;once())
        -&gt;method('getIdentity')
        -&gt;will($this-&gt;returnValue($this-&gt;registerMockObject($user)));


    $agentService = $this-&gt;createMock(AgentService::class);
    $agentService
        -&gt;expects($this-&gt;once())
        -&gt;method('getAgentsOwnedByUser')
        -&gt;will($this-&gt;returnValue($this-&gt;registerMockObject($paginator)));

    $this-&gt;dispatch('/'.$url);
    $this-&gt;assertResponseStatusCode(200);
</code></pre>

<p><strong>The error message</strong></p>

<pre><code> There was 1 failure:

    1) ControlPanelTest\Controller\AgentControllerTest::testAgentOverviewActionCanBeAccessed
    Failed asserting response code ""200"", actual status code is ""500""

    Exceptions raised:
    Exception 'TypeError' with message 'Argument 3 passed to 

    Admin\Service\AgentService::getAgentsOwnedByUser() must be an instance of Domain\User\User, null given
.
</code></pre>

<p><strong>For completeness, Rbac Class</strong></p>

<pre><code>public function rbacGuards($roles)
    {
        /**
         * Deal with Rbac Guards
         */
        $roleService = $this-&gt;getApplicationServiceLocator()-&gt;get(RoleService::class);
        $identityProvider = $this-&gt;prophesize(IdentityProviderInterface::class);
        $identity = $this-&gt;prophesize(IdentityInterface::class);
        // Here you use the setter to inject your mocked identity provider
        $roleService-&gt;setIdentityProvider($identityProvider-&gt;reveal());
        $identityProvider-&gt;getIdentity()-&gt;shouldBeCalled()-&gt;willReturn($identity-&gt;reveal());
        $identity-&gt;getRoles()-&gt;shouldBeCalled()-&gt;willReturn($roles);
    }
</code></pre>

<p><strong>Prognosis</strong></p>

<p>It seems the mocks are not being called...</p>
",https://stackoverflow.com/questions/54050664/type-error-exception-while-unit-testing-zend-test-phpunit,"['zend-framework2', 'phpunit', 'zend-test']",172,True,0,1
TDD Swift Unit testing a function with no inputs,"<p>I'm playing with Unit testing in Swift. I can mock and test most of my functions. However I'm struggling with this one (it's for a quiz):</p>

<pre><code>public func getQuestionSetStats() -&gt; (numberOfQs: Int, answered: Int, totalCorrect: Int, totalWrong: Int)? {
    guard questionSet != nil &amp;&amp; questionSet!.count &gt; 0 else {return nil}
    let number = questionSet!.count
    let answered = questionSet!.filter{ $0.answerGiven != nil &amp;&amp; $0.answerGiven ?? 0 &gt;= 0 }.count
    let correct = Array ( zip(questionSet!.map{ Int( $0.question.solution) }, questionSet!.map{ $0.answerGiven }) )
    let correctAnswers = correct.filter{ $0.0 == ( ($0.1 ?? 10) + 1)}.count
    let wrong = number - correctAnswers
    return (numberOfQs: number, answered: answered, totalCorrect: correctAnswers, totalWrong: wrong)
}
</code></pre>

<p>This basically returns the state of my quiz manager for display by some view controller. </p>

<p>Since the vars are very much caught up in the state of the quiz manager I don't know how to unit test this function without setting up a whole state for the function - what is the best approach to do this.</p>
",https://stackoverflow.com/questions/56404333/tdd-swift-unit-testing-a-function-with-no-inputs,['swift'],32,False,0,0
Getting Module Import error with unit testing in python,"<p>Hello Python Programmers</p>

<p>I'm getting a weird module import error during unittest. Not able to find the root cause.
Here is how my directory structure looks like</p>

<pre><code>Main_folder
   |
   |
   Module_x
       |  ABC.py
   |
   |
   Module_y
        | DEF.py
   |
   |
   test
       | unit_tests
             | test_ABC.py  
</code></pre>

<p>In test_ABC.py I'm importing the following</p>

<pre><code>from Module_x import ABC
</code></pre>

<p>I get the error as ""No module name Module_x""</p>

<p>I've created <code>__init__.py</code> file at each folder</p>

<p>I don't get any error if I use the same line from DEF.py</p>

<p>Please help if you're aware about why I am getting this issue?</p>

<p>I am using Python 3.5 Anaconda Distribution</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/54396222/getting-module-import-error-with-unit-testing-in-python,"['python', 'python-2.7', 'unit-testing', 'python-unittest']",339,True,-1,1
Spoofing grpc UnaryHandler for unit testing gRPC in Go,"<p>I'm working on improving coverage for my Go gRPC server but I have run into trouble writing a test for the server's interceptor function because I'm unable to meaningfully satisfy the <code>UnaryHandler</code> type.</p>

<p>I have a function <code>Interceptor</code> with the following signature:</p>

<pre><code>Interceptor func(
  ctx context.Context,
  req interface{},
  info *grpc.UnaryServerInfo,
  handler grpc.UnaryHandler, // &lt;- my issue comes from here
) (interface{}, error)
</code></pre>

<p>I assumed that any gRPC method would satisfy the signature of <code>UnaryHandler</code>:</p>

<pre><code>type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error)
</code></pre>

<p>So I tried passing in a method with this signature:</p>

<pre><code>GetToken(ctx context.Context, req *AuthData) (*Token, error)
</code></pre>

<p>I imagined this would work, since this is what the Interceptor is actually doing (forwarding that RPC), but for some reason Go complains:</p>

<blockquote>
  <p>cannot use authService.GetToken (type func(context.Context, *AuthData) (*Token, error)) as type grpc.UnaryHandler in argument to Interceptor</p>
</blockquote>

<p>I went ahead and wrote a dummy function that correctly satisfies:  </p>

<pre><code>func genericHandler(ctx context.Context, req interface{}) (interface{}, error) {
    return req, nil
}
</code></pre>

<p>which is fine since I don't particularly <em>need</em> to run any specific method when testing the interceptor. However I am curious as to why the actual method doesn't satisfy the constraints because (according to my understanding) it is being passed to the Interceptor function under hood whenever I call that RPC in the wild.</p>

<p>The most likely explanation is that the grpc UnaryHandler doesn't do what I'm thinking it does, but then what does it do? </p>
",https://stackoverflow.com/questions/57681271/spoofing-grpc-unaryhandler-for-unit-testing-grpc-in-go,"['go', 'testing', 'grpc']",1404,True,0,1
Avoiding thread.sleep in code while unit testing with Moq,"<p>I have methods which have multiple thread.sleep which last for 20 seconds at times. This is a business requirement. I am trying to unit test these methods, by mocking and skipping these sleeps so that tests can run faster and doesn't actually wait for 20 seconds. Using the moq framework.
Appreciate any ideas on how to implement this.</p>
",https://stackoverflow.com/questions/55138340/avoiding-thread-sleep-in-code-while-unit-testing-with-moq,"['c#', 'unit-testing', 'moq']",1316,True,-1,3
"When unit testing my ViewModel, list always returns empty","<p>I'm trying to learn unit testing, I have my code factored into an MVVM(i) architecture, but when I run my testParseToList() test function, it always comes back with an empty list and I can't figure out why.  I fear it may have something to do with the i part of the MVVM(i) and whether or not I'm correctly mocking my viewmodel.  I'm starting with my most simple viewmodel in hopes to get a grasp of the concepts before moving onto my more complex ones.</p>

<p><strong>OfflineViewModelUnitTest.kt</strong></p>

<pre><code>@RunWith(JUnit4::class)
class OfflineViewModelUnitTest {

    @get:Rule
    val rule = InstantTaskExecutorRule()

    @Mock
    var offlineViewModel: OfflineViewModel = OfflineViewModel(OfflineInteractorImpl())

    @Before
    fun setup() {
        MockitoAnnotations.initMocks(this)
        DaggerOfflineViewModelComponent.builder()
            .offlineInteractorImplModule(OfflineInteractorImplModule())
            .build()
            .inject(offlineViewModel)

//        this.offlineViewModel = OfflineViewModel(OfflineInteractorImpl())
    }

    @Test
    fun testParseToList() {

        val test = offlineViewModel.parseTextToList(""dried bonito extract,\n"" +
                ""    ketchup,\n"" +
                ""    millet,\n"" +
                ""    corn &amp; wheat protein"")

        val a = ""dried bonito extract""
        val b = ""ketchup""
        val c = ""millet""
        val d = ""corn &amp; wheat protein""

        val expectedResult = listOf(a, b, c, d)

        assertEquals(expectedResult, test)
    }
}
</code></pre>

<p><strong>OfflineViewModel.kt</strong></p>

<pre><code>class OfflineViewModel(private val offlineInteractor: OfflineInteractor): ViewModel() {

    init {
        DaggerOfflineViewModelComponent.builder()
            .offlineInteractorImplModule(OfflineInteractorImplModule())
            .build()
            .inject(this)
    }
    fun parseTextToList(firebaseVisionTextString: String): MutableList&lt;String&gt; {
        Log.d(""here it is"", firebaseVisionTextString)
        return offlineInteractor.parseTextToList(firebaseVisionTextString)
    }

    fun readCsvFromAssetFolder(inputStream: InputStream): List&lt;String&gt;{
        return offlineInteractor.readCsvFromAssetFolder(inputStream)
    }
}
</code></pre>

<p><strong>OfflineInteractorImpl.kt</strong></p>

<pre><code>class OfflineInteractorImpl: OfflineInteractor {

    override fun parseTextToList(firebaseVisionTextString: String): MutableList&lt;String&gt; {

            val ingredientsList: MutableList&lt;String&gt; = firebaseVisionTextString.split("","").map { it.trim() }.toMutableList()

            return ingredientsList
    }

    override fun readCsvFromAssetFolder(inputStream: InputStream): List&lt;String&gt; {
        val csvLine: ArrayList&lt;String&gt; = ArrayList()
        var content: Array&lt;String&gt;?
        try
        {
            val br = BufferedReader(InputStreamReader(inputStream))
            for (line in br.lines())
            {
                content = line.split(("","").toRegex()).dropLastWhile{ it.isEmpty() }.toTypedArray()
                csvLine.add(content[0].substringBefore("";""))
            }
            br.close()
        }
        catch (e: IOException) {
            e.printStackTrace()
        }
        return csvLine
    }
}
</code></pre>

<p><strong>Test Results</strong></p>

<pre><code>java.lang.AssertionError: 
Expected :[dried bonito extract, ketchup, millet, corn &amp; wheat protein]
Actual   :[]
</code></pre>
",https://stackoverflow.com/questions/57862471/when-unit-testing-my-viewmodel-list-always-returns-empty,"['unit-testing', 'kotlin', 'junit', 'mockito']",684,True,0,1
How to ignore spark_home when unit testing with pyspark,"<p>I trying to write unit-tests with pyspark. Tests pass with the following configuration when <code>SPARK_HOME</code> is NOT set. There are multiple installations of spark on our machines and if <code>SPARK_HOME</code> is set to one of them tests fails on that machine. </p>

<pre><code>@pytest.fixture(scope=""session"")
def spark_session(request):
    session = SparkSession\
        .builder\
        .master(""local[2]"")\
        .appName(""pytest-pyspark-local-testing"")\
        .getOrCreate()

    request.addfinalizer(lambda: session.stop())
    quiet_py4j()
    return session
</code></pre>

<p>I have tried <code>os.environ[""SPARK_HOME""] = """"</code> which gets <code>FileNotFoundError: [Errno 2] No such file or directory: './bin/spark-submit': './bin/spark-submit</code> error. </p>

<p>I have also tried <code>os.unsetenv('SPARK_HOME')</code> which gets <code>Exception: Java gateway process exited before sending its port number</code>. When I don't try to unset the env var, I get this same error as well.</p>

<p>How can I make sure that my tests will work on any machine simply ignoring any environment variables. </p>
",https://stackoverflow.com/questions/56498269/how-to-ignore-spark-home-when-unit-testing-with-pyspark,"['pyspark', 'pytest']",457,False,0,0
"good software design patterns, constructor overloading for unit testing","<p>I am developing a windows form application in c#. When instantiating the form, I initialize a few hardware classes within the constructor. <code>hardware1, Hardware2, Hardware3</code> represent the hardware classes that i instantiate in the software.</p>

<pre><code>public partial class Form1 {
    Hardware1 a;
    Hardware2 b;
    Hardware3 c;

    public Form1() {
        // initialize hardware1,2 and 3 using native dll calls of a,b and c
    }
</code></pre>

<p>I want to conduct unit testing for this method within my main form.</p>

<pre><code>public int MyMethod(int percent, ref double power) {
    for(int i =0; i&lt;3; i++)
        {
            if(a.isValid)
            {
                b.DoThing1(percent);
                b.DoThing2(true);
                c.DoSomething1();
                double val = C.DoSomething2();
                if (val != -500)
                {
                    power = val;
                    return 0;
                }
            }
            else
                return 1;

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

<p>The difficulty is that a.IsValid is set through some dll calls that i would have to mock. b.DoThing1 and C.DoThing2 also calls some dll function that I would have to mock as well. One possibility is to overload the form method constructor. Then i can mock each classes dll's </p>

<pre><code>Form1 (Hardware1 a, Hardware2 b, Hardware3 c) {
    this.a = a;
    this.b = b;
    this.c = c;
} 
</code></pre>

<p>or should i have interfaces for Hardware1 a, Hardware2 b and Hardware3 c ? I read that its generally better to have interfaces to substitute the concrete classes. </p>

<p>what is good software practice to unit test Form1 myMethod ?  </p>
",https://stackoverflow.com/questions/57040425/good-software-design-patterns-constructor-overloading-for-unit-testing,"['c#', 'visual-studio', 'unit-testing']",156,True,0,2
Unit testing the async await function in angular 5,"<p>I need to know how to write unit testing for async/await functions in angular 5 which connect with a background service for STT service .Can anybody help?</p>

<pre><code>async listen(){
 let data = await fetch('http://localhost:13005/getGoogleText', {
      method: 'GET'
    })
    .then(function(response) {
      if (response.ok) {
      return response.json();
      }
    })
    .then(response =&gt; {
      return response;
    })
    .catch(error =&gt; {
      return (error);
      console.error(error);
    });
}
</code></pre>
",https://stackoverflow.com/questions/56001896/unit-testing-the-async-await-function-in-angular-5,"['angular', 'unit-testing', 'async-await']",80,False,0,0
Unit Testing Error :Cannot read property &#39;map&#39; of undefined,"<p>I am trying to do a unit test for the following code but I am not sure how to mock this.props that contains map on it</p>

<p>ERROR:  Cannot read property 'map' of undefined</p>

<p>Is this  prop correct ? this.props.fromStatusList. I have the other props right</p>

<p>Here is part of the BatchAccount.js code :</p>

<pre><code> renderFromDropdown = () =&gt; {
let fromList = this.props.fromStatusList;
let result = fromList.map((item) =&gt; {
</code></pre>

<p>Here is how I am mocking the props in BatchAccount.test.js</p>

<pre><code>describe( 'BatchUpdateAccountModal test: ', () =&gt; {

let tree;
let baseProps;
let mockfromStatusList;
</code></pre>

<p>And then I list them under beforeEach (() =></p>

<pre><code> beforeEach(() =&gt; {

    baseProps = {
fromStatusList : mockfromStatusList,
</code></pre>

<p>and run a test to check if it renders with  all of the props for example :</p>

<pre><code>  it(' Should render with all of the props ', () =&gt; {  
tree = renderer.create(&lt;BatchUpdateAccountModal {...baseProps} /&gt;)
let treeJson = tree.toJSON()
expect(treeJson).toMatchSnapshot();
tree.unmount()
</code></pre>

<p>});</p>
",https://stackoverflow.com/questions/54238560/unit-testing-error-cannot-read-property-map-of-undefined,"['javascript', 'reactjs', 'unit-testing']",139,False,0,0
Unit testing methods which update UI elements in iOS,"<p>I am trying to write unit tests for my existing code. 
I have 3 methods.</p>

<pre><code>func methodOne() {
    // code
    methodTwo()
}

func methodTwo() {
    // code
    methodThree()
}

func methodThree() {
    // code
    // update UI element
}
</code></pre>

<p>What's the ideal way to unit test such methods. While unit testing <code>methodTwo()</code> it calls <code>methodThree()</code> as the UI elements are not loaded they have <code>nil</code> value when <code>methodThree()</code> is called. How to unit test methods which involve UI elements. I don't want to test if the UI element is loaded properly, I just want to test the code in <code>methodTwo()</code> and <code>methodThree()</code>. Is there a way to bypass UI elements related code. Any help is appreciated. Thank you.</p>
",https://stackoverflow.com/questions/55727108/unit-testing-methods-which-update-ui-elements-in-ios,"['ios', 'swift', 'unit-testing']",180,False,0,2
"C# MVC, Generic Repository and Unit Testing with Moq","<p>I have to test a method which returns true or false if date range overlaps with any item of list.</p>

<p><b>List items are holiday requests: </b></p>

<pre><code>public class HolidayRequest
{
    public int Id { get; set; } 
    public string EmployeeId { get; set; }
    public DateTime DateFrom { get; set;  }
    public DateTime DateTo { get; set; } 

}

public interface IHolidayRequestRepository :IGenericRepository&lt;HolidayRequest&gt;
{ 
    bool IsHolidayRequestAlreadyCreated(String EmployeeId, DateTime DateFrom, DateTime DateTo); 
} 

public interface IGenericRepository&lt;TEntity&gt; where TEntity : class
{
    IQueryable&lt;TEntity&gt; GetAll();
    TEntity Get(object id);
    //skipped 
}
</code></pre>

<p>Now unit tests:</p>

<pre><code>[TestClass]
public class UnitTest1
{
    private Mock&lt;IHolidayRequestRepository &gt; _holidayRepository;
    [TestInitialize]
    public void Initialize()
    {
        _holidayRepository = new Mock&lt;IHolidayRequestRepository &gt;();
    }
    [TestMethod]
    public void TestMethod1()
    {

        //Arange
        IList&lt;HolidayRequest&gt; list = new List&lt;HolidayRequest&gt;
        {
             new HolidayRequest{ Id =1, EmployeeId=""E00001"", DateFrom = new DateTime(2019,09,13,0,0,0), DateTo = new DateTime(2019,09,13,0,0,0)}
        };
        _holidayRepository.Setup(x =&gt; x.GetAll()).Returns(list.AsQueryable);

        var howMany = _holidayRepository.Object.GetAll().Count();

        //Assert
        Assert.AreEqual(1, howMany); //&lt;- Test passed

        bool val = _holidayRepository.Object
             .IsHolidayRequestAlreadyCreated(""E00001"", new DateTime(2019, 9, 12), new DateTime(2019, 9, 14));

        ////Assert
       Assert.IsTrue(val);  //&lt;- Test error - always return false

    }
}
</code></pre>

<p>I expect the test result to be true, but it always return false even if method is simplified to return always true</p>

<p>Method:</p>

<pre><code>     bool IsHolidayRequestAlreadyCreated(String EmployeeId, DateTime DateFrom, DateTime DateTo); 
</code></pre>

<p>was simplified to always return true:</p>

<pre><code>public class HolidayRequestRepository : GenericRepository&lt;HolidayRequest&gt;, IHolidayRequestRepository
{
    public HolidayRequestRepository(MvcDbContext context) : base(context) {  }

    public bool IsHolidayRequestAlreadyCreated(string EmployeeId, DateTime DateFrom, DateTime DateTo)
    {
        return true; 
    } 

}
</code></pre>

<p>How should I mock this method to use the logic from HolidayRequestRepository  class?</p>
",https://stackoverflow.com/questions/57865840/c-mvc-generic-repository-and-unit-testing-with-moq,"['c#', '.net', 'unit-testing', 'moq']",203,True,0,1
SonarQube Coverage for the unit testing project is 0,"<p>I have used SonarQube for the code quality of the project written in c# Visual Studio.</p>

<p>The solution in the Visual Studio has Two Projects (Employee and TestEmployee). Employee is the web API project and TestEmployee is the unit testing for the Employee Project.</p>

<p>In SonarQube only Employee Project is Analyzed but not the TestEmployee Project.</p>

<p>The Coverage report is zero(o). The .cs in TestEmployee are not at all showing in the SonarQube. </p>
",https://stackoverflow.com/questions/58026428/sonarqube-coverage-for-the-unit-testing-project-is-0,"['c#', 'sonarqube', 'code-coverage', 'sonarscanner']",80,False,0,0
Unit testing custom React Hook with window resize event,"<p>I'm trying to unit test a simple custom hook, <code>getWindowWidth()</code>, but I can not get the window in Enzyme to resize.</p>

<p>I'm using enzyme to mount a component that uses the hook, setting the width of the window object, forcing a re-render, yet the window width never changes.</p>

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

<pre><code>import { useState, useEffect } from 'react';

export default function getWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() =&gt; {
    const handleResize = () =&gt; setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () =&gt; {
      window.removeEventListener('resize', handleResize);
    };
  });

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

<p>and here is my test: </p>

<pre><code>import React from 'react';
import { mount } from 'enzyme';
import getWindowWidth from './getWindowWidth';

// simulate window resize
function fireResize(width) {
  window.innerWidth = width;
  window.dispatchEvent(new Event('resize'))
}
// Test component that uses the Hook
function EffecfulComponent() {
  const viewport = getWindowWidth()
  return &lt;span&gt;{viewport}&lt;/span&gt;
}

test('should show updated window width', () =&gt; {
  const wrapper = mount(&lt;EffecfulComponent /&gt;)
  expect(wrapper.text()).toEqual('1024');
  fireResize(320);
  wrapper.update();
  expect(wrapper.text()).toEqual('320');
});
</code></pre>

<p>I expected the window to resize to 320, but it stays at 1024 (the default).</p>
",https://stackoverflow.com/questions/57497945/unit-testing-custom-react-hook-with-window-resize-event,"['javascript', 'reactjs', 'unit-testing', 'enzyme']",1305,True,1,1
How to cover TypeORM @Column decorator with Jest unit testing?,"<p>I want to Unit and e2e test my applications as much as possible and my goal is a coverage of 101%. Problem right now with my setup is, that the @Column decorator from typeorm uses an arrow function to set a default value like the current timestamp on a database update. This arrow function is not covered with jest test coverage. Message is: <code>statement not covered</code></p>

<p>I run the code coverage with: <code>jest --coverage</code>.
My versions:</p>

<pre><code>""jest"": ""^24.9.0"",
""typeorm"": ""^0.2.20""
</code></pre>

<p>Jest configuration within package.json:</p>

<pre><code>{
  ""jest"": {
    ""moduleFileExtensions"": [
      ""js"",
      ""json"",
      ""ts""
    ],
    ""rootDir"": ""src"",
    ""testRegex"": "".spec.ts$"",
    ""transform"": {
      ""^.+\\.(t|j)s$"": ""ts-jest""
    },
    ""coverageDirectory"": ""../build/coverage"",
    ""testEnvironment"": ""node"",
    ""coverageThreshold"": {
      ""global"": {
        ""branches"": 80,
        ""functions"": 80,
        ""lines"": 80,
        ""statements"": -10
      }
    }
  },
}
</code></pre>

<p>My entity looks like this:</p>

<pre class=""lang-js prettyprint-override""><code>import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Role {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    tenantId: number;

    @Column({ type: 'timestamp', update: false, default: () =&gt; 'CURRENT_TIMESTAMP()' })
    createdAt: Date;

    @Column({ type: 'timestamp', default: () =&gt; 'CURRENT_TIMESTAMP()', onUpdate: 'CURRENT_TIMESTAMP()' })
    updatedAt: Date;
}
</code></pre>

<p>Coverage for this entity:</p>

<p>(to post an image i need 10 reputation -.-): <a href=""https://i.ibb.co/FYQgstP/Screenshot-2019-11-07-11-46-45.png"" rel=""noreferrer"">https://i.ibb.co/FYQgstP/Screenshot-2019-11-07-11-46-45.png</a></p>
",https://stackoverflow.com/questions/58747303/how-to-cover-typeorm-column-decorator-with-jest-unit-testing,"['typescript', 'unit-testing', 'jestjs', 'nestjs', 'typeorm']",3520,True,6,2
Laravel php unit testing takes long in Windows Docker,"<p>I am working on Laravel with docker.</p>

<p>If I run php unit test in mac os, it takes few seconds.</p>

<p>However on windows 10, it takes few mins.</p>

<p>Is there anyway to fix this problem?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/54339813/laravel-php-unit-testing-takes-long-in-windows-docker,"['laravel', 'unit-testing', 'docker']",264,False,0,1
Unit Testing (xUnit) NLog logging service under .NET Core,"<p>.NET Core 2.1 
NLog 4.6
xUnit 2.3.1</p>

<p>I have class library with xUnit that calls a separate library that contains REST-based APIs that is responsible for creating various logs for the system. </p>

<p>Since the unit test class library calls the REST-based API controller directly, the class's Startup class isn't loaded so I don't believe NLog is being configured. This will need to be done within the unit test class library but I cannot seem to figure that out. </p>

<p>I am able to load the REST-based API nlog configuration from the calling library and then execute NLogs directly from the LogManager but the NLog implementation explicitly used within the REST-based API does not log nor does any error occur. </p>

<p>If I use a soap client such as SOAPUI and call the REST's class library, the logs are created as expected. This means the unit test class library isn't configuring logging correctly.</p>

<pre><code>// Unit Test's base class for wiring up DI and other configuration including Logging
public BaseTests()
{
    // Configuration
    string loggingServiceAPIPath = @""../../../../../../LoggingService/API/CM.LoggingService.API"";
    var builder = new ConfigurationBuilder().SetBasePath(Path.GetFullPath(loggingServiceAPIPath)).AddJsonFile(""appsettings.json"");
    var configuration = builder.Build();

    // Configure logging
    LogManager.Configuration = new XmlLoggingConfiguration(Path.GetFullPath($""{ loggingServiceAPIPath }/nlog.config""));

    // Application-Wide Services
    IServiceCollection services = new ServiceCollection();
    services.AddMvc();
    services.AddLogging();

    services.AddSingleton(configuration);
    services.AddSingleton&lt;ILoggerFactory, LoggerFactory&gt;();
    services.AddSingleton(typeof(ILogger&lt;&gt;), typeof(Logger&lt;&gt;));
    services.AddSingleton&lt;IMemoryCache, MemoryCache&gt;();
    services.AddSingleton&lt;ILoggingServiceController, LoggingServiceController&gt;();
    services.AddApplicationServices();

    services.AddOptions();
    services.ConfigureConfigServerClientOptions(configuration);
    services.AddConfiguration(configuration);
    services.Configure&lt;ConfigServerData&gt;(configuration);
    this._serviceProvider = services.BuildServiceProvider();

    // Persist configuration
    IMemoryCache iMemoryCache = this._serviceProvider.GetService&lt;IMemoryCache&gt;();
    IOptionsSnapshot&lt;ConfigServerData&gt; iConfigServerData = this._serviceProvider.GetService&lt;IOptionsSnapshot&lt;ConfigServerData&gt;&gt;();
    if (iMemoryCache != null &amp;&amp; iConfigServerData != null) { iMemoryCache.Set(CM.Common.Constants.ConfigKey, iConfigServerData.Value); }
} 

// Unit Test being called from a class library
[Fact]
public async void Test_LogDebugSuccess()
{
    LoggingServiceRequest request = new LoggingServiceRequest
    {
        ErrorException = new Exception(),
        Message = System.Reflection.MethodBase.GetCurrentMethod().Name
    };

    // This is not capturing NLog probably due to not being called in a hosted environment.
    var result = await 
    this._iLoggingServiceController.LogDebug(request);

    // Assert
    Assert.Null(result as NotFoundObjectResult);
    var okObjectResult = result as OkObjectResult;
    Assert.True((okObjectResult != null &amp;&amp;
                 okObjectResult.StatusCode.GetValueOrDefault(0) == Convert.ToInt32(System.Net.HttpStatusCode.OK)), ""Log was not created."");
}

// LoggingService
public class Program
{
    /// &lt;summary&gt;
    /// Main
    /// &lt;/summary&gt;
    /// &lt;param name=""args""&gt;Arguments&lt;/param&gt;
    public static void Main(string[] args)
    {
        // NLog: setup the logger first to catch all errors
        var logger = NLogBuilder.ConfigureNLog(""nlog.config"").GetCurrentClassLogger();
        try
        {
            logger.Debug(""Init Main"");                
            Program.BuildWebHost(args).Run();
        }
        catch (Exception ex)
        {
            logger.Error(ex, $""Stopped program because of exception: { ex.Message }"");
            throw;
        }
        finally
        {
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

    /// &lt;summary&gt;
    /// Build WebHost
    /// &lt;/summary&gt;
    /// &lt;param name=""args""&gt;Arguments&lt;/param&gt;
    /// &lt;returns&gt;WebHost interface&lt;/returns&gt;
    public static IWebHost BuildWebHost(string[] args)
    {
        try
        {
            var config = WebHost.CreateDefaultBuilder(args)
                        .CaptureStartupErrors(false)
                        .AddConfigServer()
                        .UseStartup&lt;Startup&gt;()
                        .ConfigureLogging(logging =&gt;
                        {
                            logging.ClearProviders();
                            logging.SetMinimumLevel(LogLevel.Trace);
                        })
                        .UseNLog()  // NLog: setup NLog for Dependency injection
                        .Build();

            return config;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(
            config =&gt;
            {
                config.Filters.Add(typeof(CustomExceptionFilter));
            }
        );

    // Add memory cache
    services.AddMemoryCache();

    services.AddMvc();

    services.AddCors(o =&gt; o.AddPolicy(""corspolicy"",
        builder =&gt; builder.AllowAnyOrigin()
        .AllowAnyHeader()
        .AllowAnyMethod()));

    services.AddSingleton(this.Configuration);

    // Application-Wide Services
    services.AddApplicationServices();

    // Configuration
    services.AddOptions();
    services.ConfigureConfigServerClientOptions(this.Configuration);
    services.AddConfiguration(this.Configuration);
    services.Configure&lt;ConfigServerData&gt;(this.Configuration);

    // Configure Swagger
    services.AddSwaggerGen(s =&gt;
    {
        s.SwaggerDoc(""v1"", new Info { Title = ""CM LoggingService APIs"", Version = ""V1"" });
    });
}

public void Configure(IApplicationBuilder iApplicationBuilder, IHostingEnvironment iHostingEnvironment, IConfigurationManager iConfigurationManager, IMemoryCache iMemoryCache, IApplicationLifetime iApplicationLifetime, ILogger&lt;LoggingServiceController&gt; iLogger)
{
    if (iHostingEnvironment.IsDevelopment() == true)
    {
        iApplicationBuilder.UseDeveloperExceptionPage();
        iApplicationBuilder.UseStatusCodePages();

        iApplicationBuilder.UseDatabaseErrorPage();
        iApplicationBuilder.UseBrowserLink();
    }
    if (iHostingEnvironment.IsProduction() == false)
    {
        // Swagger - API Documentation
        iApplicationBuilder.UseSwagger();
        iApplicationBuilder.UseSwaggerUI(s =&gt;
        {
            s.SwaggerEndpoint(""./v1/swagger.json"", ""CM LoggingService APIs"");
        });
    }

    // Persist Steeltoe configuration
    iConfigurationManager.Init();
    if (iMemoryCache != null &amp;&amp; iConfigurationManager != null) { iMemoryCache.Set(CM.Common.Constants.MEMORYCACHE_CONFIGURATIONMANAGER_KEY, iConfigurationManager); }
    iConfigurationManager.LogConfiguration();

    // Configure global exception handler
    iApplicationBuilder.ConfigureExceptionHandler(iLogger);

    iApplicationBuilder.UseMvc();

    // Application Events
    iApplicationLifetime.ApplicationStarted.Register(this.OnApplicationStarted);
    iApplicationLifetime.ApplicationStopped.Register(this.OnApplicationStopping);
}

public class LoggingServiceController : Controller, ILoggingServiceController
{
    private readonly ILogger&lt;LoggingServiceController&gt; _iLogger = null;
    private readonly ILoggingServiceDomainController _iLoggingServiceDomainController = null;

    public LoggingServiceController(ILogger&lt;LoggingServiceController&gt; iLogger, ILoggingServiceDomainController iLoggingServiceDomainController)
    {
        this._iLogger = iLogger;
        this._iLoggingServiceDomainController = iLoggingServiceDomainController;
    }

    [HttpPost(""LogError"")]
    public async Task&lt;IActionResult&gt; LogError([FromBody] LoggingServiceRequest request)
    {
        bool result = false;

        try
        {
            // Validation
            if (ModelState.IsValid == false)
            {
                this._iLogger.LogError($""{ CM.Common.ExceptionHandling.ExceptionTypes.VALIDATION }: { typeof(LoggingServiceRequest).Name } (request) is not valid."");
                return BadRequest();
            }

            // Log
            result = this._iLogger.LogError(request.ErrorException, request.Message, request.Args);
            if (result == false) { return NotFound(); }
        }
        catch (Exception ex)
        {
            this._iLogger.LogError(ex, $""{ CM.Common.ExceptionHandling.ExceptionTypes.UNSPECIFIED }: { ex.Message }"");
        }

        return Ok(result);
    }
}

</code></pre>
",https://stackoverflow.com/questions/55575270/unit-testing-xunit-nlog-logging-service-under-net-core,"['rest', 'nlog', 'xunit']",566,False,0,0
Unit testing methods declared inside another method in Node,"<p>i have a node module of the following format </p>

<pre><code>'use strict’;

/// require dependencies here 

function outerFunc1(a, b, c) {

  function f1() {
    return f2()
  }

  function f2() {
    return 2
  }
  f1();
}
const choose = (type) =&gt; {
  let funcToCall
  switch (type) {
    case ""func1"":
      funcToCall = outerFunc1;
      break;
  }
  return funcToCall;
}

module.exports = (function () {
  return {
    choose
  };
})();
</code></pre>

<p>Can any one tell me how to unit test function f2 and f1 or in other words how can i invoke the same , is there any way to achieve the same like using reflection api or any other way using rewire or sinon ?</p>
",https://stackoverflow.com/questions/54800841/unit-testing-methods-declared-inside-another-method-in-node,"['javascript', 'node.js', 'unit-testing', 'reflection', 'sinon']",51,False,0,1
Unit testing cover catch block in RxJava Observable response,"<p>I have a try-catch block in the onError part of the subscriber of RxJava as shown. </p>

<pre><code>    fun requestAutocomplete() {
        mApi.add().subscribeOn(
            Schedulers.io()
          ).observeOn(
            AndroidSchedulers.mainThread()
          ).subscribe({
            it?.let {
              //do something
            }
          }, {
            try {
             //do something
            } catch (ex: Exception) {
              view.doThis(ex)
            }
          })
        )
      }
</code></pre>

<p>I want to cover the catch block to increase my code coverage. I can not remove it from actual code which was written a long time back. </p>

<p>This is what I tried but with no success: </p>

<pre><code>    @Test fun handleExceptionRequestAutoComplete() {
        Mockito.doAnswer({throwException()}).`when`(
            mApi.add()
          )
        )
        presenter.requestAutocomplete()
        Mockito.verify(view).doThis(throwException())
      }
</code></pre>
",https://stackoverflow.com/questions/57587872/unit-testing-cover-catch-block-in-rxjava-observable-response,"['android', 'unit-testing', 'kotlin', 'rx-java']",504,False,0,1
Spring Cloud Stream Processor Unit Testing - @Autowire not working,"<p>I am trying to write a <em>spring cloud stream processor</em> class that takes an <em>XML</em> in through using the <code>@StreamListener(Processor.INPUT)</code> annotation. </p>

<p>The processor then extracts smaller <em>XML</em> messages and sends them to the output via <code>this.processor.output().send(message);</code>
I have not yet deployed this to <em>dataflow</em> because I wanted to test it with <strong>junit</strong>. When I run this with <strong>junit</strong> I can not seem to get my Processor object to instantiate. </p>

<p>I have tried using <code>@Autowired</code> which is how I have seen it done in may examples but I can't seem to get it to work.  Any ideas would be appreciated. </p>

<p>My code is below.</p>

<pre><code>package io.spring.dataflow.sample.usagecostprocessor;

import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import lombok.AllArgsConstructor;

@AllArgsConstructor
@EnableBinding(Processor.class)
public class REDACTXMLSplitter {


    private Processor processor;

    //@Autowired
    //private SendingBean sendingBean;

    @SuppressWarnings(""unchecked"")
    @StreamListener(Processor.INPUT)
    public void parseForREDACTApplications(String redactXML) {
        InputSource doc = new InputSource( new StringReader( redactXML ) );

        try
         {

                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true); // never forget this!

                XPathFactory xfactory = XPathFactory.newInstance();
                XPath xpath = xfactory.newXPath();

                String xpathQuery = ""//REDACT/Application"";

                xpath = xfactory.newXPath();
                XPathExpression query = xpath.compile(xpathQuery);
                NodeList productNodesFiltered = (NodeList) query.evaluate(doc, XPathConstants.NODESET);

                for (int i=0; i&lt;productNodesFiltered.getLength(); ++i)
                {

                    Document suppXml = dBuilder.newDocument();

                    //we have to recreate the root node &lt;products&gt;
                    Element root = suppXml.createElement(""REDACT""); 

                    Node productNode = productNodesFiltered.item(i);

                    //we append a product (cloned) to the new file
                    Node clonedNode = productNode.cloneNode(true);
                    suppXml.adoptNode(clonedNode); //We adopt the orphan :)
                    root.appendChild(clonedNode);

                    suppXml.appendChild(root);


                    //write out files
                    //At the end, we save the file XML on disk
//                      TransformerFactory transformerFactory = TransformerFactory.newInstance();
//                      Transformer transformer = transformerFactory.newTransformer();
//                      transformer.setOutputProperty(OutputKeys.INDENT, ""yes"");
//                      DOMSource source = new DOMSource(suppXml);
//                      StreamResult result =  new StreamResult(new File(""test_"" + i + "".xml""));
//                      transformer.transform(source, result);

                    TransformerFactory tf = TransformerFactory.newInstance();
                    Transformer transformer = tf.newTransformer();
                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ""yes"");
                    StringWriter writer = new StringWriter();
                    transformer.transform(new DOMSource(suppXml), new StreamResult(writer));
                    String output = writer.getBuffer().toString().replaceAll(""\n|\r"", """");

                    System.out.println(output);

                    Message&lt;String&gt; message = (Message&lt;String&gt;) suppXml;
                    this.processor.output().send(message);
                }

            }
         catch (XPathExpressionException | ParserConfigurationException | TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code></pre>

<hr>

<pre><code>package io.spring.dataflow.sample.usagecostprocessor;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


    @SpringBootApplication
    public class REDACTXMLSplitterApplication {
        public static void main(String[] args) {
            SpringApplication.run(REDACTXMLSplitterApplication.class, args);
        }
    }
</code></pre>

<hr>

<pre><code>package io.spring.dataflow.sample.usagecostprocessor;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.util.ResourceUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext
public class MAIPXMLSplitterApplicationTests {


    @Autowired
    private Processor myProcessor;


    @Test
    public void contextLoads() {
    }

    @Test
    public void parseXML() {
            try {
                String cmErrorPayloadXML = readFile(ResourceUtils.getFile(this.getClass().getResource(""/XMLSamples/REDACTApplicationXMLSamples/redact.xml"")));
                REDACTXMLSplitter redactXMLSplitter = new REDACTXMLSplitter(myProcessor);
                redactXMLSplitter.parseForREDACTApplications(cmErrorPayloadXML);
            } catch (IOException e) {
                e.printStackTrace();
            }
    }


      public String readFile(File file) {
            StringBuffer stringBuffer = new StringBuffer();
            if (file.exists())
                try {
                    //read data from file
                    FileInputStream fileInputStream = new FileInputStream(file);
                    int c;
                    while ((c = fileInputStream.read()) != -1){
                        stringBuffer.append((char) c);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return stringBuffer.toString();
        }

}
</code></pre>

<hr>

<p>Update,</p>

<p>I tried this but myProcessor is still null</p>

<pre><code>package io.spring.dataflow.sample.usagecostprocessor;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.ResourceUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MAIPXMLSplitterApplicationTests.TestProcessor.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MAIPXMLSplitterApplicationTests {


    @Autowired
    private Processor myProcessor;

    @Test
    public void contextLoads() {
    }

    @Test
    public void parseXML() {
            try {
                String cmErrorPayloadXML = readFile(ResourceUtils.getFile(this.getClass().getResource(""/XMLSamples/MAIPApplicationXMLSamples/354_20191126_MAIP.xml"")));
                MAIPXMLSplitter maipXMLSplitter = new MAIPXMLSplitter(myProcessor);
                maipXMLSplitter.parseForMAIPApplications(cmErrorPayloadXML);
            } catch (IOException e) {
                e.printStackTrace();
            }
    }


      public String readFile(File file) {
            StringBuffer stringBuffer = new StringBuffer();
            if (file.exists())
                try {
                    //read data from file
                    FileInputStream fileInputStream = new FileInputStream(file);
                    int c;
                    while ((c = fileInputStream.read()) != -1){
                        stringBuffer.append((char) c);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return stringBuffer.toString();
        }

        @EnableBinding(Processor.class)
        @EnableAutoConfiguration
        public static class TestProcessor {

        }

}
</code></pre>
",https://stackoverflow.com/questions/59270731/spring-cloud-stream-processor-unit-testing-autowire-not-working,"['spring', 'junit', 'autowired', 'spring-cloud-stream', 'spring-cloud-dataflow']",767,False,0,1
Junit test not passing. New to unit testing services,"<p>Writing a unit test for my Spring Boot service method and I cannot get it to pass. I am a front end developer so I am not very familiar with unit testing in Java. The multipartFile is what is confusing me the most, as well as completing the entire Junit test.</p>

<p>Junit4 with mockito unit test. Tried stackoverflow and google for potential corrections. </p>

<p>Contract Service</p>

<pre><code>@Slf4j
@Service
public class ContractService {

    @Autowired
    public ContractRepository contractRepository;

    @Autowired
    public JdbcTemplate jdbcTemplate;

    @Autowired
    public UserSettingsService userSettingsService;

    @Autowired
    public ContractPermissionsService contractPermissionsService;

    @Autowired
    public OCRSubmissionService ocrSubmissionService;

    @Autowired
    public ContractDocumentStorageService contractDocumentStorageService;

    public Contract getContract(int contractID) {
       Contract contract = contractRepository.getOne(contractID);
       return contract;
    }

    //TODO: come back and reduce contractID / metaID to one ID.
    //TODO: add trigger in DB layer for coterminous
    // TODO: make sure isVisible defaults to false

    /*
    When adding a new contract, the following steps are taken:
    1. SQL transaction is begun
    2. The meta information is stored, and an ID is generated in SQL.
    3. The file is stored with the corresponding document ID.
    4. The meta information is updated with the document link.
    5. A login, submission, and logoff are made to KTA.
    6. As long as all these steps have completed, the transaction is completed
    7. Otherwise, the transaction is cancelled ad an error is thrown (controller returns 500)
     */
    @Transactional(rollbackFor=Exception.class)
    public Contract addNewContract(Contract contract, MultipartFile file) throws Exception {
        Contract newContract = this.contractRepository.save(contract);
        int ID = contract.getId();
        int fileID = this.contractDocumentStorageService.storeFile(file, ID);
        contract.setDocumentPathDesc(Integer.toString(fileID));
        this.addViewingPermissionsForSubmitter(contract);
        Boolean success = this.ocrSubmissionService.SubmitContractForOCR(file, contract.getId());
        if(success) {
            return this.contractRepository.saveAndFlush(newContract);
        } else {
            throw new OCRSubmissionFailureException(""Error in OCR Submission"");
        }
    }
</code></pre>

<p>Contract Service Test</p>

<pre><code>public class ContractServiceTest {

    ContractService contractServiceUnderTest;


    @Before
    public void setUp() {
        contractServiceUnderTest = new ContractService();
        contractServiceUnderTest.contractRepository = mock(ContractRepository.class);
        contractServiceUnderTest.jdbcTemplate = mock(JdbcTemplate.class);
        contractServiceUnderTest.userSettingsService = mock(UserSettingsService.class);
        contractServiceUnderTest.contractPermissionsService = mock(ContractPermissionsService.class);
        contractServiceUnderTest.ocrSubmissionService = mock(OCRSubmissionService.class);
        contractServiceUnderTest.contractDocumentStorageService = mock(ContractDocumentStorageService.class);
    }

    @Test
    public void testAddNewContract() throws Exception {
        // Setup
        final Contract contract = new Contract();
        final MultipartFile file = null;
        final Contract expectedResult = null;

        // Run the test
        final Contract result = contractServiceUnderTest.addNewContract(contract, file);

        // Verify the results
        assertEquals(expectedResult, result);
    }
</code></pre>
",https://stackoverflow.com/questions/55497835/junit-test-not-passing-new-to-unit-testing-services,"['java', 'junit', 'mockito']",185,False,0,0
Laravel php unit testing takes long in Windows Docker,"<p>I am working on Laravel with docker.</p>

<p>If I run php unit test in mac os, it takes few seconds.</p>

<p>However on windows 10, it takes few mins.</p>

<p>Is there anyway to fix this problem?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/54339813/laravel-php-unit-testing-takes-long-in-windows-docker,"['laravel', 'unit-testing', 'docker']",264,False,0,1
Unit testing web api controller with role based authorization,"<p>I want to test my controller action that looks like this:</p>

<pre><code>    [HttpGet(""{id}"")]
    public IActionResult GetUserById(int id)
    {
        var user = _userService.GetUserById(id);

        if (user == null)
        {
            return NotFound();
        }

        var currentUserId = int.Parse(User.Identity.Name);
        if (id != currentUserId &amp;&amp; !User.IsInRole(Role.Admin))
        {
            return Forbid();
        }

        return Ok(user);
    }
</code></pre>

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

<pre><code>    [Test]
    [TestCase(1)]
    public void GetUserById_ValidIdAsParameter_ShouldReturnOk(int id)
    {
        var result = _controller.GetUserById(id);


        Assert.That(result, Is.TypeOf&lt;OkObjectResult&gt;()); 
    }
</code></pre>

<p>My problem is that I get 'Object reference not set to an instance of an object.' for this line:</p>

<pre><code>var currentUserId = int.Parse(User.Identity.Name);
</code></pre>

<p>I'm unable to set myController.User.Identity.Name since it is a read only property. </p>
",https://stackoverflow.com/questions/56753621/unit-testing-web-api-controller-with-role-based-authorization,"['unit-testing', 'nunit', 'asp.net-core-webapi']",23,False,0,0
How to spy on window.onclick within Jasmine unit testing,"<p>How can I spy on a window.onclick <strong>event</strong> within Jasmine.
Tried to create a spy for window onclick and call this, but that didn't work.</p>

<p>The code which I want to cover with Jasmine:</p>

<pre><code>setClass() {
    const input = this.document[0].querySelector('.wrapper');
    const inputButton = this.document[0].querySelector('.input-button');
    const inputField = this.document[0].querySelector('.input-field');

    this.window.onclick = function(event) {
        if (event.target !== inputButton &amp;&amp; input.classList.contains('active')) {
            input.classList.remove('active');
        } if (event.target === inputField) {
            input.classList.add('active');
        } else {
            input.classList.remove('active');
        }
    };
}
</code></pre>

<p>This is what I tried:</p>

<pre><code>describe('setClass method', () =&gt; {
    it('should add class active to the wrapper', () =&gt; {
        const classController = new classController(this.document, this.window);
        const elementWrapper = angular.element('&lt;div class=""wrapper""&gt;&lt;/div&gt;');
        const elementBtn = angular.element('&lt;button class=""input-button""&gt;&lt;/button&gt;');
        const elementInpt = angular.element('&lt;input class=""input-field"" type=""text""&gt;');

        spyOn(classController.document[0], 'querySelector').and.returnValues(elementWrapper[0], elementBtn[0], elementInpt[0]);
        spyOn(classController.window, 'onclick');

        classController.window.onclick(elementInpt);
        classController.setClass();

        expect(elementWrapper[0].outerHTML).toBe('&lt;div class=""wrapper active""&gt;&lt;/div&gt;');
    });
});
</code></pre>

<p>The code is now covered untill this.window.onclick, how can I mock the event?</p>
",https://stackoverflow.com/questions/59070575/how-to-spy-on-window-onclick-within-jasmine-unit-testing,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",549,False,0,1
"RxJava Unit Testing for Observable.Interval, &quot;Context has changed&quot; error","<p>I am trying to write unit tests for the code block below :</p>

<pre><code>Observable.interval(INITIAL_DELAY, REFRESH_PERIOD, TimeUnit.SECONDS)
            .flatMap {thisMethodReturnsAnObservable()}
            .subscribeOn(Schedulers.io()) 
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(this::onDataLoaded, this::onError)
            .disposeLater()) 
</code></pre>

<p>I have a test rule that overrides the RxSchedulers with testSchedulers which works.</p>

<p><strong>Important</strong> the tests can run one by one, but not all together, also run with coverage is broken with the same error.</p>

<p>The error I am getting is, the running of the test immediately stops when debugger hits the <code>onDataLoaded</code> method, and displays the following message:
<a href=""https://i.stack.imgur.com/OsE6u.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/OsE6u.png"" alt="" &quot;""></a></p>
",https://stackoverflow.com/questions/56157936/rxjava-unit-testing-for-observable-interval-context-has-changed-error,"['unit-testing', 'kotlin', 'mockito', 'junit4', 'rx-java2']",549,True,0,2
Should we modify a function signature for unit testing?,"<p>Suppose we have a function <code>add()</code> as below:</p>

<pre><code>void add(int a, int b) {
    int sum=a+b;
    cout&lt;&lt;sum;
    sendSumToStorage(sum);
}
</code></pre>

<p>This simple function adds to input values, prints the sum to the console and also sends it to some external storage (say, a file).  This is how we ideally want it in the application (meaning, we don't want it to <em>return anything</em>).</p>

<p>For purposes of unit testing, is it valid (from a design perspective) if we modify the function signature so that it returns the <code>sum</code>?  We could then have a test like:</p>

<pre><code>bool checkAdd() {
    int res=add(3, 4);
    if(res==7) return true;
    else return false;
}
</code></pre>

<p>Better yet, is this (<em>returning a value</em>) the only way we could unit test it?  Is there some <em>valid</em> way in which we could unit test the <code>add()</code> function without changing the function signature?</p>
",https://stackoverflow.com/questions/56373047/should-we-modify-a-function-signature-for-unit-testing,"['c++', 'unit-testing', 'testing']",391,True,0,3
differences in unit testing frameworks and how to use,"<p>I am trying to compare the following test frameworks</p>

<p>•   Microsoft Unit Testing Framework for C++
•   Google Test
•   Boost.Test
•   CTest</p>

<p>And I am lost.  Which is best?  And how to write test-driven development.  We are a Microsoft shop with 80% C++ code and 20% c#</p>
",https://stackoverflow.com/questions/58207511/differences-in-unit-testing-frameworks-and-how-to-use,"['windows', 'unit-testing']",46,True,-1,1
Unit testing methods which update UI elements in iOS,"<p>I am trying to write unit tests for my existing code. 
I have 3 methods.</p>

<pre><code>func methodOne() {
    // code
    methodTwo()
}

func methodTwo() {
    // code
    methodThree()
}

func methodThree() {
    // code
    // update UI element
}
</code></pre>

<p>What's the ideal way to unit test such methods. While unit testing <code>methodTwo()</code> it calls <code>methodThree()</code> as the UI elements are not loaded they have <code>nil</code> value when <code>methodThree()</code> is called. How to unit test methods which involve UI elements. I don't want to test if the UI element is loaded properly, I just want to test the code in <code>methodTwo()</code> and <code>methodThree()</code>. Is there a way to bypass UI elements related code. Any help is appreciated. Thank you.</p>
",https://stackoverflow.com/questions/55727108/unit-testing-methods-which-update-ui-elements-in-ios,"['ios', 'swift', 'unit-testing']",180,False,0,2
"C# MVC, Generic Repository and Unit Testing with Moq","<p>I have to test a method which returns true or false if date range overlaps with any item of list.</p>

<p><b>List items are holiday requests: </b></p>

<pre><code>public class HolidayRequest
{
    public int Id { get; set; } 
    public string EmployeeId { get; set; }
    public DateTime DateFrom { get; set;  }
    public DateTime DateTo { get; set; } 

}

public interface IHolidayRequestRepository :IGenericRepository&lt;HolidayRequest&gt;
{ 
    bool IsHolidayRequestAlreadyCreated(String EmployeeId, DateTime DateFrom, DateTime DateTo); 
} 

public interface IGenericRepository&lt;TEntity&gt; where TEntity : class
{
    IQueryable&lt;TEntity&gt; GetAll();
    TEntity Get(object id);
    //skipped 
}
</code></pre>

<p>Now unit tests:</p>

<pre><code>[TestClass]
public class UnitTest1
{
    private Mock&lt;IHolidayRequestRepository &gt; _holidayRepository;
    [TestInitialize]
    public void Initialize()
    {
        _holidayRepository = new Mock&lt;IHolidayRequestRepository &gt;();
    }
    [TestMethod]
    public void TestMethod1()
    {

        //Arange
        IList&lt;HolidayRequest&gt; list = new List&lt;HolidayRequest&gt;
        {
             new HolidayRequest{ Id =1, EmployeeId=""E00001"", DateFrom = new DateTime(2019,09,13,0,0,0), DateTo = new DateTime(2019,09,13,0,0,0)}
        };
        _holidayRepository.Setup(x =&gt; x.GetAll()).Returns(list.AsQueryable);

        var howMany = _holidayRepository.Object.GetAll().Count();

        //Assert
        Assert.AreEqual(1, howMany); //&lt;- Test passed

        bool val = _holidayRepository.Object
             .IsHolidayRequestAlreadyCreated(""E00001"", new DateTime(2019, 9, 12), new DateTime(2019, 9, 14));

        ////Assert
       Assert.IsTrue(val);  //&lt;- Test error - always return false

    }
}
</code></pre>

<p>I expect the test result to be true, but it always return false even if method is simplified to return always true</p>

<p>Method:</p>

<pre><code>     bool IsHolidayRequestAlreadyCreated(String EmployeeId, DateTime DateFrom, DateTime DateTo); 
</code></pre>

<p>was simplified to always return true:</p>

<pre><code>public class HolidayRequestRepository : GenericRepository&lt;HolidayRequest&gt;, IHolidayRequestRepository
{
    public HolidayRequestRepository(MvcDbContext context) : base(context) {  }

    public bool IsHolidayRequestAlreadyCreated(string EmployeeId, DateTime DateFrom, DateTime DateTo)
    {
        return true; 
    } 

}
</code></pre>

<p>How should I mock this method to use the logic from HolidayRequestRepository  class?</p>
",https://stackoverflow.com/questions/57865840/c-mvc-generic-repository-and-unit-testing-with-moq,"['c#', '.net', 'unit-testing', 'moq']",203,True,0,1
SonarQube Coverage for the unit testing project is 0,"<p>I have used SonarQube for the code quality of the project written in c# Visual Studio.</p>

<p>The solution in the Visual Studio has Two Projects (Employee and TestEmployee). Employee is the web API project and TestEmployee is the unit testing for the Employee Project.</p>

<p>In SonarQube only Employee Project is Analyzed but not the TestEmployee Project.</p>

<p>The Coverage report is zero(o). The .cs in TestEmployee are not at all showing in the SonarQube. </p>
",https://stackoverflow.com/questions/58026428/sonarqube-coverage-for-the-unit-testing-project-is-0,"['c#', 'sonarqube', 'code-coverage', 'sonarscanner']",80,False,0,0
How to mock &quot;this&quot; keyword in Jest Unit Testing,"<p>I need to this code using Jest Unit Testing:</p>

<pre><code>componentDidUpdate(prevProps) {
    if (prevProps.socialMediaId !== this.props.socialMediaId) {
      if (typeof this.window.FB !== 'undefined') {
        this.window.FB.XFBML.parse();
      }
    }
  }
</code></pre>

<p>using the test case:</p>

<pre><code>it('should test componentDidUpdate', () =&gt; {
    props.socialMediaId = '/old_id/';
    const component = mount(&lt;MyComponent {...props} /&gt;);
    this.window.FB = {
      XFBML: {
        parse: () =&gt; {}
      }
    };
    props.socialMediaId = '/new_id/';
    component.setProps(props);
    expect(this.window.FB.XFBML.parse).toHaveBeenCalled();
  });
</code></pre>

<p>But, I'm getting the error:</p>

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

<p>How to fix this issue with ""<strong>this</strong>"" keyword in this case?</p>
",https://stackoverflow.com/questions/54568373/how-to-mock-this-keyword-in-jest-unit-testing,"['javascript', 'reactjs', 'unit-testing', 'this', 'jestjs']",4551,True,0,1
How to do unit testing for windows form application,"<p>how to do unit testing for windows form application. I have create <strong>Form2</strong> and i want test that form using nUnit , i got this error :</p>

<blockquote>
  <p>Message: 
      System.TypeInitializationException : The type initializer for '...Form2' threw an exception.
        ----> System.Threading.ThreadStateException : ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because
  the current thread is not in a single-threaded apartment.</p>
</blockquote>

<p>Test</p>

<pre><code>[TestFixture,SingleThreaded]
public class FormTest
{

    [SetUp]
    public void Setup()
    {

    }
    [Test]
    public void Form_Test()
    {
        var form = new Form2();

    }
}
</code></pre>

<p>code :
Form2</p>

<pre><code>public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public void SomeThing()
    { 

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

<p>code : Form2.Designer</p>

<pre><code>partial class Form2
{
    /// &lt;summary&gt;
    /// Required designer variable.
    /// &lt;/summary&gt;
    private System.ComponentModel.IContainer components = null;

    /// &lt;summary&gt;
    /// Clean up any resources being used.
    /// &lt;/summary&gt;
    /// &lt;param name=""disposing""&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt;
    protected override void Dispose(bool disposing)
    {
        if (disposing &amp;&amp; (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// &lt;summary&gt;
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// &lt;/summary&gt;
    private void InitializeComponent()
    {
        this.webBrowser1 = new System.Windows.Forms.WebBrowser();
        this.SuspendLayout();
        // 
        // webBrowser1
        // 
        this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.webBrowser1.Location = new System.Drawing.Point(0, 0);
        this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
        this.webBrowser1.Name = ""webBrowser1"";
        this.webBrowser1.Size = new System.Drawing.Size(800, 450);
        this.webBrowser1.TabIndex = 0;
        // 
        // Form2
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(800, 450);
        this.Controls.Add(this.webBrowser1);
        this.Name = ""Form2"";
        this.Text = ""Form2"";
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.WebBrowser webBrowser1;
}
</code></pre>
",https://stackoverflow.com/questions/59171188/how-to-do-unit-testing-for-windows-form-application,"['c#', 'winforms', 'unit-testing']",1280,True,-1,2
Enzyme unit testing onChange method using Material UI Components,"<p>How would i be able to unit-test onChange method on this component.  </p>

<p><strong>Comment.js</strong></p>

<pre><code>import React  from ""react"";
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
const Comment = (props) =&gt; (
    &lt;div&gt;

        &lt;form onSubmit={props.onSubmit}&gt;
             &lt;TextField
                type=""text""
                id=""outlined-multiline-static""
                label=""Write A Comment""
                multiline
                name=""comment_body""
                value={props.commentBody}
                rows=""10""
                fullWidth
                margin=""normal""
                variant=""outlined""
                onChange={props.commentChange}
            /&gt;
            {/* &lt;Button type=""submit"" variant=""outlined"" component=""span"" color=""primary""&gt;
                Post A Comment
            &lt;/Button&gt; */}
             &lt;button type=""submit"" variant=""outlined"" component=""span"" color=""primary""&gt;
                Write a Comment
            &lt;/button&gt;
        &lt;/form&gt;
    &lt;/div&gt;
)

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

<p>This is my attempt to unit test the onChange component, getting a </p>

<blockquote>
  <p>Method “simulate” is meant to be run on 1 node. 0 found instead </p>
</blockquote>

<p>around this line </p>

<p><code>const component = shallow(&lt;Comment commentChange={onChangeMock} commentBody={'test'} /&gt;)</code>
<code>component.find('input').simulate('change');</code></p>

<p>Comment.test.js</p>

<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';

import Comment from './Comment';




describe('Should render &lt;Comment/&gt; component', () =&gt; {

    it('Should render form', () =&gt; {
        const wrapper = shallow(&lt;Comment/&gt;)
        // wrapper.find('Form').at(0)
        expect(wrapper.find(""form"")).toHaveLength(1); // checks if there is a form. 

    })

    it('Should render button', () =&gt; {
        const wrapper = shallow(&lt;Comment/&gt;)
        expect(wrapper.find('button')).toHaveLength(1);
    })

    it('should check for onChange method', () =&gt; {
        // const wrapper = shallow(&lt;Comment onChange={}/&gt;)
        const onChangeMock = jest.fn();
        // const event = {
        //     preventDefualt(){},
        //     target: {
        //         value: 'testing'
        //     }
        // }
        const component = shallow(&lt;Comment commentChange={onChangeMock} commentBody={'test'} /&gt;)
        component.find('input').simulate('change');
        expect(onChangeMock).toBeCalledWith('test')
    })



})
</code></pre>

<p>The Comment component is being passed in another component like this:</p>

<p><strong>ImageContainer.js</strong></p>

<pre><code> state = {
      isComment: false,
      comment_body: """"
    }
    handleCommentChange = (e) =&gt; {
        this.setState({
           comment_body: e.target.value
        })             
    }

    commentSubmit = (event, id) =&gt; {
        event.preventDefault();
        console.log(this.state.comment_body); // doesn't get console.log
        // note that commentBody is being used for the req.body as well so its called by req.body.commentBody
        const commentBody = this.state.comment_body
        const data = {   
            commentBody,
            id
        }   
        this.props.postComment(data);
        this.setState({
            comment_body: ''
        })

    }

    &lt;Comment onSubmit={(e) =&gt; this.commentSubmit(e, img.id)} 
                commentBody={this.state.comment_body } 
                commentChange={this.handleCommentChange}/&gt; 
</code></pre>
",https://stackoverflow.com/questions/56639227/enzyme-unit-testing-onchange-method-using-material-ui-components,"['reactjs', 'jestjs', 'material-ui', 'enzyme']",2183,True,0,1
Mocking a current logged in user for unit testing,"<p>I need to mock current logged in user for testing the following function. This function returns the id of the current logged in user from the Users table in the database.</p>

<pre><code>  public static string CurrentUser()
    {
        string loginuser= System.Web.HttpContext.Current.User.Identity.Name;
        if(loginuser != """")
        {
            using (var cntx = new EdmxEntities())
            {
                return cntx.Users.Where(s =&gt; s.Email == loginuser).Select(x =&gt; x.Id).FirstOrDefault();
            }
        }
        return loginuser;

    }
</code></pre>

<p>(System.Web.HttpContext.Current.User.Identity.Name) This function returns the current logged in username but returns null during testing which throws an Null Reference Exception.</p>
",https://stackoverflow.com/questions/58390419/mocking-a-current-logged-in-user-for-unit-testing,"['c#', 'asp.net', 'asp.net-mvc', 'unit-testing', 'mocking']",1163,True,0,1
Large File Read Memory Limit in .Net Unit Testing,"<p>I have a file which size 300 mb.
I read it from my console app but when I try into the unit test that time it throws out of memory exception.What is the difference between unittest and console app?They are running on same machine and they are both Debug/Any CPU and their target framework are same.</p>

<pre><code> var path = ""C:\\my.xml"";
string xmlString = System.IO.File.ReadAllText(path);
</code></pre>
",https://stackoverflow.com/questions/58560456/large-file-read-memory-limit-in-net-unit-testing,"['c#', '.net', 'vs-unit-testing-framework']",366,False,0,0
Getting error while unit testing of angular component method?,"<p>I am running a unit test which is failing. Please look at my code:</p>

<p>This is my <strong>typescript file:</strong></p>

<pre><code>  allData: any;
  constructor(@Inject(MAT_DIALOG_DATA) private data,
    private dialogRef: MatDialogRef&lt;MyComponent&gt;,
    private _service: SampleService,
    private _router: Router) {
  }
  ngOnInit() {
    this.loadValue();
  }
  loadValue() {
    this._service.returnData().subscribe(res =&gt; {
      this.allData = res;
    })
  }
</code></pre>

<p>This is my <strong>service file implementation:</strong></p>

<pre><code>  //SampleService
  returnData(){
    const users=[{ id: ""01"", name:""Andrew"" }, { id: ""02"", name:""Shaun"" }];
    return of(users);
  }
</code></pre>

<p>This is my <strong>spec file:</strong></p>

<pre><code>describe('MyComponent', () =&gt; {
  let component: MyComponent;
  let fixture: ComponentFixture&lt;MyComponent&gt;;
  let el: DebugElement;
  let sampleservice: SampleService;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      imports: [MatDialogModule],
      providers: [
        {
          provide: MAT_DIALOG_DATA, useValue: { action: ""add"" },
        },
        {
          provide: MatDialogRef, useValue: { MyComponent}
        },
        {
          provide: Router
        },
        {
          provide: SampleService
        }
      ]
    }).compileComponents()
  }));
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(MyComponent);
    el = fixture.debugElement;
    component = fixture.componentInstance;
    sampleservice = new SampleService();
  })
</code></pre>

<p>My <strong>test case:</strong></p>

<pre><code>  it(""should call the loadvalue and fill the allData"", () =&gt; {
    let users = [{ id: ""01"", name: ""John"" }, { id: ""02"", name: ""Wick"" }];
    component.loadValue();
    spyOn(sampleservice, 'returnData').and.returnValue(of(users));
    expect(component.allData).toBe(users);
  })
</code></pre>

<p>I want to call the <code>loadvalue()</code> method and expecting the <code>allData</code> variable to filled with the dummy response using <code>spyOn</code>.
But when I run this test case, I get error as:</p>

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

<p>What am I doing wrong here? Any help would be much appreciated. Thanks!</p>
",https://stackoverflow.com/questions/58790256/getting-error-while-unit-testing-of-angular-component-method,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'angular-unit-test']",645,True,0,1
How to use imported graphql files in jest unit testing?,"<p>I'm trying to run unit tests with jest but I'm getting the following error:</p>

<pre><code>  ● Test suite failed to run

/apollo/queries/articles.gql:1
({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){query articles($orderBy: [OrderByClause!], $stripTags: Boolean, $maxCharacters: Int) {
                                                                                               ^^^^^^^^

SyntaxError: Unexpected identifier
</code></pre>

<p>I have installed </p>

<blockquote>
  <p><a href=""https://github.com/jagi/jest-transform-graphql"" rel=""noreferrer"">https://github.com/jagi/jest-transform-graphql</a></p>
</blockquote>

<p>It's suppose to transform GQL files.</p>

<p>My package.json (jest part)</p>

<pre><code>""jest"": {
    ""moduleFileExtensions"": [
        ""js"",
        ""json"",
        ""vue"",
        ""gql""
    ],
    ""watchman"": false,
    ""moduleNameMapper"": {
        ""^~/(.*)$"": ""&lt;rootDir&gt;/$1"",
        ""^~~/(.*)$"": ""&lt;rootDir&gt;/$1""
    },
    ""transform"": {
        ""^.+\\.js$"": ""&lt;rootDir&gt;/node_modules/babel-jest"",
        "".*\\.(vue)$"": ""&lt;rootDir&gt;/node_modules/vue-jest"",
        ""\\.(gql|graphql)$"": ""@jagi/jest-transform-graphql""
    },
    ""snapshotSerializers"": [
        ""&lt;rootDir&gt;/node_modules/jest-serializer-vue""
    ],
    ""collectCoverage"": true,
    ""collectCoverageFrom"": [
        ""&lt;rootDir&gt;/components/**/*.vue"",
        ""&lt;rootDir&gt;/pages/*.vue""
    ]
}
</code></pre>

<p>Test file</p>

<pre><code>import Index from ""../index"";

const factory = () =&gt;
    shallowMount(Index, {
        propsData: {
            label: ""click me!""
        }
    });

describe(""Index"", () =&gt; {
    test(""mounts properly"", () =&gt; {
        const wrapper = factory();
        expect(wrapper.isVueInstance()).toBeTruthy();
    });

    test(""renders properly"", () =&gt; {
        const wrapper = factory();
        expect(wrapper.html()).toMatchSnapshot();
    });
});
</code></pre>

<p>index.vue file (stripped out unimportant things)</p>

<pre><code>&lt;template&gt;
    &lt;div&gt;&lt;/div&gt;
&lt;/template&gt;

&lt;script lang=""ts""&gt;
import Vue from ""vue"";
import ArticlesQuery from ""~/apollo/queries/articles.gql"";

export default Vue.extend({
    name: ""Homepage"",
    apollo: {
        articles: {
            query: ArticlesQuery,
            variables() {
                return {
                    orderBy: [{ field: ""id"", order: ""DESC"" }],
                    stripTags: true,
                    maxCharacters: 150
                };
            },

            prefetch: true
        }
    }
});
&lt;/script&gt;
</code></pre>

<p>This is my first time doing unit testing, so I have zero knowledge on this subject.</p>
",https://stackoverflow.com/questions/59412890/how-to-use-imported-graphql-files-in-jest-unit-testing,"['unit-testing', 'vue.js', 'nuxt.js', 'vue-apollo']",1735,False,6,1
Karma Unit Testing for angular Forms gives the error &quot;&quot;,"<p>I have following test case,</p>

<pre><code>fit('When Address is not having any entry, the address field should be marked as Invalid', () =&gt; {
        component.basicBookFormGroup.patchValue({
            bookName: 'My Site Name',
            bookOrg: 'Organization',
            bookAddress: '',
        });
        fixture.detectChanges();
        const addressField: DebugElement = fixture.debugElement.query(By.css('#bookAddressTxtArea'));
        expect(addressField.nativeElement.Invalid).toBeTruthy();
    });
</code></pre>

<p>In the HTML address field is marked as required, so I am expecting the Invalid property should be true for the above. </p>

<pre><code>&lt;mat-form-field appearance=""outline"" class=""full-width-input""&gt;
            &lt;mat-label&gt;{{translate.address}}&lt;/mat-label&gt;
            &lt;textarea id=""bookAddressTxtArea"" autocomplete=""off"" matInput placeholder=""{{translate.address}}"" formControlName=""bookAddress""
                required&gt;&lt;/textarea&gt;
        &lt;/mat-form-field&gt;
</code></pre>

<p>However I get the following error :</p>

<pre><code>Error: No value accessor for form control with unspecified name attribute
            at _throwError (node_modules/@angular/forms/fesm5/forms.js:2094:1)
            at setUpControl (node_modules/@angular/forms/fesm5/forms.js:2004:1)
            at FormControlDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormControlDirective.ngOnChanges (node_modules/@angular/forms/fesm5/forms.js:4951:1)
            at checkAndUpdateDirectiveInline (node_modules/@angular/core/fesm5/core.js:20661:1)
            at checkAndUpdateNodeInline (node_modules/@angular/core/fesm5/core.js:21929:1)
            at checkAndUpdateNode (node_modules/@angular/core/fesm5/core.js:21891:1)
            at debugCheckAndUpdateNode (node_modules/@angular/core/fesm5/core.js:22525:1)
            at debugCheckDirectivesFn (node_modules/@angular/core/fesm5/core.js:22485:1)
</code></pre>

<p>I tried adding name property to address field , no luck</p>
",https://stackoverflow.com/questions/56808394/karma-unit-testing-for-angular-forms-gives-the-error,"['angular', 'karma-jasmine']",331,True,0,1
Way to get rid of null from unit testing,"<p>I'm getting NPE with <code>url</code> variable in method when trying to concat this url (which is resolved as a null with <code>givenTitle</code>). </p>

<pre><code>package bookstore.scraper.book.booksource.empik;

import bookstore.scraper.book.Book;
import bookstore.scraper.book.booksource.BookServiceSource;
import bookstore.scraper.enums.Bookstore;
import bookstore.scraper.enums.CategoryType;
import bookstore.scraper.urlproperties.EmpikUrlProperties;
import bookstore.scraper.utilities.JSoupConnector;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.IntStream;

@Service
public class EmpikSource implements BookServiceSource {

    private static final int FIRST_PART_PRICE = 0;
    private static final int SECOND_PART_PRICE = 1;

    private static final int BESTSELLERS_NUMBER_TO_FETCH = 5;
    private static final int CATEGORIZED_BOOKS_NUMBER_TO_FETCH = 15;
    private static final String DIV_PRODUCT_WRAPPER = ""div.productWrapper"";
    private static final String DATA_PRODUCT_ID = ""data-product-id"";

    private final EmpikUrlProperties empikUrlProperties;
    private final JSoupConnector jSoupConnector;
    private Map&lt;CategoryType, String&gt; categoryToEmpikURL;

    @Autowired
    public EmpikSource(EmpikUrlProperties empikUrlProperties, JSoupConnector jSoupConnector) {
        this.empikUrlProperties = empikUrlProperties;
        this.jSoupConnector = jSoupConnector;
        categoryToEmpikURL = createCategoryToEmpikURLMap();
    }

    @Override
    public Bookstore getName() {
        return Bookstore.EMPIK;
    }


    @Override
    public Book getMostPreciseBook(String givenTitle) {
        String concatedUrl = concatUrlWithTitle(categoryToEmpikURL.get(CategoryType.MOST_PRECISE_BOOK), givenTitle);

        Document document = jSoupConnector.connect(concatedUrl);

        String author = document.select(""div.smartAuthorWrapper.ta-product-smartauthor"").select(""a"").first().text();
        String price = convertEmpikPriceWithPossibleDiscountToActualPrice(document.select(""div.price.ta-price-tile"").first().text());
        String title = document.select(DIV_PRODUCT_WRAPPER).select(""strong"").first().text();
        String productID = document.select(DIV_PRODUCT_WRAPPER).select(""a"").first().attr(DATA_PRODUCT_ID);
        String bookUrl = createBookURL(title, productID);

        return Book.builder()
                .author(author)
                .price(price)
                .title(title)
                .productID(productID)
                .bookURL(bookUrl).build();
    }

    private String concatUrlWithTitle(String url, String title) {
        return String.format(url, title);
    }
private Map&lt;CategoryType, String&gt; createCategoryToEmpikURLMap() {
        Map&lt;CategoryType, String&gt; map = new EnumMap&lt;&gt;(CategoryType.class);

        map.put(CategoryType.CRIME, empikUrlProperties.getCrime());
        map.put(CategoryType.BESTSELLER, empikUrlProperties.getBestSellers());
        map.put(CategoryType.BIOGRAPHY, empikUrlProperties.getBiographies());
        map.put(CategoryType.FANTASY, empikUrlProperties.getFantasy());
        map.put(CategoryType.GUIDES, empikUrlProperties.getGuides());
        map.put(CategoryType.MOST_PRECISE_BOOK, empikUrlProperties.getMostPreciseBook());
        map.put(CategoryType.ROMANCES, empikUrlProperties.getRomances());

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

<p>Test:</p>

<pre><code>package bookstore.scraper.book.booksource.empik;

import bookstore.scraper.book.Book;
import bookstore.scraper.enums.CategoryType;
import bookstore.scraper.urlproperties.EmpikUrlProperties;
import bookstore.scraper.utilities.JSoupConnector;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

import static bookstore.scraper.dataprovider.EmpikBookProvider.prepare15CrimeBooks;
import static bookstore.scraper.dataprovider.EmpikBookProvider.prepareMostPreciseBook;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class EmpikSourceTest {

    @Mock
    JSoupConnector jSoupConnector;
    @Mock
    EmpikUrlProperties empikUrlProperties;

    @InjectMocks
    EmpikSource empikSource;

    /*@Before
    public void setUp() {
        when(empikUrlProperties.getConcreteBook()).thenReturn(anyString());
    }
*/

    @Test
    public void getMostPreciseBook() throws IOException {
        File in = getFile(""/empik/MostPreciseBookEmpik.html"");
        Document empikDocument = Jsoup.parse(in, ""UTF-8"");

        when(jSoupConnector.connect(any())).thenReturn(empikDocument);
        when(empikUrlProperties.getConcreteBook()).thenReturn(""https://www.empik.com/%s,%s,ksiazka-p"");

        Book actualBooks = empikSource.getMostPreciseBook(""W pustyni i w puszczy. Lektura z opracowaniem - Henryk Sienkiewicz"");
        Book expectedBooks = prepareMostPreciseBook();

        assertEquals(expectedBooks, actualBooks);
    }

    private File getFile(String resourceName) {
        try {
            return new File(EmpikSourceTest.class.getResource(resourceName).toURI());
        } catch (URISyntaxException e) {
            throw new IllegalStateException(e);
        }
    }

}
</code></pre>

<p>What should I do not to have url as a null?</p>

<p>Stacktrace:</p>

<pre><code>java.lang.NullPointerException
    at java.base/java.util.regex.Matcher.getTextLength(Matcher.java:1769)
    at java.base/java.util.regex.Matcher.reset(Matcher.java:416)
    at java.base/java.util.regex.Matcher.&lt;init&gt;(Matcher.java:253)
    at java.base/java.util.regex.Pattern.matcher(Pattern.java:1130)
    at java.base/java.util.Formatter.parse(Formatter.java:2698)
    at java.base/java.util.Formatter.format(Formatter.java:2653)
    at java.base/java.util.Formatter.format(Formatter.java:2607)
    at java.base/java.lang.String.format(String.java:2734)
    at bookstore.scraper.book.booksource.empik.EmpikSource.concatUrlWithTitle(EmpikSource.java:154)
    at bookstore.scraper.book.booksource.empik.EmpikSource.getMostPreciseBook(EmpikSource.java:74)
    at bookstore.scraper.book.booksource.empik.EmpikSourceTest.getMostPreciseBook(EmpikSourceTest.java:66)
</code></pre>

<p>EmpikUrlProperties:</p>

<pre><code>package bookstore.scraper.urlproperties;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Getter
@Setter
@Component
@ConfigurationProperties(""external.library.url.empik"")
public class EmpikUrlProperties {

    private String mostPreciseBook;
    private String bestSellers;
    private String concreteBook;
    private String romances;
    private String biographies;
    private String crime;
    private String guides;
    private String fantasy;
}
</code></pre>
",https://stackoverflow.com/questions/57441016/way-to-get-rid-of-null-from-unit-testing,"['java', 'unit-testing', 'mockito']",97,True,0,1
Stubbing is not covering my method in unit testing,"<p>I am trying to implementing unit testing by using the stubbing methodology. 
However, when I stub the method, there is no line coverage of the tested class. </p>

<p>Service Class</p>

<pre><code>@Service
@Slf4j
public class Service {

    @Autowired
    private Client client;

    private String doclinkUrl = ""www.website.com""

    public byte[] downloadContent(String objectId) {
        String url = doclinkUrl + ""documents/"" +objectId + ""/binary"";
        return client.target(url).request().get(byte[].class);
    }
}
</code></pre>

<p>Stubbed Service Class</p>

<pre><code>public class ServiceStub extends Service {

    @Override
    public byte[] downloadContent(String objectId) {
        return ""test"".getBytes();
    }

}
</code></pre>

<p>Testing Service Class</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @InjectMocks
    private Service testee;

    @Test
    public void testDownloadContent(){
        testee = new ServiceStub();
        Assert.assertNotNull(testee.downloadContent(""objectId""));
    }

}
</code></pre>
",https://stackoverflow.com/questions/55049258/stubbing-is-not-covering-my-method-in-unit-testing,"['java', 'unit-testing', 'junit', 'mockito', 'stubbing']",1056,True,0,2
RxJava unit testing - Observable not emitting events in tests,"<p>I'm testing a view model which has the following definition:</p>

<pre><code>class PostViewModel(private val postApi: PostApi): ViewModel() {

    private val _post: PublishSubject&lt;Post&gt; = PublishSubject.create()
    val postAuthor: Observable&lt;String&gt; = _post.map { it.author }

    fun refresh(): Completable {
        return postApi.getPost() // returns Single&lt;Post&gt;
            .doOnSuccess {
                _post.onNext(it)
            }
            .ignoreElement()
        }
    }
}
</code></pre>

<p>My fragment then displays the post author by subscribing to <code>viewModel.postAuthor</code> in its <code>onActivityCreated</code> and calling and subscribing to <code>refresh()</code> whenever the user wants an updated post and everything is fine and dandy.</p>

<p>The issue I'm running into is trying to verify this behaviour in a unit test: specifically, I am unable to get <code>postAuthor</code> to emit an event in my testing environment.</p>

<p>My test is defined as follows:</p>

<pre><code>
    @Test
        fun `When view model is successfully refreshed, display postAuthor`() {


        val post = Post(...)


        whenever(mockPostApi.getPost().thenReturn(Single.just(post))
            viewModel.refresh()
                .andThen(viewModel.postAuthor)
                .test()
                .assertValue { it == ""George Orwell"" }
        }

</code></pre>

<p>The test fails due to no values or errors being emitted, even though I can verify through the debugger that the mock does in-fact return the <code>Post</code> as expected. Is there something obvious that I'm missing, or am I completely wrong in my testing approach?</p>
",https://stackoverflow.com/questions/55402415/rxjava-unit-testing-observable-not-emitting-events-in-tests,"['android', 'kotlin', 'junit', 'rx-java', 'rx-java2']",2519,True,0,2
Please help understand the use case of unit testing,"<p>I have 2 scripts.</p>

<ol>
<li><p>It runs a load test using locust, collects the output in dict format, then pass it to the 2nd script.</p></li>
<li><p>2nd script will accept a dict as input from script-1, parses it, creates a json payload and sends the data to an api endpoint where it stores in some db. </p></li>
</ol>

<p>The application starts running from the 1st script and all the functionalities are working well. I have never worked on a unit testing. My question here is:
What can be tested here using unit testing in order to keep proper standard of building an application.</p>

<p>script-1. (suppose locust is running in already)</p>

<pre><code>def on_slave_report(data):
    send_to_db(data)

events.slave_report += on_slave_report
</code></pre>

<p>script-2.</p>

<pre><code>def send_to_db(data):
     send_it(take_only_needed(data))

def take_only_needed(data):
     needed=data[stats]
     payload = json.dumps({'stats' : needed, 'bla': bla})
     return payload

def send_it(payload):
     requests.request(""POST"", url, data=payload, headers=headers)
</code></pre>
",https://stackoverflow.com/questions/57093624/please-help-understand-the-use-case-of-unit-testing,"['python', 'unit-testing']",50,False,0,1
Angular 5 unit testing failing even with module imports,"<p>After running <code>ng test</code>, my Angular 5 app keeps returning errors like</p>

<pre><code>Can't bind to 'routerLink' since it isn't a known property of 'button'.
</code></pre>

<p>and</p>

<pre><code>Can't bind to 'ngModel' since it isn't a known property of 'select'.
</code></pre>

<p>It was generated by Angular-CLI.</p>

<p>Going in to my <code>app.component.spec.ts</code> file...</p>

<pre><code>import { RouterTestingModule } from '@angular/router/testing'
import { AppComponent } from './app.component'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { UserService } from './user-account/user.service'

describe('AppComponent', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FormsModule,
        ReactiveFormsModule
      ],
      declarations: [
        AppComponent
      ],
      providers: [
        UserService
      ]
    })
    TestBed.compileComponents()
  })

  it('should create the app', async(() =&gt; {
    const fixture = TestBed.createComponent(AppComponent)
    const app = fixture.debugElement.componentInstance
    expect(app).toBeTruthy()
  }))

  it(`should have as title 'app works!'`, async(() =&gt; {
    const fixture = TestBed.createComponent(AppComponent)
    const app = fixture.debugElement.componentInstance
    expect(app.title).toEqual('app works!')
  }))

  it('should render title in a h1 tag', async(() =&gt; {
    const fixture = TestBed.createComponent(AppComponent)
    fixture.detectChanges()
    const compiled = fixture.debugElement.nativeElement
    expect(compiled.querySelector('h1').textContent).toContain('app works!')
  }))
})
</code></pre>

<p>Since I'm importing the <code>FormsModule</code> and <code>RouterTestingModule</code>, I shouldn't be seeing these errors, right? I've closed and re-ran the test after saving but that has not fixed it either.</p>
",https://stackoverflow.com/questions/55815452/angular-5-unit-testing-failing-even-with-module-imports,"['angular', 'karma-jasmine']",69,False,0,0
How to reset dynamodb local data for unit testing,"<p>using Jest, DynamoDB Local, I wanna reset database for each test so it doesn't have to be in specific order.
Is there any way to do that wisely?</p>

<pre><code>beforeEach(() =&gt; {
 resetDB()
})

it('create a data', () =&gt; {

})

it('remove the data', () =&gt; {

})

it('find the data', () =&gt; {
 test should pass but it fails because the data is removed.
})
</code></pre>
",https://stackoverflow.com/questions/57351246/how-to-reset-dynamodb-local-data-for-unit-testing,"['jestjs', 'serverless', 'amazon-dynamodb-local']",2231,False,0,1
Unit testing save methods when return type is void,"<p>Is there any way to write unit tests for save methods in DAO layer when return type is void?  I'm using Log4j, Junit in spring boot project. </p>

<p>I've tried many ways to assert them. But since they aren't returning any value i wasn't able to assert them. </p>
",https://stackoverflow.com/questions/56567759/unit-testing-save-methods-when-return-type-is-void,"['java', 'junit5', 'spring-boot-test']",4751,True,-1,4
Unit testing a textfield using Formik with Jest / Enzyme,"<p>I am totally lost with unit testing a change in a textfield. I'm using jest + enzyme to change the textfield but policyEffectiveField.props().value is always null.</p>

<p>I've tried to simulate but using 'change' and 'click' from the <a href=""https://github.com/jaredpalmer/formik/blob/f5d76609b222ce583663add279ac76e807e2d0ba/README.md#testing-formik"" rel=""nofollow noreferrer"">formik doc</a>.</p>

<pre><code>policyEffectiveField.simulate('change', {
    // you must add this next line as (Formik calls e.persist() internally)
    persist: () =&gt; {},
    // simulate changing e.target.name and e.target.value
    target: {
      name: 'policyEffectiveDate',
      value: ""07/30/2019"",
    },
  });
  expect(policyEffectiveField.props().value).toEqual(now);
</code></pre>

<p>But policyEffectiveField.props().value is null</p>

<pre><code>it('change policyEffectiveDate textfield ', () =&gt; {
  let now = moment().format('L');
  var mountRTI = mount(&lt;TestRTI forms={[policyEffectiveDate]} /&gt;);
  var policyEffectiveField = mountRTI.find(TextField).find('input').find({ name: 'policyEffectiveDate' });
  policyEffectiveField.simulate('change', {
    // you must add this next line as (Formik calls e.persist() internally)
    persist: () =&gt; {},
    // simulate changing e.target.name and e.target.value
    target: {
      name: 'policyEffectiveDate',
      value: ""07/29/2019"",
    },
  });
  expect(policyEffectiveField.props().value).toEqual(now);
});
</code></pre>

<p>I expected expect(policyEffectiveField.props().value).toEqual(now); to be true, but I am getting the below error</p>

<pre><code>change policyEffectiveDate textfield

expect(received).toEqual(expected) // deep equality

Expected: ""07/30/2019""
Received: undefined

  48 |     },
  49 |   });
&gt; 50 |   expect(policyEffectiveField.props().value).toEqual(now);
</code></pre>
",https://stackoverflow.com/questions/57278710/unit-testing-a-textfield-using-formik-with-jest-enzyme,"['javascript', 'reactjs', 'jestjs', 'enzyme', 'formik']",1674,False,0,1
Angular unit testing multiple getters on a singular service,"<p>So I'm trying to test the calls that <em>component x</em> make to it's injected service, the service it self has a couple of methods, and rxjs BehaviourSubject getters/setters. </p>

<p>Currently testing one getter like so.</p>

<pre><code>let component: EditFeatureComponent;
  let fixture: ComponentFixture&lt;EditFeatureComponent&gt;;
  let vectorLayerSubject = new BehaviorSubject&lt;any&gt;({});
  let mockAnnoService = { getLayerToEdit: vectorLayerSubject.asObservable() };
  let mockFeatureService = jasmine.createSpyObj(['getFeatureToEdit', 'setFeatureToEdit']);

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [EditFeatureComponent, CoreMapComponent, MapsComponent],
      imports: [FormsModule, HttpClientModule],
      providers: [
        { provide: AnnotationService, useValue: mockAnnoService},
        { provide: FeatureStyleService, useValue: mockFeatureService}
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    // Fields required for the component
    layer = {
      layerName: 'testLayer',
      ol_uid: 1
    }
    // Create the testbed
    fixture = TestBed.createComponent(EditFeatureComponent);
    component = fixture.componentInstance;
  });

  it('Should return a layer object and have a ol_uid of 1', fakeAsync(()=&gt;{
    vectorLayerSubject.next(layer);
    component.ngOnInit();
    expect(component.layer).toBe(layer);
  }))
</code></pre>

<p>And this works fine passes and covers code coverage, but how do I go about testing the other getter calls on the service and methods, as I can't have more than one mockValue assigned to a service.</p>

<p>Normally I would just create spyObj for the methods, but I can't seem to assign more than useValue to the service or store all the getters/methods in one variable.</p>

<p>I should also note that services are private and readonly on the component.</p>
",https://stackoverflow.com/questions/54389548/angular-unit-testing-multiple-getters-on-a-singular-service,"['angular', 'testing', 'jasmine', 'angular6', 'karma-jasmine']",496,False,0,0
Mock multiple level arrays in java for unit testing,"<p>Hypothetically I have </p>

<pre><code>class Box{
   Item[] items;
}

class Item{
   Toy[] toys;
}

class Toy{
   Color[] colors;
}
</code></pre>

<p>The method is to test if the Box has green color toy;</p>

<pre><code>public bool testHasColor(Box){
   //There will be code here that
   //Streams over each type till we get to color
   // Final point is
   if(color==Color.GREEN){
    return true;
   }
}
</code></pre>

<p>BoxText.class</p>

<pre><code>public void testBoxHasColorGreenMethod(){
    // Need mocking here
}
</code></pre>

<p>What the best way to mock this Box class for the test case?</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/54461361/mock-multiple-level-arrays-in-java-for-unit-testing,"['java', 'arrays', 'unit-testing', 'testing', 'mockito']",141,True,0,1
Generated test fails when unit testing component inside the library,"<p>My project was created using nx schematics, and I'm having some components inside libraries that I want to unit test using jest.js. Every test fails with following errors:</p>

<pre><code>● MyComponent › should create

    Failed: ""Zone is needed for the async() test helper but could not be found. Please make sure that your environment includes zone.js/dist/zone.js""

       7 |   let fixture: ComponentFixture&lt;MyComponent&gt;;
       8 | 
    &gt;  9 |   beforeEach(async(() =&gt; {
         |   ^
      10 |     TestBed.configureTestingModule({
      11 |       declarations: [ MyComponent ]
      12 |     })

      at Env.beforeEach (node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:41:24)
      at Suite.&lt;anonymous&gt; (libs/componentlib/src/lib/components/my-component/my-component.component.spec.ts:9:3)
      at Object.&lt;anonymous&gt; (libs/componentlib/src/lib/components/my-component/my-component.component.spec.ts:5:1)

  ● MyComponent › should create

    TypeError: Cannot read property 'getComponentFromError' of null

      at TestBedViewEngine._initIfNeeded (../../packages/core/testing/src/test_bed.ts:393:46)
      at TestBedViewEngine.createComponent (../../packages/core/testing/src/test_bed.ts:594:10)
      at Function.TestBedViewEngine.createComponent (../../packages/core/testing/src/test_bed.ts:247:36)
      at Object.&lt;anonymous&gt; (libs/componentlib/src/lib/components/my-component/my-component.component.spec.ts:17:23)

  ● MyComponent › should create

    expect(received).toBeTruthy()

    Received: undefined

      21 | 
      22 |   it('should create', () =&gt; {
    &gt; 23 |     expect(component).toBeTruthy();
         |                       ^
      24 |   });
      25 | });
      26 | 

      at Object.&lt;anonymous&gt; (libs/componentlib/src/lib/components/my-component/my-component.component.spec.ts:23:23)
</code></pre>

<p>I've tried already to import zone.js in spec files, importing modules, removing async, reseting the test environment before each test, but everything fails with some different error. I should mention also that I'm using clarity components from vmware.</p>

<p>Here's the .spec file:</p>

<pre class=""lang-js prettyprint-override""><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { MyComponent } from './my-component.component';

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ]
    })
    .compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>I was expecting that this should work like intended when using nx. What am I missing here?</p>
",https://stackoverflow.com/questions/55374934/generated-test-fails-when-unit-testing-component-inside-the-library,"['angular', 'typescript', 'unit-testing', 'jestjs', 'nrwl']",5823,True,5,3
Django unit testing: AttributeError: &#39;WSGIRequest&#39; object has no attribute &#39;user&#39;,"<p>When running the tests i get outputted following error:</p>

<p>user = self.request.user
AttributeError: 'WSGIRequest' object has no attribute 'user'</p>

<p>I have tried switching from <code>MIDDLEWARE</code> to <code>MIDDLEWARE_CLASSES</code> and vice versa. Currently, I'm running Django 2.1.</p>

<p>Also, I have tried switching middleware positions and it didn't help.</p>

<h1>settings.py</h1>

<pre><code>MIDDLEWARE = (
    ""django.contrib.sessions.middleware.SessionMiddleware"",
    ""django.middleware.common.CommonMiddleware"",
    ""django.middleware.csrf.CsrfViewMiddleware"",
    ""django.contrib.auth.middleware.AuthenticationMiddleware"",
    ""django.contrib.auth.middleware.SessionAuthenticationMiddleware"",
    ""django.contrib.messages.middleware.MessageMiddleware"",
    ""django.middleware.clickjacking.XFrameOptionsMiddleware"",
    ""django.middleware.security.SecurityMiddleware"",
    ""whitenoise.middleware.WhiteNoiseMiddleware"",  # to serve static files
)
</code></pre>

<h1>test_views.py</h1>

<pre><code>from django.test import (TestCase,
                     RequestFactory
                     )
from mixer.backend.django import mixer

from .. import views
from accounts.models import User


class TestHomeView(TestCase):
    def test_anonymous(self):
        req = RequestFactory().get(""/"")
        resp = views.HomeView.as_view()(req)
        self.assertEquals(resp.status_code, 200,
                          ""Should be callable by anyone"")

    def test_auth_user(self):
        req = RequestFactory().get(""/"")
        req.user = mixer.blend(""accounts.User"")
        resp = views.HomeView.as_view()(req)
        self.assertTrue(""dashboard"" in resp.url,
                        ""Should redirect authenticated user to /dashboard/"")
</code></pre>

<h1>error output</h1>

<p>user = self.request.user
AttributeError: 'WSGIRequest' object has no attribute 'user'</p>
",https://stackoverflow.com/questions/54183451/django-unit-testing-attributeerror-wsgirequest-object-has-no-attribute-user,['django-testing'],3552,True,5,1
Angular 7 unit testing dependency injection not working in ngOnInit,"<p>I am using Angular 7 with and Angular CLI version 7.3.4.  I am unit testing a component with 2 service injections all important code is included below. I included the stub which is causing errors, the spec file, and the important part of the component in question. Despite this, I am still getting this error ""TypeError: this.spreading.getSpreadingDays is not a function"" I am aware that fixture.detectchanges() is what causes ngOnInit to be called, but the function should be defined since I injected the service.  I am sure it is a silly error, but I have looked at a number of tutorials and I cannot figure out what is wrong with my code. Any suggestions would be appreciated.</p>

<p>Spec file</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { SpreadSignUpComponent } from './spread-sign-up.component';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { AuthService } from 'src/app/core/services/auth.service';
import { SpreadingService } from 'src/app/core/services/spreading.service';
import { AuthServiceStub } from 'src/app/core/testing/auth.service.stub';
import { SpreadingServiceStub } from 'src/app/core/testing/spreading.service.stub';

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

  let authService: AuthService;
  let spreadingService: SpreadingService;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        { provide: AuthService, useValue: AuthServiceStub },
        { provide: SpreadingService, useValue: SpreadingServiceStub }
      ],
      declarations: [ SpreadSignUpComponent ],
      schemas: [ NO_ERRORS_SCHEMA ],
    })
    .compileComponents();

    authService = TestBed.get(AuthService);
    spreadingService = TestBed.get(SpreadingService);
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>stub class:</p>

<pre><code>import { SpreadingService } from '../services/spreading.service';
import { of } from 'rxjs';
import { SpreadingDay } from 'src/app/shared/models/spreadingDay';
import { I } from 'src/app/shared/testing/interfaceBuilder';

export class SpreadingServiceStub implements I&lt;SpreadingService&gt; {

  getSpreadingDays() {
    return of([]);
  }

  getSpreadingDaysForUser() {
    return of([]);
  }

  setSpreadingDay(
    spreadingDay: SpreadingDay
  ) {
    return &lt;Promise&lt;void&gt;&gt;{};
  }

  addVolunteerToDay(
    spreadingDay: SpreadingDay,
    userID: string,
  ) {
    return &lt;Promise&lt;void&gt;&gt;{};
  }

  removeVolunteerFromDay(
    spreadingDay: SpreadingDay,
    userID: string,
  ) {
    return &lt;Promise&lt;void&gt;&gt;{};
  }

  addRequestToDay(
    spreadingDay: SpreadingDay,
    userID: string,
    first: string,
    last: string,
  ) {
    return &lt;Promise&lt;void&gt;&gt;{};
  }
}
</code></pre>

<p>component:</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { SpreadingService } from 'src/app/core/services/spreading.service';
import { SpreadingDayReturn, SpreadingDay } from 'src/app/shared/models/spreadingDay';
import { Observable } from 'rxjs';
import { AuthService } from 'src/app/core/services/auth.service';

@Component({
  selector: 'app-spread-sign-up',
  templateUrl: './spread-sign-up.component.html',
  styleUrls: ['./spread-sign-up.component.scss']
})
export class SpreadSignUpComponent implements OnInit {

  spreadingDays$: Observable&lt;SpreadingDayReturn[]&gt;;

  constructor(
    private auth: AuthService,
    private spreading: SpreadingService,
  ) { }

  ngOnInit() {
    this.spreadingDays$ = this.spreading.getSpreadingDays();
  }
</code></pre>
",https://stackoverflow.com/questions/55270100/angular-7-unit-testing-dependency-injection-not-working-in-ngoninit,"['angular', 'typescript', 'unit-testing', 'dependency-injection', 'ngoninit']",3278,True,4,1
Getting asserting the value None error when unit testing with Pytest,"<p>I'm trying to do a very simple assertion of equality of my expected dataframe output to the result dataframe once the test data is run through the test function. However, instead of comparing if they're are the same, I'm getting None. </p>

<p>I don't have this issue with any of my other tests that use dataframes. I also can print out the dataframe for both the expected AND the result so I know they both exists. Finally, I can even run full production data through the function and it comes out as expected. </p>

<p>I figure I'm missing something but I'm not sure what. I haven't really tried anything other than playing around with it. I assume it's something to do with how dataframes are structured. </p>

<h2>FUNCTIONS</h2>

<pre><code>def get_valid_postal_code(postal_code):
    valid_pc = len(postal_code) == 6 and postal_code[0:5:2].isalpha() and postal_code[1:6:2].isnumeric()
    return valid_pc

def clean_postal_codes(sales):
    sales = sales.dropna(subset=['Postal_Code']).copy()
    sales['Postal_Code'] = sales['Postal_Code'].str.replace("" "", """")
    sales = sales[sales['Postal_Code'].apply(get_valid_postal_code)]
    sales['Postal_Code'] = [x.upper() for x in sales['Postal_Code']]
    return sales
</code></pre>

<h2>TEST FUNCTION</h2>

<pre><code>def test_clean_postal_codes():
    test_data = pd.DataFrame(
        [[344, 'a0a 0a0', 3000], [344, 'a0a 0a0', -2000], [484, 'A0A 0a0', 1000], [494, 'A0a 0A0', 1000],
         [700, 'A0A0A0', 1000], [900, 'A0A0A0', 1000], [50, 'Not null', 2352], [600, 'asdffa', 23523],
         [634, '3HN3H3', 8839], [32, '3523', 238], [432, 'M5N22H', 2352]],
        columns=['Store_Num', 'Postal_Code', 'Sales']
    )
    expected = pd.DataFrame([[344, 'A0A0A0', 3000], [344, 'A0A0A0', -2000], [484, 'A0A0A0', 1000],
                             [494, 'A0A0A0', 1000], [700, 'A0A0A0', 1000], [900, 'A0A0A0', 1000]],
                            columns=['Store_Num', 'Postal_Code', 'Sales'])

    result = clean_postal_codes(test_data)
    print(expected)  # Is not None
    print(result) # Is also not None 
    assert testing.assert_frame_equal(expected, result) # Getting None
</code></pre>

<p>I keep get the following error <strong>""PytestAssertRewriteWarning: asserting the value None, please use ""assert is None""</strong>. If you run the and print out the expected and result dataframes, you can see that both dataframes exist and are the same. Despite this, the error persists.</p>
",https://stackoverflow.com/questions/57498709/getting-asserting-the-value-none-error-when-unit-testing-with-pytest,"['python-3.x', 'pandas', 'unit-testing', 'pytest']",20221,True,10,1
Unit Testing of methods define inside a class using doctesting,"<p>I need to define:
1. doctests for '<strong>init</strong>' which creates a circle 'c1' with radius 2.5 and checks that accessing attribute 'radius' return 2.5.
2. Define a doc test for 'area' which creates a circle 'c1' with radius 2.5 and checks that it computed area is 19.63.</p>

<p>I have written below mentioned code but not getting the output.
Please suggest.</p>

<pre><code>class Circle:

    def __init__(self, radius):

        """"""
        &gt;&gt;&gt; c1=Circle(2.5).__init__()
        2.5
        """"""
        self.radius = radius

    def area(self):

        """"""
        &gt;&gt;&gt; c1=Circle(2.5).area()
        19.63

        """"""

        return round(math.pi*(self.radius**2),2)
</code></pre>
",https://stackoverflow.com/questions/55482649/unit-testing-of-methods-define-inside-a-class-using-doctesting,"['python', 'python-3.x', 'doctest']",10345,True,4,2
unit testing .net core 2.2 SignalR hub issue with HubContext,"<p>I have a SignalR hub that I wish to unit test. The hub is pretty straightforward except that it includes an IHubContext parameter in the ctor. The issue I'm having is that any attempt to unit test the UpdateData method such that I can verify the DataModel data property gets updated fails on a null reference exception. So far all I can verify is that the method get called.
Is it the case that I have not mocked the HubContext dependency properly?</p>

<p>Can anyone provide details of how to resolve this problem please?</p>

<pre><code>using Microsoft.AspNetCore.SignalR;
using Moq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace Tests
{
    public class DataModel
    {
        public string Name { get; set; }
        public string Job { get; set; }

    }

    public class DataHub : Hub
    {
        private readonly IHubContext&lt;DataHub&gt; _hubContext;

        private DataModel data;

        public DataHub(IHubContext&lt;DataHub&gt; context)
        {
            _hubContext = context;
        }

        public override async Task OnConnectedAsync()
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, ""DataGroup"");
        }

        public void UpdateData(DataModel update)
        {
            data = update;
            _hubContext.Clients.Group(""DataGroup"").SendAsync(""Data"", data);
        }

    }

    public class DataHubTests
    {

        private DataModel update;
        private DataHub hub;

        Mock&lt;IClientProxy&gt; mockClientProxy = new Mock&lt;IClientProxy&gt;();
        Mock&lt;IHubClients&gt; mockClients = new Mock&lt;IHubClients&gt;();
        Mock&lt;IHubContext&lt;DataHub&gt;&gt; mockHubContext = new Mock&lt;IHubContext&lt;DataHub&gt;&gt;();
        Mock&lt;IGroupManager&gt; mockGroups = new Mock&lt;IGroupManager&gt;();

        public DataHubTests()
        {
            SetupData();

            mockClients.Setup(clients =&gt; clients.All).Returns(mockClientProxy.Object);

            CancellationToken cancellationToken = default(CancellationToken);
            mockGroups.Object.AddToGroupAsync(""1234"", ""DataGroup"", cancellationToken);

            mockHubContext.Setup(x =&gt; x.Clients.All).Returns(mockClientProxy.Object);            
            mockHubContext.Setup(groups =&gt; groups.Groups).Returns(mockGroups.Object);

            hub = new DataHub(mockHubContext.Object);


        }

        private void SetupData()
        {
            update = new DataModel();
            update.Name = ""Bob"";
            update.Job = ""Builder"";
        }

        [Fact]
        public void DataHubIsAThing()
        {
            Assert.NotNull(hub);
        }

        [Fact]        
        public void UpdateDataIsCalled()
        {
            // act
            hub.UpdateData(update);
            // assert
            mockClients.Verify(clients =&gt; clients.All, Times.Once);
        }

    }
}
</code></pre>
",https://stackoverflow.com/questions/57577371/unit-testing-net-core-2-2-signalr-hub-issue-with-hubcontext,"['asp.net-core', 'moq', 'xunit', 'signalr-hub']",4718,True,3,2
Python way to mock a TCP socket for unit testing,"<p>My current approach is to mock <code>socket.socket</code>, listen and run my code for one connection, then stop the service.</p>

<p>But <code>socket.socket.accept()</code> is a blocking method.</p>

<p>I tried to simulate <code>socket.socket.accept()</code> by returning a <code>(socket, address)</code> mockup tuple on the first call, then raise a <code>socket.error</code> <code>Exception</code>, so I can break the loop on my app that invokes <code>socket.socket.accept()</code></p>

<p>Oddly enough all my unit tests pass but <code>py.test</code> process remains active (doing what?? The debugger is not helping: It doesn't stop on any breakpoints after the second call that exits the loop as expected...) hogging resources on an endless loop until it crashes the whole system.</p>

<p>So, what's the right approach here?</p>

<p><code>TcpService.py</code>:</p>

<pre><code>import socket
import threading

class TcpService:

    _bind_ip = '127.0.0.1'
    _bind_port = 0
    _max_tcp_conn = 20

    def _handle_client_connection(self):
        pass

    def listen_tcp(self):

        self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._server.bind((self._bind_ip, self._tcp_bind_port))
        self._server.listen(self._max_tcp_conn)

        self._tcp_listen = True

        while self._tcp_listen:
            client_sock, address = self._server.accept() # socket.error is supposed to be raised on the second iteration during the unit test, breaking the loop
            client_handler = threading.Thread(
                target=self._handle_client_connection,
                args=(client_sock, address)
            )
            client_handler.start()
</code></pre>

<p><code>test_TcpService.py</code>:</p>

<pre><code>import unittest
import socket
from time import sleep
import mock
import TcpService

def accept_gen():
    for i in range(1):
        mock_socket = mock.MagicMock(name='socket.socket', spec=socket.socket)
        sleep(1)
        yield (mock_socket, ['0.0.0.0', 1234])
    while True:
        sleep(1) # so I have a chance to kill the process before the OS becomes unresponsive
        yield socket.error()



class test_TcpService(unittest.TestCase):

    @mock.patch('socket.socket', autospec=True)
    def test_listen_tcp(self, mock_socket):
        mocked_socket = mock_socket.return_value
        mocked_socket.accept.side_effect = accept_gen()
        sts = TcpService()
        with self.assertRaises(socket.error):
            sts.listen_tcp()
            mock_socket.assert_called_once() # trivial POC check, final test would be more thorough...
        sts.close_tcp()
</code></pre>
",https://stackoverflow.com/questions/58168673/python-way-to-mock-a-tcp-socket-for-unit-testing,"['python', 'unit-testing', 'sockets', 'mocking']",3816,True,3,1
Unit testing Vue JS component that uses MSAL.js for authentication,"<p>I have a Vue component which uses the <code>created</code> hook to connect to AzureAD and authenticate a user </p>

<p>The code looks like this: </p>

<pre><code>  created () {
    this.loginOnLoad()
  },
  methods: {
    async loginOnLoad () {
      this.authService = new AuthService()
      let user = this.authService.sso()
      if (!user) {
        this.loginFailed = true
        await this.login()
        await this.authService.assignAccessTokenToHeader()
        NotificationsService.successNotification('Logged in successfully')
      } else {
        await this.authService.assignAccessTokenToHeader()
        NotificationsService.successNotification('Welcome Back')
      }
    }
  }
</code></pre>

<p>Now, I'm trying to write unit tests using <code>vue-test-utils</code> and <code>Jest</code>, however, when I run the tests the result is saying that user login is required. This is due to me not having mocked the <code>loginOnLoad</code> method, however, before I do that I'd like to know if actually mocking that method is the right way to go i.e. <code>let loginOnLoad = jest.fn()</code> or that will take away the value of the tests? </p>
",https://stackoverflow.com/questions/58272101/unit-testing-vue-js-component-that-uses-msal-js-for-authentication,"['javascript', 'vue.js', 'jestjs', 'azure-active-directory', 'vue-test-utils']",386,False,3,0
How to Mock a Google API Library with Python 3.7 for Unit Testing,"<p>I'm trying to create a set of Unit Tests to test the Google Client Library for Bigquery. I'm struggling to make a Unittest file which will mock the client and will let me test my inputs. I've provided a simple script with some set functionality to return a list of Tables that belong to the DataSet. </p>

<p>Would somebody show me a sample example of mocking the Google Client Library as the documentation I have found @ <a href=""https://github.com/googleapis/google-cloud-python/blob/master/bigquery/tests/unit/test_client.py"" rel=""noreferrer"">https://github.com/googleapis/google-cloud-python/blob/master/bigquery/tests/unit/test_client.py</a> is not directly interacting with the methods of the code, so I am unable to apply it to my code.</p>

<p>Appreciate any ideas or ways to achieve this, I can't seem to find anywhere on Stack Overflow documenting this problem. </p>

<p>Thanks</p>

<pre class=""lang-py prettyprint-override""><code>from google.cloud import bigquery


def get_dataset():
    client = bigquery.Client.from_service_account_json('some_client_secret.json')

    dataset_id = 'some_project.some_dataset'

    dataset = client.get_dataset(dataset_id)

    full_dataset_id = ""{}.{}"".format(dataset.project, dataset.dataset_id)
    friendly_name = dataset.friendly_name
    print(
        ""Got dataset '{}' with friendly_name '{}'."".format(
            full_dataset_id, friendly_name
        )
    )

    # View dataset properties
    print(""Description: {}"".format(dataset.description))
    print(""Labels:"")
    labels = dataset.labels
    if labels:
        for label, value in labels.items():
            print(""\t{}: {}"".format(label, value))
    else:
        print(""\tDataset has no labels defined."")

    # View tables in dataset
    print(""Tables:"")
    tables = list(client.list_tables(dataset))  # API request(s)
    if tables:
        for table in tables:
            print(""\t{}"".format(table.table_id))
    else:
        print(""\tThis dataset does not contain any tables."")
</code></pre>
",https://stackoverflow.com/questions/57808461/how-to-mock-a-google-api-library-with-python-3-7-for-unit-testing,"['python-3.x', 'unit-testing', 'google-app-engine', 'mocking', 'google-client']",10969,True,21,2
Unable to mock $root.$refs while unit testing Vue component,"<p>I have a component where im using reference of $root in its mounted hook.</p>

<pre><code>//here's mounted of my Vue component
mounted() {
    this.$root.$refs.myRef.show()
}
</code></pre>

<p>here is the test case</p>

<pre><code>it('test mount', () =&gt; {
  shallowMount(myComponent)
})
</code></pre>

<p>But it is not getting the root's reference</p>

<pre><code>//error
Could notresolve show() of undefined
</code></pre>

<p>I've tried to mock $root as well</p>

<pre><code>it('test mount', () =&gt; {
  shallowMount(myComponent, {
    mocks: {
      $root: {
        $refs: {
          myRef: {
            show: jest.fn()
          }
        }
      }
    }
  })
})
</code></pre>

<p>But still, it gives the same error.</p>
",https://stackoverflow.com/questions/56169578/unable-to-mock-root-refs-while-unit-testing-vue-component,"['vue.js', 'jestjs', 'vue-test-utils']",2538,False,3,0
Unit Testing Freemarker templates in SpringBoot - unable to initialize freemarker configuration,"<p>we are using Freemarker for generating the HTML code for the emails our application is going to be sending.</p>

<p>Our usage and configuration is based off of <a href=""https://github.com/hdineth/SpringBoot-freemaker-email-send"" rel=""noreferrer"">https://github.com/hdineth/SpringBoot-freemaker-email-send</a>
Particularly:</p>

<pre><code>package com.example.techmagister.sendingemail.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;

import java.io.IOException;

@Configuration
public class FreemarkerConfig {

    @Bean(name=""emailConfigBean"")
    public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration(ResourceLoader resourceLoader) {
        FreeMarkerConfigurationFactoryBean bean = new FreeMarkerConfigurationFactoryBean();
        bean.setTemplateLoaderPath(""classpath:/templates/"");
        return bean;
    }
}
</code></pre>

<p>However, there is absolutely no information or documentation anywhere, about how to run Unit Tests for this using JUnit 5.</p>

<p>When I added the relevant dependencies</p>

<pre><code>        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;
            &lt;version&gt;${junit.jupiter.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-params&lt;/artifactId&gt;
            &lt;version&gt;${junit.jupiter.version}&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-engine&lt;/artifactId&gt;
            &lt;version&gt;${junit.jupiter.version}&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;${mockito.version}&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-junit-jupiter&lt;/artifactId&gt;
            &lt;version&gt;${mockito.version}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
</code></pre>

<p>versions:</p>

<pre><code>        &lt;junit.jupiter.version&gt;5.3.1&lt;/junit.jupiter.version&gt;
        &lt;mockito.version&gt;2.23.0&lt;/mockito.version&gt;
</code></pre>

<p>And made a test class:</p>

<pre><code>package com.example.techmagister.sendingemail;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.io.IOException;


@ExtendWith({SpringExtension.class, MockitoExtension.class})
@Import(com.example.techmagister.sendingemail.config.FreemarkerConfig.class)
public class EmailTestTest {
    private static final Logger LOGGER = LogManager.getLogger(EmailTestTest.class);

    @Autowired
    @Qualifier(""emailConfigBean"")
    private Configuration emailConfig;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() throws Exception {
        try {
            Template template = emailConfig.getTemplate(""email.ftl"");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
</code></pre>

<p>When I run that in debug mode, <code>emailConfig</code> is null.
Why is that? </p>

<p>Their test example <a href=""https://github.com/hdineth/SpringBoot-freemaker-email-send/blob/master/src/test/java/com/example/techmagister/sendingemail/SendingemailApplicationTests.java"" rel=""noreferrer"">https://github.com/hdineth/SpringBoot-freemaker-email-send/blob/master/src/test/java/com/example/techmagister/sendingemail/SendingemailApplicationTests.java</a>
works if I add the same autowired property, but it is a full SprintBoot context that is slow to boot, and I need to test just template usage, without actually sending out the email.</p>

<p>In our actual code (which is large, multi module project), I have another error <code>org.springframework.beans.factory.UnsatisfiedDependencyException</code>
caused by:</p>

<pre><code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'freemarker.template.Configuration' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=emailConfigBean)}
</code></pre>

<p>But that is just for context, first I want to get it working in the simple, sample project then worry about getting it working in our complex one.</p>
",https://stackoverflow.com/questions/59220213/unit-testing-freemarker-templates-in-springboot-unable-to-initialize-freemarke,"['spring-boot', 'junit', 'freemarker', 'junit5']",4958,True,9,2
How to control randomness for unit testing purposes in Swift?,"<p>I'd like to inject a <code>RandomNumberGenerator</code> to my class in order to write unit tests. However, it seems that the methods that receive a random number generator only work with concrete types.</p>

<p>Which means that </p>

<pre><code>var rng: RandomNumberGenerator = SystemRandomNumberGenerator()
Bool.random(using: &amp;rng)
</code></pre>

<p>does not compile, with the error:</p>

<blockquote>
  <p>In argument type <code>inout RandomNumberGenerator</code>, <code>RandomNumberGenerator</code> does not conform to expected type <code>RandomNumberGenerator</code></p>
</blockquote>

<p>but </p>

<pre><code>var rng = SystemRandomNumberGenerator()
Bool.random(using: &amp;rng)

</code></pre>

<p>does.</p>

<p>The trouble with that is that I'd like to use the default random number generator when running my app, and use a custom random number generator that i control for testing.  What is the general approach to controlling randomness in order to make testable code in Swift?</p>
",https://stackoverflow.com/questions/59520001/how-to-control-randomness-for-unit-testing-purposes-in-swift,['swift'],716,True,3,2
Not able to increase code coverage in Angular Unit testing,"<p>I am trying to learn how to make unit testing for Angular with Karma and Jasmine.</p>

<p>My problem is that I make it with spyOn() and expect.toHaveBeenCalled() and even though Karma says that passed the tests, the Code Coverage is not updated.</p>

<p>I am new to angular unit testing and I dont know how to test methods properly so as to get code coverage.</p>

<p>Thanks everyone for the help.</p>
",https://stackoverflow.com/questions/58129821/not-able-to-increase-code-coverage-in-angular-unit-testing,"['angular', 'unit-testing', 'karma-jasmine', 'karma-coverage']",6754,True,2,2
How to skip Fluent validation static function during unit testing?,"<p>I am using xunit with Moq and testing other functionality in one function but i always get an exception from Fluent Validation extension methods which I can not bypass.</p>

<p>This is original code </p>

<pre><code>    public class AdService : IAdService
{
    private readonly IValidator&lt;AdToSearchDto&gt; _adToSearchDtoValidator;
    public AdService(IValidator&lt;AdToSearchDto&gt; addToSearchDtoValidator)
    {
        _adToSearchDtoValidator = addToSearchDtoValidator
    }

    public async Task&lt;AdsToReturnDto&gt; GetAdsAsync(AdToSearchDto searchDto)
    {
         _adToSearchDtoValidator.ValidateAndThrow(searchDto); // This line always throw exception

          return await _adRepository.GetUserAdsAsync(searchDto, userId, user?.Country);            
    }

}
</code></pre>

<p>Unit test class</p>

<pre><code> [Fact]
public async Task Ads_Can_Searched_By_UserId()
{
    var validator = new Mock&lt;IValidator&lt;AdToSearchDto&gt;&gt;();

    var adService = new AdService(validator.Object);

    var adService = new AdService(validator.Object );

    var ads = DataGenerator.CreateAds(2);
    ads[0].UserId = searchingUserId;
    ads[1].UserId = anotherUserId;

    await adRepository.CreateAdAsync(ads[0]);
    await adRepository.CreateAdAsync(ads[1]);

    var result = await adService.GetAdsAsync( adToSearchDto, Guid.Empty ) ;

    result.Ads.Count.Should().Be(1);
    result.Ads.FirstOrDefault()?.UserId.Should().Be(searchingUserId.ToString());

}
</code></pre>

<p>I cant bypass </p>

<blockquote>
  <p>ValidateAndThrow</p>
</blockquote>

<p>as this is extension method.</p>

<p>Is there any way to bypass ValidateAndThrow method in unit test <strong>?</strong></p>

<p>Edited:</p>

<p>Error i am getting</p>

<pre><code>System.NullReferenceException : Object reference not set to an instance of an object.
   at FluentValidation.DefaultValidatorExtensions.ValidateAndThrow[T](IValidator`1 validator, T instance, String ruleSet) in C:\Projects\FluentValidation\src\FluentValidation\DefaultValidatorExtensions.cs:line 943
   at Market.Business.Ad.AdService.GetAdsAsync(AdToSearchDto searchDto, Guid userId) in C:\Users\Shahid Abdullah\Projects\MyStuff.IdentityServer\src\Market\Market.Business\Ad\AdService.cs:line 129
   at Market.Test.Ad.AdTests.Ads_Can_Searched_By_UserId() in C:\Users\Shahid Abdullah\Projects\MyStuff.IdentityServer\src\Market\Market.Test\Ad\AdTests.cs:line 100
--- End of stack trace from previous location where exception was thrown ---
</code></pre>

<p>Exception in source code</p>

<pre><code>public static void ValidateAndThrow&lt;T&gt;(
      this IValidator&lt;T&gt; validator,
      T instance,
      string ruleSet = null)
    {
      ValidationResult validationResult = validator.Validate&lt;T&gt;(instance, (IValidatorSelector) null, ruleSet);
      if (!validationResult.IsValid) // this line throws exception as validationResult is null
        throw new ValidationException((IEnumerable&lt;ValidationFailure&gt;) validationResult.Errors);
    }
</code></pre>
",https://stackoverflow.com/questions/58450291/how-to-skip-fluent-validation-static-function-during-unit-testing,"['c#', 'unit-testing', '.net-core', 'moq', 'xunit']",1196,True,2,1
"In unit testing, what&#39;s the difference between fixture.debugElement.nativeElement.query and document.getElement?","<p>I'm new to Angular unit tests and was looking at some tests written by others. I see the attempts to access elements three different ways:</p>

<ul>
<li><code>fixture.debugElement.query(By.css('#hello'))</code></li>
<li><code>fixture.debugElement.nativeElement.querySelector('#hello')</code></li>
<li><code>document.getElementById('#hello')</code></li>
</ul>

<p>Is there any difference/best practice for using these?</p>
",https://stackoverflow.com/questions/58965722/in-unit-testing-whats-the-difference-between-fixture-debugelement-nativeelemen,"['html', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",4621,True,2,1
Show error of two strings are equal in unit testing,"<p>I have created a small Laravel project and I am applying unit testing on my project. When I fill wrong credentials in function, it doesn't redirect to the login page and shows error on terminal saying Failed asserting that two strings are equal. Here is my code...</p>

<pre><code>$credentials = [
    'email' =&gt; 'test@gmail.com',
    'password' =&gt; 'wrongcode'
];

$this-&gt;post('/login', $credentials)-&gt;assertRedirect('/login');
</code></pre>

<p>But when i change <code>assertRedirect('/login')</code> to <code>assertRedirect('/')</code> , it works fine</p>

<pre><code>$credentials = [
    'email' =&gt; 'test1234@gmail.com',
    'password' =&gt; '98756412'
];

$this-&gt;post('/login', $credentials)-&gt;assertRedirect('/');
</code></pre>
",https://stackoverflow.com/questions/55468883/show-error-of-two-strings-are-equal-in-unit-testing,"['php', 'laravel', 'unit-testing']",752,True,2,2
slickgrid jquery-ui.sortable module not loaded error in unit-testing,"<p>I am running a unit test with angular-slickgrid and it returns me an error as following</p>

<pre><code>SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded
</code></pre>

<p>I have tried installing <code>jquery-ui</code> and set the columnReorder to <code>true</code> and <code>false</code>. </p>
",https://stackoverflow.com/questions/55529337/slickgrid-jquery-ui-sortable-module-not-loaded-error-in-unit-testing,"['angular', 'typescript', 'unit-testing', 'slickgrid']",689,False,2,0
How can I change the app url for unit testing?,"<p>I have a function which requires the url to be able to work. I am trying to unit test it as its behaviour changes depending on the url query parameters.</p>

<p>MyServiceTest.php</p>

<pre><code>function testMyTestFunction() {
    $service = new MyService();

    // Some how change the url for the app. This doesn't work
    config(['app.url' =&gt; 'http://test.test?myNewParam=5']);

    $service-&gt;test();
}
</code></pre>

<p>MyService.php</p>

<pre><code>function test() {
    // Does not contain `myNewParam`
    $url = url()-&gt;full();

    // do some logic
}
</code></pre>

<p>I've also tried mocking the request as that's what the <code>url()</code> helper function references but I've had no luck in doing this successfully.</p>
",https://stackoverflow.com/questions/56468053/how-can-i-change-the-app-url-for-unit-testing,"['php', 'laravel', 'laravel-5', 'phpunit']",781,True,2,1
Unit Testing Custom iOS Framework with or without Host Application,"<p>I have a custom iOS framework written in Swift that presents AVCaptureVideoPreviewLayer and also presents some custom popup screens. I want to add unit tests and wondering if I can do this without having a host App specified and instead programmatically create a minimal host app.</p>

<p>Some resources I've found that seem to be moving in the direction but were not written with unit testing frameworks in-mind:</p>

<p><a href=""https://marcosantadev.com/fake-appdelegate-unit-testing-swift/"" rel=""nofollow noreferrer"">https://marcosantadev.com/fake-appdelegate-unit-testing-swift/</a></p>

<p><a href=""https://qualitycoding.org/ios-app-delegate-testing/"" rel=""nofollow noreferrer"">https://qualitycoding.org/ios-app-delegate-testing/</a></p>
",https://stackoverflow.com/questions/54030136/unit-testing-custom-ios-framework-with-or-without-host-application,"['swift', 'xcode', 'unit-testing', 'frameworks', 'xctest']",1925,True,2,1
Codeception Unit testing [RuntimeException] Call to undefined method UnitTester::haveRecord,"<p>I am new in Codeception trying to run a sample unit test in my Laravel framework but getting the following error:</p>

<pre><code>[RuntimeException] Call to undefined method UnitTester::haveRecord
</code></pre>

<p>And following code I have tried to run using Codeception:</p>

<pre><code> &lt;?php namespace Article;
 use App\Article;
 use Faker\Factory as Faker;
 use Carbon\Carbon;
 class SaveTest extends \Codeception\Test\Unit
{
/**
 * @var \UnitTester
 */
protected $tester;

protected function _before()
{
}

protected function _after()
{
}

// tests
public function testSomeFeature()
{
    $faker= Faker::create('App/Article');

        $title = $faker-&gt;sentence;
        $content = implode($faker-&gt;paragraphs(5));
        $created_at = Carbon::now();
        $updated_at = Carbon::now();


        $this-&gt;tester-&gt;haveRecord( 'Article',   ['title' =&gt; $title, 'content' =&gt; $content,'created_at' =&gt; $created_at,'updated_at' =&gt; $updated_at]);


         $this-&gt;tester-&gt;seeRecord('articles',['title' =&gt; $title,'content' =&gt; $content,'created_at' =&gt; $created_at,'updated_at' =&gt; $updated_at]);




}
}
</code></pre>

<p>Could please help me out of this error? Thanks in advance.</p>
",https://stackoverflow.com/questions/54288920/codeception-unit-testing-runtimeexception-call-to-undefined-method-unittester,"['php', 'laravel', 'unit-testing', 'laravel-5', 'codeception']",881,True,2,1
Unit Testing AWS python lambda global variable patch doesnt work,"<p>I am trying to unit test Python based aws lambda code. I tried to use patch to mock environment variables but it throws error.How to handle global variables during unit testing. Any help is appreciated</p>

<p>Tried @mock @patch but nothing seems to be working. When executing the testcase the values seems to be empty</p>

<p>[registration.py]</p>

<pre class=""lang-py prettyprint-override""><code>    import os 

    #Global Variables
    DEBUG = os.environ.get(""EnableLog"")
    rest_endpoint = os.environ.get('restApiEndpoint')
    db_fn_endpoint = rest_endpoint+"":3000/rpc/""

    def lambda_handler(event,context):
    return ""success"" #to see if this works

    if __name__ == ""__main__"":
        lambda_handler('', '')
</code></pre>

<p>Unit Test [test_registration.py]</p>

<pre class=""lang-py prettyprint-override""><code>    import json
    import pytest
    import sys, os
    from mock import patch
    from businesslogic import registration

    @mock.patch.dict(os.environ,{'EnableLog':'True'})
    @mock.patch.dict(os.environ,{'restApiEndpoint':'http://localhost'})

    @patch('registration.restApiEndpoint', 'http://localhost') 


    def test_lambda_handler():
       assert lambda_handler() ==""success""

</code></pre>

<p>When I run pytest test_registration.py</p>

<p>I get below exception </p>

<pre><code>businesslogic\registration.py:6: in &lt;module&gt;
    db_fn_endpoint = rest_endpoint+"":3000/rpc/""
E   TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
</code></pre>
",https://stackoverflow.com/questions/57117736/unit-testing-aws-python-lambda-global-variable-patch-doesnt-work,['python'],1410,False,2,1
Unable to do unit testing of retry parameter of AmazonS3Client,"<p>I have build a nifi custom processor.to put a object in AWS s3 bucket.(used AmazonS3Client in AWS SDK)
In  the ClientConfig , i have chnaged the MaxErrorRetry to 4(default AWS gives 3).</p>

<p>testcase Scenario:
I want do a unit testing(using Junit, Mokito) , to test this chnaged retry parameter is working or not.</p>

<p>Means, If i am getting 5**(Errror from server side) error then it will again attemp to upload the file to s3 and it will continue to try 4 times as my configured paramater whihc is 4 times.</p>

<p>I also want another clarification , while uploading the file s3 bucket, if i am giving wrong bucketname(errror related to client side 4**), then it will rerty 4 times or not.</p>

<p>Thanks in advance for help</p>

<pre><code>@Test
    public void testRetryLogin() {
        final TestRunner runner = TestRunners.newTestRunner(new myprocessor);


// need the logiv`enter code here`
        runner.run();
       // will do assert

    }
</code></pre>
",https://stackoverflow.com/questions/58355847/unable-to-do-unit-testing-of-retry-parameter-of-amazons3client,"['java', 'amazon-web-services', 'amazon-s3', 'junit4', 'apache-nifi']",403,False,2,0
Unit testing the onPageStarted and onPageFinished of a WebView&#39;s WebViewClient callbacks,"<pre><code>Android Studio 3.5.1
Kotlin 1.3
</code></pre>

<p>I have the following method that I am trying to unit test. That uses the <code>WebView</code> and <code>WebViewClient</code></p>

<p>The method I have is the following that needs to be unit tested:</p>

<pre><code>fun setPageStatus(webView: WebView?, pageStatus: (PageStatusResult) -&gt; Unit) {
    webView?.webViewClient = object : WebViewClient() {

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            pageStatus(PageStatusResult.PageStarted(url ?: """", favicon))
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            pageStatus(PageStatusResult.PageFinished(url ?: """"))
        }
    }
}
</code></pre>

<p>I takes a webView that overrides some callback from the WebViewClient. And then calls a lambda function in the onPageStarted or onPageFinished.</p>

<p>Uses a sealed class to set the properties that is passed in the lambda method</p>

<pre><code>sealed class PageStatusResult {
    data class PageFinished(val url: String) : PageStatusResult()
    data class PageStarted(val url: String, val favicon: Bitmap?) : PageStatusResult()
}
</code></pre>

<p>In the unit test I have do something like this:</p>

<pre><code>@Test
fun `should set the correct settings of the WebView`() {
    // Arrange the webView
    val webView = WebView(RuntimeEnvironment.application.baseContext)

    // Act by calling the setPageStatus
    webFragment.setPageStatus(webView) { pageStatusResult -&gt;
        when(pageStatusResult) {
            is PageStarted -&gt; {
            // Assert that the url is correct
                assertThat(pageStatusResult.url).isEqualToIgnoringCase(""http://google.com"")
            }
        }
    }

    // Call the onPageStarted on the webViewClient and and assert in the when statement
    webView.webViewClient.onPageStarted(webView, ""http://google.com"", null)
}
</code></pre>
",https://stackoverflow.com/questions/58457110/unit-testing-the-onpagestarted-and-onpagefinished-of-a-webviews-webviewclient-c,"['android', 'unit-testing', 'kotlin', 'android-webview']",1385,True,7,2
How to mock fake url with axios for unit testing?,"<p><strong>Context</strong></p>

<p>The URL in this app is only accessible in production and it is not able to access via local. When doing unit tests, I need to mock the response of that url.</p>

<p><strong>What I got</strong></p>

<p>Follow this <a href=""https://medium.com/@lucaspenzeymoog/mocking-api-requests-with-jest-452ca2a8c7d7"" rel=""nofollow noreferrer"">tutorial</a></p>

<p><strong>Code I have</strong></p>

<p>saga.js</p>

<pre><code>import {all, call, put, takeEvery} from 'redux-saga/effects';
import axios from 'axios';

async function myfetch(endpoint) {
  const out = await axios.get(endpoint);
  return out.data;
}

function* getItems() {
  //const endpoint = 'https://jsonplaceholder.typicode.com/todos/1';
  const endpoint = 'http://sdfds';
  const response = yield call(myfetch, endpoint);
  const items = response;

  //test
  console.log('items', items);

  yield put({type: 'ITEMS_GET_SUCCESS', items: items});
}

export function* getItemsSaga() {
  yield takeEvery('ITEMS_GET', getItems);
}

export default function* rootSaga() {
  yield all([getItemsSaga()]);
}

</code></pre>

<p>You can see that I made endpoint as const <code>endpoint = 'http://sdfds';</code>, which is not accessible.</p>

<p>saga.test.js</p>

<pre><code>// Follow this tutorial: https://medium.com/@lucaspenzeymoog/mocking-api-requests-with-jest-452ca2a8c7d7
import SagaTester from 'redux-saga-tester';
import mockAxios from 'axios';
import reducer from '../reducer';
import {getItemsSaga} from '../saga';

const initialState = {
  reducer: {
    loading: true,
    items: []
  }
};

const options = {onError: console.error.bind(console)};

describe('Saga', () =&gt; {
  beforeEach(() =&gt; {
    mockAxios.get.mockImplementationOnce(() =&gt; Promise.resolve({key: 'val'}));
  });

  afterEach(() =&gt; {
    jest.clearAllMocks();
  });

  it('Showcases the tester API', async () =&gt; {
    const sagaTester = new SagaTester({
      initialState,
      reducers: {reducer: reducer},
      middlewares: [],
      options
    });

    sagaTester.start(getItemsSaga);

    sagaTester.dispatch({type: 'ITEMS_GET'});

    await sagaTester.waitFor('ITEMS_GET_SUCCESS');

    expect(sagaTester.getState()).toEqual({key: 'val'});
  });
});

</code></pre>

<p>axios.js</p>

<pre><code>const axios = {
  get: jest.fn(() =&gt; Promise.resolve({data: {}}))
};
export default axios;
</code></pre>

<p>I was hopping this will overwrite the default <code>axios</code></p>

<p><a href=""https://github.com/kenpeter/test-saga"" rel=""nofollow noreferrer"">Full code here</a></p>

<p><strong>Summary</strong></p>

<p>Need to overwrite default axios' return response.</p>
",https://stackoverflow.com/questions/59167657/how-to-mock-fake-url-with-axios-for-unit-testing,"['javascript', 'reactjs', 'unit-testing', 'axios']",1952,False,1,1
Unit testing: react context api with enzyme return an empty object,"<p>I am trying for the first time to use React context API to pass information from a main component to a grandchild component.</p>
<p>So first I have created a context</p>
<pre class=""lang-js prettyprint-override""><code>const MyContext = React.createContext({});

export default MyContext;
</code></pre>
<p>Here is the main component that sets the value of the context</p>
<pre class=""lang-js prettyprint-override""><code>import MyContext from &quot;./MyContext.js&quot;;
import ParentComponent from &quot;./ParentComponent.js&quot;;

function App() {
  return (
    &lt;div&gt;
      &lt;MyContext.Provider value={{ foo: 12 }}&gt;
        &lt;ParentComponent /&gt;
      &lt;/MyContext.Provider&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>The parent component doesn't care about the context and is just here to create the grandchild component</p>
<pre class=""lang-js prettyprint-override""><code>import ChildComponent from &quot;./ChildComponent.js&quot;;

class ParentComponent extends Component {
  render() {
    return (
      &lt;div&gt;
        Parent
        &lt;ChildComponent /&gt;
      &lt;/div&gt;
    );
  }
}

export default ParentComponent;
</code></pre>
<p>And here is the child component that reads the context</p>
<pre class=""lang-js prettyprint-override""><code>import MyContext from &quot;./MyContext.js&quot;;

class ChildComponent extends PureComponent {
  constructor() {
    super();
    this.state = {
      bar: 456
    };
  }

  render() {
    return (
      &lt;div&gt;
        &lt;MyContext.Consumer&gt;
          {({ foo }) =&gt; (
            &lt;div&gt;
              &lt;h1&gt;Hello I'm the ChildComponent&lt;/h1&gt;
              &lt;h2&gt;Context value: {foo}&lt;/h2&gt;
              &lt;h2&gt;State value: {this.state.bar}&lt;/h2&gt;
              &lt;button onClick={() =&gt; this.setState({ bar: foo })}&gt;
                Click me
              &lt;/button&gt;
            &lt;/div&gt;
          )}
        &lt;/MyContext.Consumer&gt;
      &lt;/div&gt;
    );
  }
}

export default ChildComponent;
</code></pre>
<p>So far no problem. Everything works as expected. The ChildComponent has retrieved the context value.</p>
<p>The problem comes when I try to test it with jest/enzyme. I can't manage to set the context</p>
<pre class=""lang-js prettyprint-override""><code>it(&quot;Should test the context value&quot;, () =&gt; {
  let wrapper = mount(&lt;ChildComponent /&gt;, {
    context: { foo: 987 }
  });

  expect(wrapper.state(&quot;bar&quot;)).toEqual(456);
  expect(wrapper.context(&quot;foo&quot;)).toEqual(987);
});
</code></pre>
<p>The last expect fails and the context value is an empty object. So foo is undefined</p>
<p>I have recreated the problem here:
<a href=""https://codesandbox.io/embed/x25yop4x5w?fontsize=14"" rel=""nofollow noreferrer"">https://codesandbox.io/embed/x25yop4x5w?fontsize=14</a></p>
<p>Thank you for your help</p>
",https://stackoverflow.com/questions/55730219/unit-testing-react-context-api-with-enzyme-return-an-empty-object,"['reactjs', 'unit-testing', 'jestjs', 'enzyme', 'react-context']",6877,True,7,3
How to fix &quot;SVG Not defined&quot; in JEST unit testing,"<p>I'm trying to setup an unit test case for a function defined in a typescript class.  This class is dependent on svg.js.
Now when I am trying to unit test the function with jest, it throws error
SVG.extend or SVG is not a function.</p>

<p>We have tried ways in jest.config.js file for the testEnvironment to be node to jsdom.</p>

<p>Code for ts is as follows
    import SVG from 'svg.js';</p>

<pre><code>export class DrawManager {
  private static _drawingStage : SVG.Nested|undefined;
  private static _canvas : SVG.Doc|undefined;
}

static start(div: string) {
    this._canvas = SVG(div)
    this._drawingStage = this._canvas.nested();
}
</code></pre>

<p>code for unit testing is as follows</p>

<pre><code>import { DrawManager } from './drawmanager';
describe('Test for Draw Manager', () =&gt; {
    it('should process task loader method', () =&gt; {
    DrawManager.start('drawing');
 });
});
</code></pre>

<p>We are expecting output pass to test case without any SVG dependency problem and run the test case with the initiated svg class</p>

<p>Help would be appreciated</p>
",https://stackoverflow.com/questions/54037495/how-to-fix-svg-not-defined-in-jest-unit-testing,"['typescript', 'unit-testing', 'webpack', 'jestjs', 'svg.js']",2233,True,1,1
Unit testing Boolean method based on other methods return types,"<p>New to unit testing and am looking for a way to unit test a Boolean method that is validated by two other methods results.  </p>

<pre><code> protected boolean isUpdateNeeded(){ 
 return (method1() &amp;&amp; method2()); 
}
</code></pre>

<p>the other methods look like this for this example. </p>

<pre><code>protected boolean method1() { 
 return false; 
}

protected boolean method2() { 
 return true; 
} 
</code></pre>

<p>But these two methods are/can be Overriden if need be. Idk if that really matter at this point</p>

<p>So my thinking behind the test is this. Find a way to pass true/false to method1 or method2 to meet the required possible outcomes.  </p>

<pre><code>@Test
 public void testCheckToSeeIfUpdateIsNeeded(){ 
   assertTrue('how to check here'); 
   asserFalse('how to check here');
   assertIsNull('was null passed?');  

 }
</code></pre>
",https://stackoverflow.com/questions/57999782/unit-testing-boolean-method-based-on-other-methods-return-types,"['java', 'unit-testing', 'junit']",1575,True,1,2
Mocking connection to mySQL database in Node.js for unit-testing,"<p>I am trying to unit-test my Node.js application using Jest and have ran into the problem of trying to mock a mySQL database in memory. If I understand correctly unit-tests must be fast and not hit the database or file system, they also must also be Isolated/Independent.</p>

<p>While testing functions that hit the file system I have used <a href=""https://github.com/tschaub/mock-fs"" rel=""nofollow noreferrer"">mock-fs</a> to mock the fs model and run file read and writes in memory.</p>

<p>The problem I am having with unit-testing functions that hit the database. I am using the <a href=""https://www.npmjs.com/package/mysql"" rel=""nofollow noreferrer"">mySQL</a> module to communicate with a mySQL server. So my question is, is there a way to run a mySQL database in memory ?
I have seen information on using SQLite3 in memory, I have tired mocking the mySQL module and using a SQLite3 database ran in memory as a drop in replacement, however this causes problems because the SQL syntax is different between mySQL and SQLite3.</p>

<p>Any information would be greatly appreciated. </p>
",https://stackoverflow.com/questions/58380071/mocking-connection-to-mysql-database-in-node-js-for-unit-testing,"['mysql', 'node.js', 'sqlite', 'unit-testing', 'mocking']",1541,False,1,0
How to set up unit testing when developing Directus extensions?,"<p>What is a good project setup for developing Directus extensions such as hooks and custom endpoint, while using unit testing with PHPUnit?</p>

<p>Directus extensions live under the same codebase as the core project itself. That's a problem for having the extension code under version control. So what I have now is a symlink from <code>directus/public/extensions/custom/hooks</code> to a directory outside. In there, I have the usual <code>src/</code> and <code>tests/</code>, and I've done <code>composer install --dev phpunit ^8</code> and I PHPUnit is in place, and is loading my own classes. Now, how do I bring Directus in here, because Directus is not, AFAIK, on Composer. Maybe make a <code>lib/</code>, checkout Directus from GitHub in there, and have it included in <code>autoload/classmap</code> in composer.json?</p>

<p>Or would it alternatively be better to fork the whole Directus, and use a close of the whole Directus repo for extension dev? How to develop more than one extension?</p>

<p>Or something else?</p>
",https://stackoverflow.com/questions/58476595/how-to-set-up-unit-testing-when-developing-directus-extensions,"['php', 'unit-testing', 'phpunit', 'directus']",414,False,1,1
Unit Testing: How to return value asynchronously from mocked interface,"<p>I'm trying to unit test a method and assert that the result is of a specific type when calling a mocked 'request provider' which handles HttpClient logic, though I have setup the mocked interface it always returns null.</p>

<p>Previously when using HttpClient I've mocked the HttpMessageHandler and handled the business logic in the method at the other side, however the third party API we are using requires multiple calls to their rest api using GET requests, so I wanted a solution that kept the solution more 'DRY'</p>

<p>The following is the setup I am currently trying to use</p>

<pre><code>_requestProvider.Setup(
    svc =&gt; svc.GetAsync&lt;PlayerBalance&gt;(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;()))
    .Returns(() =&gt; Task.FromResult(new PlayerBalance
    {
        Balance = 0
    }));

_playerService = new PlayerService(_playerRepository.Object, 
            _secretsService.Object,
            _awsConfig,
            _requestProvider.Object);
</code></pre>

<p>My act/assertion</p>

<pre><code>var result = await _playerService.GetPlayerBalanceAsync(request);

result.Should().BeOfType&lt;PlayerBalance&gt;();
</code></pre>

<p>The method under test</p>

<pre><code>public async Task&lt;PlayerBalance&gt; GetPlayerBalanceAsync(PlayerBalanceRequest playerBalanceRequest)
{
    if (string.IsNullOrEmpty(playerBalanceRequest.Login)) throw new Exception(""Login is a required parameter."");


    string url = $@""myrestendpoint"";

    var result = await _requestProvider.GetAsync&lt;List&lt;PlayerBalance&gt;&gt;(url);

    return result.FirstOrDefault();
}
</code></pre>

<p>And where it's failing invocation on the mock</p>

<pre><code>public async Task&lt;TResult&gt; GetAsync&lt;TResult&gt;(string uri, string token = """")
{
    HttpClient httpClient = CreateHttpClient(token);
    HttpResponseMessage response = await httpClient.GetAsync(uri);

    await HandleResponse(response);
    string serialized = await response.Content.ReadAsStringAsync();

    TResult result = await Task.Run(() =&gt;
            JsonConvert.DeserializeObject&lt;TResult&gt;(serialized, _serializerSettings));

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

<p>When running in 'Strict' it is telling me that it expected invocation but no setup was found. I'm not really sure what else needs setting up here. </p>

<p>the result returned from the last slice of code is always null, but I want it to be PlayerBalance { Balance = 0 }</p>

<p>Any help would be appreciated.</p>

<p>Just to clarify I have also tried my setup in the following ways</p>

<pre><code>.Returns(Task.FromResult(new PlayerBalance
{
    Balance = 0
}));

.ReturnsAsync(new PlayerBalance {
    Balance = 0
});
</code></pre>
",https://stackoverflow.com/questions/54364591/unit-testing-how-to-return-value-asynchronously-from-mocked-interface,"['c#', 'unit-testing', 'moq', 'xunit']",314,True,1,1
How can I solve problem with vuex and unit-testing?,"<p>I am trying to write and run unit-testing first time with mocha and faced some problem.
I have a component <code>Table.vue</code> wrote with vuetify</p>

<pre><code>    &lt;v-container&gt;
        &lt;h1&gt;Table&lt;/h1&gt;
        &lt;v-layout
                text-center
                wrap
        &gt;
            &lt;v-simple-table v-if=""table.length""&gt;
                &lt;template v-slot:default&gt;
                    &lt;thead&gt;
                    &lt;tr&gt;
                        &lt;th class=""text-left""&gt;Id&lt;/th&gt;
                        &lt;th class=""text-left""&gt;Name&lt;/th&gt;
                        &lt;th class=""text-left""&gt;Description&lt;/th&gt;
                        &lt;th class=""text-left""&gt;Action&lt;/th&gt;
                    &lt;/tr&gt;
                    &lt;/thead&gt;
                    &lt;tbody&gt;
                    &lt;tr v-for=""(item, index) in table"" :key=""index""&gt;
                        &lt;td&gt;{{ item.id }}&lt;/td&gt;
                        &lt;td&gt;{{ item.name }}&lt;/td&gt;
                        &lt;td&gt;{{ item.description }}&lt;/td&gt;
                        &lt;td&gt;
                            &lt;v-btn
                                    color=""blue""
                                    :to=""{name: 'create', params: { item: item, id: item.id }}""
                            &gt;
                                Update
                            &lt;/v-btn&gt;
                            &lt;v-btn
                                    color=""red""
                                    @click=""show(item)""
                            &gt;
                                Delete
                            &lt;/v-btn&gt;
                        &lt;/td&gt;
                    &lt;/tr&gt;
                    &lt;/tbody&gt;
                &lt;/template&gt;
            &lt;/v-simple-table&gt;
        &lt;/v-layout&gt;
        &lt;v-btn
                :to=""{name: 'create'}""
                color=""primary""
        &gt;
            &lt;span class=""mr-2""&gt;Create&lt;/span&gt;
        &lt;/v-btn&gt;
        &lt;modal name=""hello-world""&gt;
            &lt;v-container&gt;
                &lt;v-layout
                        text-center
                        wrap
                &gt;
                    Are you sure you eant to remove this item?
                &lt;/v-layout&gt;
                &lt;v-layout
                        text-center
                        wrap
                &gt;
                    &lt;v-btn
                            color=""red""
                            @click=""deleteItem""
                    &gt;
                        Yes
                    &lt;/v-btn&gt;
                    &lt;v-btn
                            color=""primary""
                            @click=""hide""
                    &gt;
                        No
                    &lt;/v-btn&gt;
                &lt;/v-layout&gt;
            &lt;/v-container&gt;
        &lt;/modal&gt;
    &lt;/v-container&gt;
&lt;/template&gt;

&lt;script&gt;
    import { mapState, mapActions } from 'vuex'
    export default {
        name: ""Table"",
        data() {
            return {
                itemToRemove: null
            }
        },
        methods: {
            ...mapActions([
                'removeItem'
            ]),
            show (item) {
                this.$modal.show('hello-world');
                this.itemToRemove = item
            },
            hide () {
                this.$modal.hide('hello-world');
                this.itemToRemove = null
            },
            deleteItem () {
                this.removeItem(this.itemToRemove)
                this.hide()
            }
        },
        computed:
            mapState({
            table: state =&gt; state.table.table
        })
    }
&lt;/script&gt;

&lt;style scoped&gt;

&lt;/style&gt;
</code></pre>

<p>And I want to run test there. I have file <code>table.spec.js</code> inside <code>tests/unit</code> folder</p>

<pre><code>import { expect } from 'chai'
import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import Table from '@/components/Table.vue'
const localVue = createLocalVue()
localVue.use(Vuex)
const store = new Vuex.Store({
    state: {}
})

describe('Table.vue', () =&gt; {
    it('renders h1 tag', () =&gt; {
    const wrapper = shallowMount(Table, {localVue, store})
    expect(wrapper.find('h1').text().equal('Table'))
})
})
</code></pre>

<p>When I run command <code>npm run test:unit</code> I have error <code>1) Table.vue
       renders h1 tag:
     TypeError: Cannot read property 'table' of undefined</code>
previously it was error with text <code>Cannot read property 'state' of undefined</code></p>

<p>I tried to include vuex inside tests, but it is my first time with unit-test and looks like I do something wrong</p>

<p>I need my test to be passed and maybe someone can help me to write new test for some event, for example click button and call action. Thanks in advance</p>
",https://stackoverflow.com/questions/58475075/how-can-i-solve-problem-with-vuex-and-unit-testing,"['unit-testing', 'vue.js', 'mocha.js', 'vuex']",147,True,1,1
How do i properly import relative path for unit testing,"<p>I have been reading <a href=""https://stackoverflow.com/questions/30669474/beyond-top-level-package-error-in-relative-import"">this</a>, <a href=""https://stackoverflow.com/questions/6323860/sibling-package-imports"">this</a> and <a href=""https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time"">this</a> but i still can't figure out how to proper import so i can run coverage.</p>

<p>This is the structure of my app</p>

<pre><code>package/
   app/
      services/
         __init__.py
         news_services.py
   test/
      news_test.py
</code></pre>

<p>This is the import</p>

<p><code>from ..app.services.news_services import NewsServices</code></p>

<p>This is the command that i run the file.</p>

<pre class=""lang-py prettyprint-override""><code>coverage run .\test\news_test.py
</code></pre>

<p>And this is the error that i get</p>

<p><code>ValueError: attempted relative import beyond top-level package</code></p>
",https://stackoverflow.com/questions/57998289/how-do-i-properly-import-relative-path-for-unit-testing,['python'],246,True,1,1
Implementing code coverage and unit testing on existing Python/Flask app,"<p>Having trouble getting this implementation down.</p>

<p>What I need: Code coverage results on my existing flask application, preferably using unit tests compatible with pytest.</p>

<p>What I am seeing:
I am seeing coverage only for lines that are executed on the startup of my app. When I use pytest or postman to send requests to my server, coverage metrics do not change. That is, I can start the server, stop it, and get the same results as starting it, sending requests, and stopping it.  </p>

<p>I have investigated using pytest, pytest-cov, and coverage.py. </p>

<p>I implemented the sitecustomize.py coverage plugin workaround in site_packages to support subprocess coverage, to no effect.</p>

<p>I am running the coverage server like this:
<code>coverage run --source . app.py  -m</code></p>

<p>Then in a new terminal, I am running pytest like this:
<code>pytest</code></p>

<p>Then I ctrl+c the server, run 
<code>coverage report -m</code>
to view my output. </p>

<p>My app.py has contents like this:</p>

<pre class=""lang-py prettyprint-override""><code>from flask import Flask, request, render_template, make_response
from flask_cors import CORS
from flask_restplus import Resource, Api, reqparse
app = Flask(__name__)
CORS(app)
api = Api(app)

if ENV == 'dev':
    app.debug = True
else:
    app.debug = False
ns_namespace = api.namespace('namespace', description='namespace')
@ns_namespace.route(""/"")
class Namespace(Resource):
    def get(self):
        pass

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0')

</code></pre>

<p>Ideally, I want to run one command to start the app.py server, execute pytest, and record the actual code coverage. Has someone run into something like this?</p>
",https://stackoverflow.com/questions/58631061/implementing-code-coverage-and-unit-testing-on-existing-python-flask-app,"['python-3.x', 'flask', 'pytest', 'coverage.py', 'pytest-cov']",1858,True,7,1
Periodic work not reach running state when unit testing WorkManager,"<p>I created a <code>PeriodicWorkRequest</code> from my <code>SyncDatabaseWorker</code>, which like below:</p>

<pre><code>class SyncDatabaseWorker(ctx: Context, params: WorkerParameters) : RxWorker(ctx, params) {

    private val dataManager: DataManager = App.getDataManager()

    override fun createWork(): Single&lt;Result&gt; {
        return Single.create { emitter -&gt;

            dataManager.loadStoresFromServer()
                    .subscribe(object : SingleObserver&lt;List&lt;Store&gt;&gt; {
                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onSuccess(storeList: List&lt;Store&gt;) {
                            if (!storeList.isEmpty()) {
                                emitter.onSuccess(Result.success())
                            } else {
                                emitter.onSuccess(Result.retry())
                            }
                        }

                        override fun onError(e: Throwable) {
                            emitter.onSuccess(Result.failure())
                        }
                    })
        }
    }

    companion object {
        fun prepareSyncDBWorker(): PeriodicWorkRequest {
            val constraints = Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build()

            val myWorkBuilder = PeriodicWorkRequest.Builder(SyncDatabaseWorker::class.java, 7, TimeUnit.DAYS)
                    .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1, TimeUnit.DAYS) // Backoff retry after 1 day
                    .setConstraints(constraints)

            return myWorkBuilder.build()
        }
    }
}
</code></pre>

<p>Then I write unit test base on <a href=""https://developer.android.com/topic/libraries/architecture/workmanager/how-to/testing#periodic-work"" rel=""nofollow noreferrer"">Google's guide</a> like this:</p>

<pre><code>@RunWith(AndroidJUnit4::class)
class SyncDatabaseWorkerTest {
    private lateinit var context: Context

    @Before
    fun setup() {
        context = InstrumentationRegistry.getInstrumentation().targetContext

        val config = Configuration.Builder()
                .setMinimumLoggingLevel(Log.DEBUG)
                .setExecutor(SynchronousExecutor())
                .build()

        // Initialize WorkManager for instrumentation tests.
        WorkManagerTestInitHelper.initializeTestWorkManager(context, config)
    }

    @Test
    @Throws(Exception::class)
    fun testPeriodicWork_WithConstrains() {
        // Create request
        val request = SyncDatabaseWorker.prepareSyncDBWorker()

        val workManager = WorkManager.getInstance(context)
        val testDriver = WorkManagerTestInitHelper.getTestDriver(context)

        // Enqueue and wait for result.
        workManager.enqueue(request).result.get()

        // Check work request is enqueued
        var workInfo = workManager.getWorkInfoById(request.id).get()
        assertThat(workInfo.state, `is`(WorkInfo.State.ENQUEUED))

        // Tells the testing framework the period delay &amp; all constrains is met
        testDriver!!.setPeriodDelayMet(request.id)
        testDriver.setAllConstraintsMet(request.id)

        // Check work request is running
        workInfo = workManager.getWorkInfoById(request.id).get()
        assertThat(workInfo.state, `is`(WorkInfo.State.RUNNING))
    }
}
</code></pre>

<p>It's always in state <code>ENQUEUED</code>, even when <strong>period delay &amp; all constrains is met</strong>.</p>

<pre><code>Expected: is &lt;RUNNING&gt;
but: was &lt;ENQUEUED&gt;
</code></pre>

<p>When I debugged the test &amp; find out that the <code>createWork(): Single&lt;Result&gt;</code> method is also triggered, but why the state is not <code>RUNNING</code>?</p>

<p>May be I'm wrong about the approach, but the documents about unit testing WorkManager is very few now, and I don't know the right way to do it.</p>
",https://stackoverflow.com/questions/57099887/periodic-work-not-reach-running-state-when-unit-testing-workmanager,"['java', 'android', 'unit-testing', 'android-testing', 'android-workmanager']",832,True,1,2
Unit testing python data types - test failed &quot;Expected :NaT Actual:NaT&quot;,"<p>I am introducing unit-testing my python data pipeline using <code>unittest</code> module.  </p>

<p>Data class object example:</p>

<pre class=""lang-py prettyprint-override""><code>class IsAvailable(Object)
    employee_id: int = Property()
    start_time: str = Property()
</code></pre>

<p>Unit test case:</p>

<pre class=""lang-py prettyprint-override""><code>class TestIsAvailable(TestCase):
    def setUp(self):
        self.employee = pd.read_json('employee_leave.json', orient='records')
        self.isAvailable = IsAvailable()
        self.isAvailable.id = self.employee['start_time'][0]
</code></pre>

<pre class=""lang-py prettyprint-override""><code>    def test_is_available_all_day_001(self):
        assert self.isAvailable.start_time == pd.NaT
</code></pre>

<p>test result:</p>

<pre class=""lang-py prettyprint-override""><code>self = &lt;tests.test_nodes.TestIsAvailable testMethod=test_is_available_all_day_001&gt;

    def test_is_available_all_day_001(self):
        """"""test employee is available all day on specific day of the week""""""
&gt;       assert self.isAvailable.start_time == pd.NaT
E       AssertionError: assert NaT == NaT
E        +  where NaT = &lt;IsAvailable id=1&gt;.start_time
E        +    where &lt;IsAvailable id=1&gt; = &lt;tests.test_nodes.TestIsAvailable testMethod=test_is_available_all_day_001&gt;.isAvailable
E        +  and   NaT = pd.NaT

</code></pre>

<p>How do you test data types?</p>
",https://stackoverflow.com/questions/57343061/unit-testing-python-data-types-test-failed-expected-nat-actualnat,"['python', 'unit-testing', 'python-unittest']",148,False,1,1
How much should I isolate my method for unit testing?,"<p>I have the following method:</p>

<pre><code>public &lt; V extends U &gt; boolean matchesObject (V object, String filter) {

    if (filterIsAny(filter)) return true;

    else {

        List&lt;T&gt; targets = getFilterTarget(object);

        for (T t : targets) if (matches(t, filter)) return true;
        return false;

    }

}
</code></pre>

<p>where filterIsAny(filter) is a trivial method (just checks filter != null). </p>

<p>My question is: when I'm unit testing, is it worth to mock this method so that I'm sure that my function follows the correct path in the function, or do I just assume that my filterIsAny(filter) works and test using the real method? In this particular case, it is pretty easy to mock this method, but I have other instances where it would take several lines of code to mock intermediate results returned by trivial functions, such as list.indexOf(object) in a list of mocked objects.</p>

<p>I know it wouldn't be ""pure"" unit testing, since theoretically I'd be testing more than one function at a time, but how is is worth doing pure unit testing when it takes more work than finding the error in the code in the case of the test failing?</p>
",https://stackoverflow.com/questions/56985546/how-much-should-i-isolate-my-method-for-unit-testing,"['java', 'unit-testing', 'testing', 'junit', 'mocking']",177,True,1,1
Vue Unit Testing: Using Functions imported Incorrectly into a Component,"<p>I'm trying to retrofit unit testing into an old Vue app that we've developed. The one gotcha that's been set by my senior is that I cannot change any of the code in the actual app (this is causing too much headache for me).</p>

<p>Now, I'm trying to test if a method is activated when a user clicks a button:</p>

<pre><code>import { mount, shallowMount, createLocalVue } from '@vue/test-utils';
import { expect } from 'chai';
import Vuex from 'vuex';
import sinon from 'sinon';
import AccountCreation from '@/components/.../AccountCreation.vue';
import createStoreConfig from '@/store/create-store-config';

const localVue = createLocalVue();
localVue.use(Vuex);

const storeConfig = createStoreConfig();
const store = new Vuex.Store(storeConfig);
store.state.selectedMemberType = 'writer';

describe('Account Creation', () =&gt; {
  const wrapper = shallowMount(AccountCreation, {
    methods: {
    },
    store,
    localVue,
  });
  it('should return a writer argument when the validate username button is clicked', () =&gt; {
      let ga = () =&gt; {console.log('test')}
      const button = wrapper.find('#accountCreation .col-xl-5 .card span ').trigger('click')
  })
});
</code></pre>

<p>I know there's no <code>expect</code> in this test.
And the actual method looks like this. I know the method is being triggered, but <code>mocha</code>/<code>chai</code> throws an error before it can set a success.</p>

<p>I can't share the actual code, but basically it will do something like this:</p>

<pre><code>validateUsername(fieldName) {
  ga('send', 'event', 'page' 'action' 'error')
}
</code></pre>

<p>There's more to the code, but none of it is run through since <code>ga</code> will throw a <code>ReferenceError</code> when run. Google Analytics was weirdly imported in <code>main.js</code>, so I can't stub it in the normal <code>sinon</code> or <code>mocha</code> way.</p>
",https://stackoverflow.com/questions/54541184/vue-unit-testing-using-functions-imported-incorrectly-into-a-component,"['javascript', 'unit-testing', 'vue.js', 'sinon', 'chai']",191,True,1,1
Angular 7 spyon from is not working in unit testing?,"<p>Firstly, I tried all the questions &amp; answers related to this topic. Additionally and I tried related questions and try to solve it but no success. So please read my question thoroughly.</p>

<p><strong>Search Questions</strong>:</p>

<p><a href=""https://stackoverflow.com/questions/49775474/spyon-in-angular-testing"">SpyOn in Angular testing</a></p>

<p><a href=""https://stackoverflow.com/questions/53385444/spyon-not-working-in-http-interceptor-in-angular-6"">spyOn not working in Http Interceptor in Angular 6</a></p>

<p>Basically, my unit test calls a method on a component that calls a service and compares to data but somehow <strong>from</strong> is error are there. </p>

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

<pre><code>Property 'from' does not exist on type 'typeof Observable'.ts(2339)
</code></pre>

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

<p><strong>interface</strong></p>

<pre><code>export interface servicecasemodel {
    _id:string,
    propertyName:string,
    propertyDesc:string,
    propertyType:number
}
</code></pre>

<p><strong>service</strong></p>

<pre><code>import { Injectable } from '@angular/core';
import { servicecasemodel } from 'src/app/service-test-case/model/servicecasemodel';
import { HttpClient } from '@angular/common/http';
import { Observable,of } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ServicecaseService {

  constructor( private http:HttpClient) { }

   url:string = 'http://XXX.XXX.X.X:5000/api/property';
  getproduct():Observable&lt;servicecasemodel[]&gt; {
    return this.http.get&lt;servicecasemodel[]&gt;(this.url);

  }

}
</code></pre>

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

<pre><code>import { Component, OnInit } from '@angular/core';
import {ServicecaseService} from 'src/app/service-test-case/service/servicecase.service';
import { servicecasemodel } from './model/servicecasemodel';

@Component({
  selector: 'app-servicce-test-case',
  templateUrl: './service-test-case.component.html',
  styleUrls: ['./service-test-case.component.css']
})
export class ServiceTestCaseComponent implements OnInit {

  product:servicecasemodel[];
  constructor( private service_instance:ServicecaseService) { }

  ngOnInit() {
   this.service_instance.getproduct().subscribe(
      (responce:servicecasemodel[]) =&gt; {
        console.log(responce);
        this.product = responce;
      }
    );

  }

}
</code></pre>

<p><strong>Unit Test Code</strong></p>

<pre><code>import {ServicecaseService} from 'src/app/service-test-case/service/servicecase.service';
import { ServiceTestCaseComponent } from './service-test-case.component';
import { servicecasemodel } from './model/servicecasemodel';
import { Observable,from,of, observable,throwError } from 'rxjs';

describe('ServiceTestCaseComponent', () =&gt; {
  let component :ServiceTestCaseComponent;
  let service: ServicecaseService;
  const Getdata :servicecasemodel[] =[
    {
      _id:'1',
      propertyName:'Pro Nmae',
      propertyDesc:'Pro Desc',
      propertyType:1
    },
    {
      _id:'2',
      propertyName:'Pro Nmae 2',
      propertyDesc:'Pro Desc 2',
      propertyType:3
    },
  ];


  beforeEach(() =&gt; {

    service = new ServicecaseService(null);
    component = new ServiceTestCaseComponent(service);

  });

  it('should set property with the items returned',() =&gt;{

      spyOn(service,'getproduct').and.callFake(() =&gt; { 
      return Observable.from([Getdata]);
    }); 


    // Make actual call
    component.ngOnInit();
    //expect(service).toBeTruthy();
    expect(component.product).toEqual(Getdata);
  });
});
</code></pre>
",https://stackoverflow.com/questions/54740902/angular-7-spyon-from-is-not-working-in-unit-testing,"['angular', 'unit-testing', 'http', 'jasmine', 'karma-jasmine']",3554,True,1,1
How to use jest in react native for unit testing,"<p>Here I am trying to implemnet jest unit testing . There are 2 files test and mock . In below code I am excuting test file (npm run test Contactdetails-test). But getting error
     FAIL  <strong>tests</strong>/Contactdetails-test.js
  × find Contact details info (5ms)
   ● find Contact details info</p>

<pre><code>ReferenceError: MockedProvider is not defined


 Contactdetails-mock.js
        import react from 'react-native';
        import Contactdetails from '../app/components/container/ContactdetailsContainer';
        import { __generator } from 'tslib';

        const contactDetails = `[{""contactDetails"":{""isContactBySms"":""Y"",""mobileNo"":""8880995809"",""isContactByPost"":""N"",""isContactByEmail"":""Y"",""emailId"":""test@test.com""},""socialMediaDetails"":{""socialMediaDetail"":[{""name"":""twitter"",""link"":""HARIRAM@twitter.com"",""__typename"":""SocialMediaDetail""},{""name"":""facebook"",""link"":""VarnaHERO@facebook.com"",""__typename"":""SocialMediaDetail""},{""name"":""linkedIn"",""link"":""linkedIn@linkedin.com"",""__typename"":""SocialMediaDetail""},{""name"":""instagram"",""link"":""instagram@instagram.com"",""__typename"":""SocialMediaDetail""},{""name"":""telegram"",""link"":""kaushik@telegram.com"",""__typename"":""SocialMediaDetail""}]}}]`;
        const contactDetailsinfo = JSON.parse(contactDetails);
        console.log(""contact info"", contactDetailsinfo);


        export const ContactDetailsData = {
            customerInfo: { contactDetailsinfo },

        }

    // Contactdetails-test.js

    import React from 'react';
    import renderer from 'react-test-renderer';
    import ContactDetailsData from '../__mocks__/Contactdetails-mock';
        expect(findElement(tree,'Contactdetails.customerInfo','Contactdetails.navigation','')).toBeDefined();

    //   });

    it('find Contact details info', () =&gt; {

        renderer.create(
            &lt;MockedProvider mocks={mocks} addTypename={false}&gt;
                &lt;ContactDetailsData /&gt;
            &lt;/MockedProvider&gt;,
        );
    });
</code></pre>

<p>Please help</p>
",https://stackoverflow.com/questions/57671933/how-to-use-jest-in-react-native-for-unit-testing,"['javascript', 'reactjs', 'react-native', 'jestjs', 'babel-jest']",42,False,1,0
How to deal with Error 0 in CakePHP Unit Testing?,"<p>Whilst trying to access my unit tests through the browser I encountered an error '0'. (See full error below). My cake application is inside a docker container, with another docker container running alongside it to run the database.</p>

<p>I checked the test.php file and the phpunit.phar and phpunit.php files, but cannot uncover any cause for the error. I've also tried to set up a test database, and I'm not sure if that might be causing the error.</p>

<pre><code>0
phar ""/var/www/&lt;app_name&gt;/app/Vendor/phpunit.phar"" SHA1 signature could not be verified: broken signature
</code></pre>

<p>I should be able to see a list of all the core tests that I have available.</p>
",https://stackoverflow.com/questions/55337075/how-to-deal-with-error-0-in-cakephp-unit-testing,"['unit-testing', 'cakephp-2.0', 'sha1']",52,True,1,1
How to get the response data in laravel unit testing,"<p>I have been trying to work with laravel unit testing.
What I wanted was how to get the response data of original.</p>

<pre><code>public function testProducts()
{
    $response=$this-&gt;call('GET','/products',['cat','all']);

    // dd($response);

    $data = $response-&gt;getData();
    //  dd($data);
}
</code></pre>

<p>When I dd in the first case it shows me HTML content. What I want to be shown is the real content with array. What should I do ?</p>
",https://stackoverflow.com/questions/59012648/how-to-get-the-response-data-in-laravel-unit-testing,"['laravel', 'unit-testing']",2206,False,1,3
Unit testing the code that is written using repository pattern,"<p>I am implemented my business logic using repository pattern. I basically have Approve method in my controller . I am calling the service method ApproveUserChangeRequest
which in turn invokes GetUserChangeRequest and ApproveUserChangeRequest in the UnitofWork class. I would like to know if this is standard or better way of doing it
Please bare in mind in to test the service methods</p>

<p>UserConroller</p>

<pre><code>[HttpPost]
[AllowAnonymous]
[Route(""approve-change-request"")]
public IActionResult ApproveUserChangeRequest([FromBody] ApproveUserChangeRequests approveUserChangeRequests)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(new ResponseModel()
        {
            ResponseMessages = new Dictionary&lt;string, string[]&gt;
            {
                { ""Errors"", ModelState.Values.SelectMany(x =&gt; x.Errors).Select(x =&gt; x.ErrorMessage).ToArray() }
            }
        });
    }    

    var result  = _userService.ApproveUserChangeRequest(approveUserChangeRequests);
    var message = string.Empty;
    if (result.Succeeded)
    {
        return Ok(new ResponseModel()
        {
            ResponseMessages = new Dictionary&lt;string, string[]&gt;
            {
               { ""Info"", new string[] { $""True"" } }
            }
        });
    }
    message = string.Join("";"", result.Errors.Select(x =&gt; $""Code: {x.Code}. Description: {x.Description}""));
    _logger.Error(new IdentityException($""Error approving user change requests. Message: {message}""));
    return BadRequest();

}
</code></pre>

<p>UserService class  </p>

<pre><code>public  IdentityResult ApproveUserChangeRequest(ApproveUserChangeRequests approveUserChangeRequests)
{
    var userChangeRequest = _userUow.GetUserChangeRequest(approveUserChangeRequests.UserChangeRequestID);

    IdentityResult result =  _userUow.ApproveUserChangeRequest(userChangeRequest, approveUserChangeRequests.ApprovedByAuthUserId, approveUserChangeRequests.AuthApplicationName);
    return result;
}    
</code></pre>

<p>UnitofWork class (uow)</p>

<pre><code>public UserChangeRequest GetUserChangeRequest(int userChangeRequestId)
{
    return UserChangeRequestRepository.GetQueryable(x =&gt;
        x.Id == userChangeRequestId)
        .FirstOrDefault();
}


public IdentityResult ApproveUserChangeRequest(UserChangeRequest userChangeRequest, int approvedByAuthUserId, string authApplicationName)
{
    var idResult = IdentityResult.Success;

    // Check if UserChangeRequest is still Pending
    bool isUserChangeRequestPending = UserChangeRequestRepository.GetQueryable(x =&gt; x.Id == userChangeRequest.Id &amp;&amp; x.ChangeStatus == ""Pending"").Any();

    if (isUserChangeRequestPending &amp;&amp; approvedByAuthUserId &gt; 0)
    {
        // Inserting record in the UserChangeRequestApproval table
        InsertUserChangeRequestApproval(userChangeRequest);
        SaveContext();

        //Updating the user details in IdentityDB, ClientCompanyContact and AuthUser tables 
        UpdateUserDetails(userChangeRequest, authApplicationName);
    }
    else
    {
        idResult = IdentityResult.Failed(new IdentityError { Description = ""No userchange request to approve"" });
    }
    return idResult;
}
</code></pre>
",https://stackoverflow.com/questions/58838048/unit-testing-the-code-that-is-written-using-repository-pattern,"['c#', 'repository-pattern']",72,False,1,1
Unit testing - unexpected result from lambda expression in mock object,"<p>I am writing some unit tests. One of the tests I have written has unexpected behavior and I am confused about what has happened exactly. The problem is in mocking <code>GetAsync</code> method. When I use a variable like <code>limit</code>, the code does not work correctly, but if I use const instead of variables it works fine. Here is my source code:</p>

<pre><code>namespace TestClass
{
    public class LambdaTest&lt;T&gt; where T : TestModel
    {
        readonly List&lt;T&gt; _list = new List&lt;T&gt;();
        public virtual IEnumerable&lt;T&gt; GetAsync(Expression&lt;Func&lt;T, bool&gt;&gt; predicate)
        {
            return _list.AsQueryable().Where(predicate).Where(x =&gt; !x.IsDeleted).ToList();
        }

        public IEnumerable&lt;T&gt; TestMethod()
        {
            int limit = 100;
            var result = GetAsync(p =&gt; !p.IsDeleted &amp;&amp; (DateTime.Now - p.CreationDate).TotalHours &lt; limit);
            return result;
        }
    }

    public class TestModel
    {
        public long Id { get; set; }
        public bool IsDeleted { get; set; }
        public DateTime CreationDate { get; set; }
    }
}
</code></pre>

<p>And the Test project:</p>

<pre><code>namespace TestClass.Tests
{
    public class ExpressionTest
    {
        [Fact]
        public void SimpleTest()
        {
            var returnValue = new List&lt;TestModel&gt;
            {
                new TestModel() {CreationDate = DateTime.Now, Id = 1},
                new TestModel() {CreationDate = DateTime.Now, Id = 2}
            };
            var sut = new Mock&lt;LambdaTest&lt;TestModel&gt;&gt;();
            int limit = 100;
            sut.Setup(x =&gt; x.GetAsync(p =&gt; !p.IsDeleted &amp;&amp; (DateTime.Now - p.CreationDate).TotalHours &lt; limit))
               .Returns(returnValue);

            var result = sut.Object.TestMethod();

            Assert.True(true);
        }
    }
}
</code></pre>

<p>I can not use const here. I know about expression tree and some other subjects related to this problem, but can anyone explain what is happening exactly here and how can I solve this problem?</p>

<p>I will appreciate any help.</p>
",https://stackoverflow.com/questions/54991627/unit-testing-unexpected-result-from-lambda-expression-in-mock-object,"['c#', 'unit-testing', 'lambda', 'moq', 'xunit']",527,True,1,1
Python unit testing on class methods with no input arguments,"<p>Given a class with class methods that contain only <code>self</code> input:</p>

<pre><code>class ABC():
    def __init__(self, input_dict)
        self.variable_0 = input_dict['variable_0']
        self.variable_1 = input_dict['variable_1']
        self.variable_2 = input_dict['variable_2']
        self.variable_3 = input_dict['variable_3']

    def some_operation_0(self):
        return self.variable_0 + self.variable_1

    def some_operation_1(self):
        return self.variable_2 + self.variable_3
</code></pre>

<p><strong>First question</strong>: Is this very bad practice? Should I just refactor <code>some_operation_0(self)</code> to explicitly take the necessary inputs, <code>some_operation_0(self, variable_0, variable_1)</code>? If so, the testing is very straightforward.</p>

<p><strong>Second question</strong>: What is the correct way to setup my unit test on the method <code>some_operation_0(self)</code>? 
Should I setup a fixture in which I initialize <code>input_dict</code>, and then instantiate the class with a mock object?</p>

<pre><code>@pytest.fixture
def generator_inputs():
    f = open('inputs.txt', 'r')
    input_dict = eval(f.read())
    f.close()
    mock_obj = ABC(input_dict)

def test_some_operation_0():
    assert mock_obj.some_operation_0() == some_value
</code></pre>

<p>(I am new to both python and general unit testing...)</p>
",https://stackoverflow.com/questions/59181921/python-unit-testing-on-class-methods-with-no-input-arguments,"['python', 'unit-testing', 'pytest']",908,True,1,1
Unit Testing with mocking of FusedLocationProviderClient and dependency injection with Koin,"<p>Within our Android app we are using Google Maps API in order to show the users location. At the moment we are using Koin in order to provide a parametered injection (it requires an activity) of the FusedLocationProviderClient dependency into our Fragment class. In theory, this should make testing and mocking the Client class (with mockk) more straight forward. However, upon attempts to run tests with the Android FragmentScenario, it appears the test hangs in an endless loop somewhere (with debugging giving no answers as to why). 
Does anyone have any further ideas on how to test this alongside the frameworks we are using. Android/Google documentation offers no assistance and nor does numerous hours of trawling the web.</p>

<p>We have attempted to test with and without injection of the FusedLocationProvideClient. We have tried to launch the Koin test module, in our test class, parameterised with the activity and without and nothing seems to make a difference. The FusedLocationProviderClient is mocked with relaxed set to true.</p>

<p>Test Class:</p>

<pre><code>private val viewModel = mockk&lt;LocationSelectionViewModel&gt;(relaxed = true)
    private val locationClient = mockk&lt;FusedLocationProviderClient&gt;(relaxed = true)


    override var testModule = module {
        viewModel { viewModel }
        factory { locationClient }
    }

    @Test
    fun itShouldDoSomethingWithLocation() {
        val scenario = FragmentScenario.launchInContainer(LocationSelectionDialogFragment::class.java)
        scenario.moveToState(Lifecycle.State.RESUMED)
        scenario.onFragment {
            val location = Location(""this"")
            location.latitude = 37.422
            location.longitude = -122.084
            location.accuracy = 3.0f

            locationClient.setMockMode(true)
            locationClient.setMockLocation(location)
            verify { viewModel.onDisplayed() }
        }
    }
</code></pre>

<p>Fragment Class:</p>

<pre><code>class LocationSelectionDialogFragment: AbstractBottomSheetFragment(), KoinComponent, TestSupportDatabindingInterface, OnMapReadyCallback {

    private lateinit var _dataBinding: ViewDataBinding
    override fun dataBinding(): ViewDataBinding? = _dataBinding

    private val viewModel: LocationSelectionViewModel by viewModel()

    //Ma Objects n Variables
    private val LOCATION_PERMISSION = 42

    private lateinit var map: GoogleMap
    private var mapView: MapView? = null

    private val fusedLocationClient: FusedLocationProviderClient by inject { parametersOf(activity!!) }
    private lateinit var locationCallback: LocationCallback
</code></pre>

<p>Stuck in an endless loop</p>
",https://stackoverflow.com/questions/57053426/unit-testing-with-mocking-of-fusedlocationproviderclient-and-dependency-injectio,"['android', 'google-maps', 'fusedlocationproviderapi', 'koin', 'mockk']",1171,False,7,1
Unit testing. Reducer does not change state after dispatching action,"<p>I am trying to perform simple reducer test. new StartLoading(); is dispatched this should set isLoading to true. Unfortunately it shows: 
<strong>Expected $.isLoading = false to equal true.</strong></p>

<p>Nothing fancy. This is how test looks like:</p>

<pre><code>   it('should set isLoading to true', () =&gt; {
        const isLoading = true;

        const action = new StartLoading();
        const newState = uiReducers(initialState, action);

        const expectedState = { ...initialState, isLoading };

        expect(newState).toEqual(expectedState);
    })
</code></pre>

<p>And reducer:</p>

<pre><code>export interface UIState {
    isLoading: boolean;
}

export const initialState: UIState = {
    isLoading: false
};

export function uiReducers(state = initialState, action: UIActions) {
    switch (action.type) {
        case UIActionTypes.START_LOADING: {
            console.log('stt')
            return {
                isLoading: true,
                ...state
            };
        }
        case UIActionTypes.STOP_LOADING: {
            return {
                isLoading: false,
                ...state
            };
        }
        default:
            return {
                ...state
            }
    }

}
</code></pre>
",https://stackoverflow.com/questions/57827434/unit-testing-reducer-does-not-change-state-after-dispatching-action,"['angular', 'jasmine', 'karma-runner', 'ngrx-reducers']",157,True,0,1
how to mockup translateservice in jasmine unit testing of angular,"<p>LearningComponent > should create</p>

<blockquote>
  <p>TypeError: this.translate.addLangs is not a function</p>
</blockquote>

<p>Getting above error of my custom <code>component(LearningComponent)</code> while mocking up the Translate Service</p>
",https://stackoverflow.com/questions/57971152/how-to-mockup-translateservice-in-jasmine-unit-testing-of-angular,['karma-jasmine'],588,False,0,1
Do unit testing using protractor having good scope in future?,"<p>I was working in Blackbox automation testing earlier, recently I am working on E2E unit testing using type script and Protractor framework. I just want to know the scope of my current work compared to my previous one. This ll help me to learn and work more enthusiastically. </p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/57001344/do-unit-testing-using-protractor-having-good-scope-in-future,"['typescript', 'unit-testing', 'protractor']",63,True,0,1
how to write angular 6 unit testing for if condition,"<p>How to write unit testing for if the condition, please help me, anyone I tried to like this but it's not covered in my codecoverage</p>

<p>My component</p>

<pre><code>isAppListEditable(){
    if(this.requestType === ""new""){
      //console.info('inside');
      return false;
    }else{
      return true;
    }
  }
</code></pre>

<p>my spec file </p>

<pre><code>it('isAppListEditable', () =&gt; {
    let requestType = ""new"";
    component.isAppListEditable();
    expect(component.isAppListEditable()).toBeFalsy;
  });
</code></pre>
",https://stackoverflow.com/questions/55293125/how-to-write-angular-6-unit-testing-for-if-condition,"['angular', 'unit-testing']",320,False,0,0
How can i apply Unit Testing on my simple algorithm?,"<p>I have a maven project that draws Christmas tree. I need to implement Unit tests on it but i have no idea how to do it :/  </p>

<p>I already set up , JUnit on my Maven project </p>

<pre><code>for (int i = 0; i &lt; 4; i++) {
   for (int j = 0; j &lt; 10 - i; j++)
    System.out.print("" "");
   for (int k = 0; k &lt; (2 * i + 1); k++)
    System.out.print(""*"");
   System.out.println();
  }
</code></pre>
",https://stackoverflow.com/questions/56327366/how-can-i-apply-unit-testing-on-my-simple-algorithm,"['java', 'unit-testing', 'junit']",471,True,-2,2
Unit testing controller functions in Nodejs using Mocha and Chai,"<p>I have a function in my controller which takes 2 arguments request and response. </p>

<pre><code>function convertTime (req, res) {
   callOtherFunction().then(function(result){
       res.status(200).send(result);
    }
}
</code></pre>

<p>My unit testing function to test this function looks something like this. </p>

<pre><code>describe('Testing my function ', function() {
  var req = {
      query: {}
     };

 var res = {
     sendCalledWith: '',
     send: function(arg) { 
              this.sendCalledWith = arg;
            },
    json: function(err){
            console.log(""\n : "" + err);
            },
     status: function(s) {this.statusCode = s; return this;}
   };

  it('Should error out if no inputTime was provided', function() {
    convertTime(req,res);
    expect(res.statusCode).to.equal(500)
  });

});
</code></pre>

<p>when I run my unit testing, it's not waiting for my response to resolve. As I don't have a callback function here to wait for, how do I make the test to wait until res object is updated?</p>
",https://stackoverflow.com/questions/54397897/unit-testing-controller-functions-in-nodejs-using-mocha-and-chai,"['node.js', 'unit-testing', 'express', 'mocha.js', 'chai']",1574,True,0,1
unit testing a login view controller in ios related queries,"<p>i need to perform unit tests for login screen( it has one email textfield, one password textfield and one loginbutton), having a few queries related to it.</p>

<p>what i understand of unit testing of viewcontroller is, i need to make rest of an interacting components (like viewmodels) as mock objects.</p>

<p>So viewcontroller responsibility is only to show/take action what has been sent from mockviewmodel/viewmodel. </p>

<p>In that case for unit testing of login screen, it should only check for, is it taking correct actions based on what has been sent from viewmodels ?</p>

<p><strong>So actual testing of what kind of error/output generated by different kind of email, password combinations should be done by viewmodel unit tests.</strong></p>

<p>Is my above understanding of unit testing of loginscreen (viewcontroller) correct ?</p>
",https://stackoverflow.com/questions/59327967/unit-testing-a-login-view-controller-in-ios-related-queries,"['ios', 'swift', 'unit-testing']",517,False,1,1
General unit-testing: possible to mock self functions? (ceedling/CMock),"<p>Is it principally possible to mock the functions of a file to be tested?</p>

<p>E.g. I want to test the file self_test.c consisting of those functions:</p>

<pre><code>#include ""self_test.h""

uint8_t function_1(uint8_t argument)
{
    return function_2(argument);
}

uint8_t function_2(uint8_t argument)
{
    return (argument+1);
}
</code></pre>

<p>with the test file principally looking like this:</p>

<pre><code>#include ""mock_self_test.h""

void test_function_1(void)
{
    uint8_t input_value = 8;
    stest_function_2_ExpectAndReturn(input_value, 10);
    uint8_t output_value = function_1(input_value);
    TEST_ASSERT_EQUAL_UINT8(10, output_value);
}
</code></pre>

<p>and for completion the self_test.h file:</p>

<pre><code>uint8_t function_1(uint8_t argument);
uint8_t function_2(uint8_t argument);
</code></pre>

<p>When I do this, the compiler returns: ""error: Function function_1. Called more times than expected.""</p>

<p>I suppose this is bad practice and may not work, but as my function_2 is rather large this could save me a ton of work since I can test function_1 idependently of function_2.
And I am working on legacy code, so rewriting everything with a better testing interface is unfortunately not an option.</p>

<p>Ceedling output:</p>

<pre><code>[==========] Running 1 tests from 1 test cases.
[----------] Global test environment set-up.
[----------] 1 tests from test_self_test.c
[ RUN      ] test_self_test.c.test_function_1
test_self_test.c(22): error: Function function_1.  Called more times than expected.
 Actual:   FALSE
 Expected: TRUE
[  FAILED  ] test_self_test.c.test_function_1 (0 ms)
[----------] 1 tests from test_self_test.c (0 ms total)
</code></pre>
",https://stackoverflow.com/questions/58095755/general-unit-testing-possible-to-mock-self-functions-ceedling-cmock,"['c', 'unit-testing', 'cmock', 'ceedling']",719,True,0,1
Unit testing a class with dependency that uses getBean(&quot;myService&quot;),"<p>I'm using a Jackson custom serializer which is known to not support Spring dependency injection so my serializer class is as follows:</p>

<pre><code>public class ShippingAddressDataSerializer extends JsonSerializer&lt;ShippingAddressData&gt; {

    /** Jackson serializers don't support Spring dependency injection */
    private CalculatedSettingsService calculatedSettingsService =
            (CalculatedSettingsService) Registry.getApplicationContext().getBean(""calculatedSettingsService"");

    @Override
    public void serialize(ShippingAddressData addressData, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeStartObject();

        jsonGenerator.writeStringField(""id"", addressData.getId());

        CalculatedSettings calculatedSettings = getCalculatedSettingsService()
                .getSettingsForCurrentUser(SettingType.REQUIRE_COUNTY);

        if (calculatedSettings.getIsCountyRequired()) {
            jsonGenerator.writeStringField(""county"", addressData.getCounty());

        }

        jsonGenerator.writeEndObject();
    }

    public CalculatedSettingsService getCalculatedSettingsService() {
        return calculatedSettingsService;
    }

    public void setCalculatedSettingsService(CalculatedSettingsService calculatedSettingsService) {
        this.calculatedSettingsService = calculatedSettingsService;
    }
}
</code></pre>

<p>I'm having trouble unit testing this class because I don't know how to provide a mock version of <code>calculatedSettingsService</code>.</p>

<p>The unit test keeps trying to startup my application context and I get the below error:</p>

<pre><code>java.lang.IllegalStateException: Can not activate tenant &lt;&lt;master&gt;&gt; since it has no application context created 
</code></pre>
",https://stackoverflow.com/questions/55652649/unit-testing-a-class-with-dependency-that-uses-getbeanmyservice,"['java', 'spring', 'junit']",89,True,0,1
How to write unit testing for guzzle request in laravel?,"<p>I have a login function which makes a curl call via Guzzle Http request.The api is working fine and now i need to write unit test for the same api for all cases. Please help me how to write unit testing for the below function.</p>

<pre><code>public function login(Request $request)
    {
        $input = $request-&gt;all();

        /*
        *  check whether all the required parameters are received
        */

        $validator = Validator::make($input,[
            'username' =&gt; 'required',
            'password' =&gt; 'required'
        ]);

        if($validator-&gt;fails())
        {
            // if the validation fails send error response

            return $this-&gt;sendError('Validation Error',$validator-&gt;errors(),400);

            //EOF
        }

        /*
        *   get the username and password from Request and url value from .env file 
        *   and make a curl to  server to check the user authentication
        */

        $client = new \GuzzleHttp\Client(['http_errors' =&gt; false]);

        $response = $client-&gt;request('POST', config('link'), [
                'form_params' =&gt; [
                    'action' =&gt; 'login',
                    'username' =&gt; $input['username'],
                    'pwd' =&gt; $input['password']
                ]
            ]);

        $response_body = json_decode($response-&gt;getBody(),true);

        if(array_key_exists('success',$response_body))
        {
            if($response_body['success'] == 'yes')
            {
                $userId = $response_body['data']['profileData']['id'];
                // check if user is already registered or not

                $userObj = new User;
                $isUserExists = $userObj-&gt;checkUserExists($userId);

                // EOF

                if($isUserExists &lt; 1)
                {
                    $createUser['id'] = $userId;
                    $createUser['name'] = $response_body['data']['profileData']['first_name']."" "".$response_body['data']['profileData']['last_name'];
                    $createUser['email'] = $response_body['data']['profileData']['email'];
                    $createUser['password'] = bcrypt($input['password']);
                    $createUser['company_id'] = $response_body['data']['profileData']['company_id'];

                    $user = User::create($createUser);
                }
                else
                {
                    $user = User::find($userId);
                }

                // check if company already exists or not else register new company

                $companyObj = new Company;

                $companyId = $response_body['data']['profileData']['company_id'];
                $isCompanyExists = $companyObj-&gt;checkCompanyExists($companyId);

                if($isCompanyExists &lt; 1)
                {
                    $createCompany['id'] = $companyId;
                    $createCompany['name'] = $response_body['data']['profileData']['comp_name'];

                    $company = Company::create($createCompany);
                }

                // EOF

                // send the response back to the appliaction

                $success['user_id'] = $userId;
                $success['company_id'] = $response_body['data']['profileData']['company_id'];
                $success['token'] =  $user-&gt;createToken('silva-reborn')-&gt; accessToken;


                return $this-&gt;sendResponse($success,'Login successful');

                // EOF
            }
            else
            {
                // Invalid login

                return $this-&gt;sendError($response_body['msg'], array() ,401);

                // EOF
            }
        }
        else
        {
            return $this-&gt;sendError(""Invalid url"", '' ,404);
        }
    }
</code></pre>

<p>This api is working perfectly now i need to write the unit test case for this api .How to do it  ?</p>
",https://stackoverflow.com/questions/55255110/how-to-write-unit-testing-for-guzzle-request-in-laravel,"['laravel', 'guzzle']",1160,False,0,1
If statements not covered in a function unit testing- Jasmine,"<p>I am writing jasmine test cases for a certain code. I have covered the functions in the component but the if statements in the functions are not covered. Below are the if statements from a function which are not covered.</p>

<pre><code> ngOnChanges(changes: SimpleChanges) {
 this.branchuserRole = this.userService.getUser().getId();
 if (this.data) {
  if (this.branchuserRole === this.TEST) {
    this.data = this.data.filter(task =&gt; task.assignedUser !== null);
    this.data = this.data.filter(task =&gt; task.assignedRole === this.TEST);
    this.summaryListLength = this.data.length;
  } else {
    this.summaryListLength = this.data.length;
  }
</code></pre>

<p>The whole if else part is not covered in the code-coverage. Below is the code I tried.</p>

<pre><code>it('should call ngOnChanges function', () =&gt; {
    const changes: any = '';
    spyOn(component, 'ngOnChanges').and.callThrough();
    component.ngOnChanges(changes);
    expect(component.ngOnChanges).toHaveBeenCalled();
});
it('should set the value of data', () =&gt; {
    const changes: any = '';
    component.ngOnChanges(changes);
    component.branchuserRole = TEST;
    expect(component.data).toBeTruthy();
    expect(component.data).toEqual(component.data.filter(task =&gt; task.assignedUser !== null));
    expect(component.taskData).toEqual(component.taskData.filter(
        task =&gt; task.assignedRole === TEST));
    expect(component.summaryListLength).toEqual(component.data.length);
});
</code></pre>
",https://stackoverflow.com/questions/55625523/if-statements-not-covered-in-a-function-unit-testing-jasmine,"['angular', 'typescript', 'karma-jasmine']",7824,True,0,2
Trouble unit testing onClick method using Mocha Chai and Enzyme,"<p>I'm having trouble with unit testing using mocha, chai and enzyme for the following. I can't seem to understand how to unit test methods in components and how to unit test <code>onClick</code> methods will call those methods. 
The following is what I am trying to unit test: </p>

<pre><code>&lt;Link to=""/create-new-template-results"" onClick={this.checkLink}&gt;
    &lt;Button
        buttonname=""Next_button""
        variant=""primary""
        label=""Save""
        onClickMethod={() =&gt; this.submitTemplateCreation()}
        disabled={!this.disabledButtonCheck()}
    /&gt;
&lt;/Link&gt;
</code></pre>

<p>.</p>

<pre><code>Header: '',
Cell: value =&gt; {
    return (
        &lt;div&gt;
            &lt;img
                height={34}
                src=""https://content.usaa.com/mcontent/static_assets/Media/icon-trash.svg""
                onClick={() =&gt; this.removeAttribute(value)}
            /&gt;
        &lt;/div&gt;
    );
}
</code></pre>

<p>.</p>

<pre><code>removeAttribute = value =&gt; {
    this.props.change('templateAttributeForm', value.original.name, '');
    this.props.removeAttributeItem(value.index);
};

submitTemplateCreation() {
    let profLvlData = Object.values(this.props.templateAttributeFormData);
    let attrData = Object.keys(this.props.templateAttributeFormData);
    let attributeProfLvl = attributeProfLvlUtil(attrData, profLvlData);
    let templateCreationJSON = templateCreationPOSTFilter(attributeProfLvl, this.props.templateFormData);
    this.props.submitTemplateCreation(templateCreationJSON);
}
</code></pre>
",https://stackoverflow.com/questions/54635758/trouble-unit-testing-onclick-method-using-mocha-chai-and-enzyme,"['unit-testing', 'react-redux', 'mocha.js', 'enzyme', 'chai']",2308,False,0,1
How to fix the error from my unit-testing class?,"<p>I have an homework where I need to create a J2EE application web. In my team, I'm the one that need to prepare the unit-tests, but I have a lots of errors in them and I don't know how to solve them so I would like to request some help please.</p>

<p>Class Customer:</p>

<pre><code>public class Customer {

private int CustomerID;
private String email;

public int getCustomerID() {
    return CustomerID;
}

public void setCustomerID(int CustomerID) {
    this.CustomerID = CustomerID;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

}
</code></pre>

<p>Class CustomerDAO:</p>

<pre><code>private final DataSource myDataSource;
public CustomerDAO(DataSource dataSource) {
    this.myDataSource = dataSource;
}


public Customer LoginCustomer(int customerID, String email) throws DAOException {
    Customer result = null;

    String sql = ""SELECT * FROM CUSTOMER WHERE CUSTOMER_ID = ? AND EMAIL = ?"";
    try (Connection connection = myDataSource.getConnection(); 
        PreparedStatement stmt = connection.prepareStatement(sql)) {

        stmt.setInt(1, customerID);
                    stmt.setString(2, email);

        try (ResultSet rs = stmt.executeQuery()) {
            if (rs.next()) {
                String name = rs.getString(""NAME"");
                String address = rs.getString(""ADDRESSLINE1"");

                result = new Customer();
                                    result.setCustomerID(customerID);
                                    result.setEmail(email);
            } 
        }
    }  catch (SQLException ex) {
        Logger.getLogger(""DAO"").log(Level.SEVERE, null, ex);
        throw new DAOException(ex.getMessage());
    }

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

<p>Class DAO:</p>

<pre><code>public class DAO {

private final DataSource myDataSource;

public DAO(DataSource dataSource) {
    this.myDataSource = dataSource;
}
    public int addOrder(int ordernum, int idcustomer, int   idproduct, int quantity, int shippingcost, Date salesDate, Date shippingDate, String company) throws SQLException {
    int result = 0;
    String sql = ""INSERT INTO PURCHASE_ORDER VALUES=(?,?,?,?,?,?,?,?) "";
    try (Connection connection = myDataSource.getConnection();
            PreparedStatement stmt = connection.prepareStatement(sql)) {
        stmt.setInt(1, ordernum);
        stmt.setInt(2, idcustomer);
        stmt.setInt(3, idproduct);
        stmt.setInt(4, quantity);
        stmt.setInt(5, shippingcost);
        stmt.setDate(6, (java.sql.Date) salesDate);
        stmt.setDate(7, (java.sql.Date) shippingDate);
        stmt.setString(8, company);
        result = stmt.executeUpdate();
    }
    return result;
}
public int deleteOrder(int OrderNum) throws SQLException {
    int result = 0;
    String sql = ""DELETE FROM PURCHASE_ORDER WHERE ORDER_NUM = ?"";
    try (Connection connection = myDataSource.getConnection();
            PreparedStatement stmt = connection.prepareStatement(sql)) {
        stmt.setInt(1, OrderNum);
        result = stmt.executeUpdate();
    }
    return result;
}
public int changeOrder(int Qte, int ordernum) throws SQLException {
    int result=0;
    String sql = ""UPDATE PURCHASE_ORDER SET QUANTITY = ? WHERE ORDER_NUM=?"";
    try (Connection connection = myDataSource.getConnection();
            PreparedStatement stmt = connection.prepareStatement(sql)) {
        stmt.setInt(1, Qte);
        stmt.setInt(2, ordernum);
        result=stmt.executeUpdate();
    }
    return result;
}
</code></pre>

<p>Class DataSouceFactory:</p>

<pre><code>public class DataSourceFactory {

public enum DriverType {
    embedded, server
};

// Choic du type de driver : embedded ou serveur
private static final DriverType TYPE = DriverType.embedded;

/**
 * Renvoie la source de données (server ou embbeded)
 *
 * @return la source de données
 */
public static DataSource getDataSource() {

    ds.setDatabaseName(""sample"");
    ds.setUser(""app"");
    ds.setPassword(""app"");
    // The host on which Network Server is running
    ds.setServerName(""localhost"");
    // port on which Network Server is listening
    ds.setPortNumber(1527);
    return ds;
}

}
</code></pre>

<p>Class Product:
    public class Product {</p>

<pre><code>private int idproduct;
private int idmanufacturer;
private String productcode;
private int purchasecost;
private int quantityonhand;
private int markup;
private String available;
private String description;

public Product(int idproduct, int idmanufacturer, String productcode, int purchasecost, int quantityonhand, int markup, String available, String description){
    this.idproduct=idproduct;
    this.idmanufacturer=idmanufacturer;
    this.productcode=productcode;
    this.purchasecost=purchasecost;
    this.quantityonhand=quantityonhand;
    this.markup=markup;
    this.available=available;
    this.description=description;
}

//GETTER

public int getIdProduct() {
    return idproduct;
}

public int getIdManufacturer(){
    return idmanufacturer;
}

public String getProductCode(){
    return productcode;
}

public int getPurchaseCost(){
    return purchasecost;
}

public int getQuantityOnHand(){
    return quantityonhand;
}

public int getMarkup(){
    return markup;
}

public String getAvailable(){
    return available;
}

public String getDescription(){
    return description;
}
}
</code></pre>

<p>Class PurchaseOrder:</p>

<pre><code>public class PurchaseOrder {

private int ordernum;
private int idcustomer;
private int idproduct;
private int quantity;
private int shippingcost;
private Date salesDate;
private Date shippingDate;
private String company;

public PurchaseOrder(int ordernum, int idcustomer, int idproduct, int quantity, int shippingcost, Date salesDate, Date shippingDate, String company) {
    this.ordernum=ordernum;
    this.idcustomer=idcustomer;
    this.idproduct=idproduct;
    this.quantity=quantity;
    this.shippingcost=shippingcost;
    this.salesDate=salesDate;
    this.shippingDate=shippingDate;
    this.company=company;
}

//GETTER

public int getOrderNumber() {
    return ordernum;
}

public int getIdCustomer() {
    return idcustomer;
}

public int getIdProduct(){
    return idproduct;
}

public int getShippingCost(){
    return shippingcost;
}


public Date getSalesDate() {
    return salesDate;
}

public Date getShippingDate() {
    return shippingDate;
}

public String getCompany() {
    return company;
}



}
</code></pre>

<p>Class DAOException:</p>

<pre><code>public class DAOException extends Exception {

/**
 * Creates a new instance of &lt;code&gt;DAOException&lt;/code&gt; without detail
 * message.
 */
public DAOException() {
}

/**
 * Constructs an instance of &lt;code&gt;DAOException&lt;/code&gt; with the specified
 * detail message.
 *
 * @param msg the detail message.
 */
public DAOException(String msg) {
    super(msg);
}
}
</code></pre>

<p>Unit-testing class:</p>

<pre><code>public class DAOTest {

private DAO myDAO;
private DataSource myDataSource;
private static Connection myConnection;

/**
 * Test for the data base
 */
@Before
//Test la création de la BDD.
public void createBDD() throws SQLException {
    myDataSource = getDataSource();
    myConnection = myDataSource.getConnection();
    myDAO = new DAO(myDataSource);
}

@After
//Test la destruction de la BDD.
public void deleteBDD() throws SQLException {
    myConnection.close();
    myDAO = null;
}

@Test
//Test le remplissage de la BDD à partir d'un fichier sql.
private void fillBDD(String file, Connection myConnection) throws SQLException {
    String path = DAOTest.class.getResource(file).getFile();
    SqlFile fileSQL = new SqlFile(new File(path));
    fileSQL.setConnection(myConnection);
    fileSQL.execute();
    fileSQL.closeReader();
}

/**
 * Test for the class dataSourceFactory
 */
//Test l'acquisition de la source de donnée.
@Test
public void getDataSource() throws DAOException {
    org.hsqldb.jdbc.JDBCDataSource ds = new org.hsqldb.jdbc.JDBCDataSource();
    ds.setDatabase(""jdbc:hsqldb:mem:testcase;shutdown=true"");
    ds.setUser(""username"");
    ds.setPassword(""password"");
    return ds;
}

/**
 * Test for the class CustomerDAO
 */
@Test
// Test si le login fonctionne
public void logIN() throws DAOException {
    int customerID = 1;
    String email = ""test@example.com"";
    assertEquals(customerID, myDAO.identification(email));
}

/**
 * Test for the class ???
 */
@Test
//Test le calcule du prix du produit.
public void finalPrice() {
    float price = 10;
    int quantity = 1;
    float discountRate = 0;
    float shippingcost = 10;
    float markup = 0;
    assertEquals(price * quantity * 0.01 * (1 - discountRate) + shippingcost, ""Méthode qui calcule le prix final"");
}
}
</code></pre>

<p>I don't know if it can help, but we made a git for it here: <a href=""https://github.com/Selena00/ProjetTechnoWeb"" rel=""nofollow noreferrer"">https://github.com/Selena00/ProjetTechnoWeb</a></p>

<p>Well the first problem that I have in the unit-testing classs is the fact that when I do a ""throws DAOException"", I have an error conserning its location.</p>

<p>Same in with ""private DAO myDAO"", it says that the symbol DAO can't be found. And that problem is present everywhere where I create a new ""DAO"".
Again I have a problem with the test ""fillBDD"", where it again says that the symbol SqlFile isn't found.</p>

<p>Finally in the test ""getDataSource"", it says in the first line that the package org.hsqlsb.jsbc does not exist.</p>

<p>In all of the above case, the only thing that it proposed me was to search for depencies in the Maven repositories but without success.</p>

<p>Afterwards if some people can give me some advice about how to do the tests: ""addOrder"", ""deleteOrder"" and ""changeOrder"", I would really be grateful. For those three tests I don't know how to begin :/.</p>

<p>Thanks in advance for those who would take the time to help me :D.</p>
",https://stackoverflow.com/questions/55686550/how-to-fix-the-error-from-my-unit-testing-class,"['java', 'database', 'unit-testing', 'exception', 'netbeans']",480,False,0,0
How to perform unit testing on void function with coverage,"<p>I am new to unit testing. <br/>
I am trying to perform unit testing on the below code<br/></p>

<pre><code>public void send(Map&lt;String, List&lt;Integer&gt;&gt; mapOf){

     mapOf.forEach((k ,v) -&gt; {
         v.stream().forEach(o -&gt;{
             myList.add(o)
             message.push(o);
         });
     });
    }
</code></pre>

<p><br/></p>

<pre><code>message.push(o), pushes data to the database. &lt;br/&gt;
</code></pre>

<p><br/>
How can I Unit test this method?</p>
",https://stackoverflow.com/questions/54613838/how-to-perform-unit-testing-on-void-function-with-coverage,"['java', 'unit-testing', 'mockito']",118,True,0,1
Unit Testing a Basic Function with npm nock (hostname undefined),"<p>Updated:
I have a basic async function that I want to unit test. I am using npm's nock to mock the response from the server. Everytime I run this small test script I get the error that the hostname is undefined:
I don't understand why I get this error when I try to call the function from a test. It works fine when I run the script and when I make the call in postman. I feel like I'm looking over something that's super basic?</p>

<p>Here's the unit test code:</p>

<pre><code>const assert = require('chai').assert;
const getSorted = require('../src/karma').getSorted;
const nock = require('nock');

describe('Sorting', function () {
    it('should return karma in DESC order', function (done) {
        let expectedKarmas = { users: ['nikki', 'person', 'nolan'], karmas: ['3', '2', '1'] }

        let karmaApi = nock(`http://server:4567/`);
        karmaApi.get('/getsorted/DESC')
            .reply(200,
                [['bmlra2k=', '3'], ['cGVyc29u', '2'], ['bm9sYW4=', '1']]
            );

        let recievedKarmas = getSorted(""DESC"");
        console.log('recievedKarmas:::', recievedKarmas)
        assert.equal(recievedKarmas, expectedKarmas);
    });
});
</code></pre>

<p>Here's the original function:</p>

<pre><code>let axios = require(""axios"");
let atob = require('atob');

//end point is ""server:4567""
let KARMABOT_API_ENDPOINT = process.env.KARMABOT_API_ENDPOINT;
module.exports = {

getSorted: async function (direction) {
        if (direction !== ""ASC"" &amp;&amp; direction !== ""DESC"") {
            console.error(""INVALID SORTING DIRECTION: %s. PLEASE PROVIDE ASC OR DESC"", direction);
            return;
        }
        try {
            let url = `http://${KARMABOT_API_ENDPOINT}/getsorted/${direction}`;
            console.log('URL IS:', url)
            let jsonResult = await axios.get(url);
            let sorted = { users: [], karmas: [] };
            jsonResult.data.forEach(element =&gt; {
                //users are stored in the database encoded, atob() decodes them back into strings
                sorted.users.push(atob(element[0]));
                sorted.karmas.push(element[1]);
            });
            return sorted
        } catch (error) {
            console.error('ERROR HERE', error)
        }
    }
</code></pre>

<p>Full error:</p>

<pre><code>
  Sorting
URL IS: http://undefined/getsorted/DESC
recievedKarmas::: Promise { &lt;pending&gt; }
    1) should return karma in DESC order
ERROR HERE { Error: getaddrinfo ENOTFOUND undefined undefined:80
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
  errno: 'ENOTFOUND',
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'undefined',
  host: 'undefined',
  port: 80,
  config:
   { url: 'http://undefined/getsorted/DESC',
     method: 'get',
     headers:
      { Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/0.19.0' },
     transformRequest: [ [Function: transformRequest] ],
     transformResponse: [ [Function: transformResponse] ],
     timeout: 0,
     adapter: [Function: httpAdapter],
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     data: undefined },
  request:
   Writable {
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        emitClose: true,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     _events:
      [Object: null prototype] {
        response: [Function: handleResponse],
        error: [Function: handleRequestError] },
     _eventsCount: 2,
     _maxListeners: undefined,
     _options:
      { protocol: 'http:',
        maxRedirects: 21,
        maxBodyLength: 10485760,
        path: '/getsorted/DESC',
        method: 'GET',
        headers: [Object],
        agent: undefined,
        auth: undefined,
        hostname: 'undefined',
        port: 80,
        nativeProtocols: [Object],
        pathname: '/getsorted/DESC',
        proto: 'http',
        host: 'undefined:80' },
     _redirectCount: 0,
     _redirects: [],
     _requestBodyLength: 0,
     _requestBodyBuffers: [],
     _onNativeResponse: [Function],
     _currentRequest:
      ClientRequest {
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Socket],
        connection: [Socket],
        _header:
         'GET /getsorted/DESC HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.19.0\r\nHost: undefined\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/getsorted/DESC',
        _ended: false,
        res: null,
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Circular],
        [Symbol(isCorked)]: false,
        [Symbol(outHeadersKey)]: [Object] },
     _currentUrl: 'http://undefined:80/getsorted/DESC' },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function] }


  0 passing (24ms)
  1 failing

  1) Sorting
       should return karma in DESC order:
     AssertionError: expected {} to equal { Object (users, karmas) }
      at Context.&lt;anonymous&gt; (test/test-karma.js:21:16)



npm ERR! Test failed.  See above for more details.
</code></pre>

<p>So I know the test is at least hitting the original <code>getSorted()</code> function because <code>ERROR HERE</code> gets logged. But I don't understand why the host and host name is undefined. I'm explicitly saying 'server:4567'.</p>

<p>I think I'm making a silly mistake because this is just me trying to call a function from a basic unit test. </p>

<p>Thanks for your help!</p>
",https://stackoverflow.com/questions/56893640/unit-testing-a-basic-function-with-npm-nock-hostname-undefined,"['node.js', 'axios', 'chai']",768,True,0,1
"When Unit Testing with headless chrome, Vuex Store is undefined","<p>I'm just trying to test a simple component. I inherited a project and it was set up with Vue CLI 2 and it looks very boilerplatey. My issue is I'm trying to unit test anything I devote to the project. However, I'm having issues with the vuex store coming up as undefined. It's preventing me from testing and I haven't figured it out yet. </p>

<p>I googled around and found multiple things including this. <a href=""https://stackoverflow.com/questions/47814626/vue-js-and-vuex-this-store-is-undefined"">Vue.js and vuex: this.$store is undefined</a></p>

<p>This is the error message I'm receiving</p>

<pre><code>&gt; cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run

07 08 2019 14:52:06.948:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/07 08 2019 14:52:06.958:INFO [launcher]: Launching browser ChromeHeadless with unlimited
concurrency
07 08 2019 14:52:07.006:INFO [launcher]: Starting browser ChromeHeadless
07 08 2019 14:52:17.675:INFO [HeadlessChrome 75.0.3770 (Windows 10.0.0)]: Connected on socket KXXgp_cAT4JbkbufAAAA with id 2108708
HeadlessChrome 75.0.3770 (Windows 10.0.0) WARN LOG: '[vue-router] Duplicate named routes
definition: { name: ""load-balancing"", path: ""/networking/load-balancing/:ServiceRequestId/edit"" }'
07 08 2019 14:52:20.798:WARN [web-server]: 404: /static/img/oops.png
HeadlessChrome 75.0.3770 (Windows 10.0.0) WARN LOG: '[vue-router] Duplicate named routes
definition: { name: ""resource-groups"", path: ""/portal/resource-groups/:ResourceGroupId"" }'
HeadlessChrome 75.0.3770 (Windows 10.0.0) WARN LOG: '[vue-router] Duplicate named routes
definition: { name: ""manage-service-offerings"", path: ""/portal/admin/service-offerings/new"" }'
HeadlessChrome 75.0.3770 (Windows 10.0.0) WARN LOG: '[vue-router] Duplicate named routes
definition: { name: ""manage-service-offerings"", path: ""/portal/admin/service-offerings/:Id"" }'
HeadlessChrome 75.0.3770 (Windows 10.0.0) ERROR LOG: '[Vue warn]: Cannot find element: #app'
HeadlessChrome 75.0.3770 (Windows 10.0.0) WARN LOG: '[Vuetify] Unable to locate target [data-app]

found in

---&gt; &lt;VDialog&gt;
       &lt;VApp&gt;
         &lt;App&gt; at src/App.vue
           &lt;Root&gt;'
HeadlessChrome 75.0.3770 (Windows 10.0.0) WARN LOG: '[Vuetify] Unable to locate target [data-app]

found in

---&gt; &lt;VDialog&gt;
       &lt;VApp&gt;
         &lt;App&gt; at src/App.vue
           &lt;Root&gt;'
ERROR LOG: '[Vuetify] Image load failed

src: /static/img/oops.png

found in

---&gt; &lt;VImg&gt;
       &lt;VCard&gt;
         &lt;ThemeProvider&gt;
           &lt;VDialog&gt;
             &lt;VApp&gt;
               &lt;App&gt; at src/App.vue
                 &lt;Root&gt;'
ERROR LOG: '[Vue warn]: Error in config.errorHandler: ""TypeError: Cannot read property 'state' of undefined""'
ERROR LOG: TypeError{}
ERROR LOG: '[Vue warn]: Error in render: ""TypeError: Cannot read property 'state' of undefined""

found in

---&gt; &lt;UserDropdownMenu&gt; at src/components/common/UserDropDownMenu.vue
       &lt;Root&gt;'
ERROR LOG: TypeError{}

  User.vue
    × should have a default value of false for user-menu
        TypeError: Cannot read property 'state' of undefined
            at VueComponent.mappedState (webpack:///node_modules/vuex/dist/vuex.esm.js:791:0 &lt;- index.js:5858:31)
            at Watcher.get (webpack:///node_modules/vue/dist/vue.esm.js:3142:0 &lt;- index.js:10010:25)
            at Watcher.evaluate (webpack:///node_modules/vue/dist/vue.esm.js:3249:0 &lt;- index.js:10117:21)
            at VueComponent.computedGetter [as User] (webpack:///node_modules/vue/dist/vue.esm.js:3507:0 &lt;- index.js:10375:17)
            at VueComponent.userPhoto (webpack:///src/components/common/UserDropDownMenu.vue:35:0 &lt;- index.js:25280:49)
            at Watcher.get (webpack:///node_modules/vue/dist/vue.esm.js:3142:0 &lt;- index.js:10010:25)
            at Watcher.evaluate (webpack:///node_modules/vue/dist/vue.esm.js:3249:0 &lt;- index.js:10117:21)
            at VueComponent.computedGetter [as userPhoto] (webpack:///node_modules/vue/dist/vue.esm.js:3507:0 &lt;- index.js:10375:17)
            at Object.get (webpack:///node_modules/vue/dist/vue.esm.js:1943:0 &lt;- index.js:8811:20)
            at Proxy.render (webpack:///src/components/common/UserDropDownMenu.vue?bfff:19:26 &lt;- index.js:85974:37)


HeadlessChrome 75.0.3770 (Windows 10.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.746 secs / 0.01 secs)

</code></pre>

<p>I just want to know why store isn't rendering correctly</p>

<p>Here is the simple test that I wrote</p>

<pre><code>import {expect} from 'chai'
import {shallowMount} from '@vue/test-utils'
import UserDropDownMenu from '@/components/common/UserDropDownMenu.vue'

describe('User.vue', () =&gt; {
  it('should have a default value of false for user-menu', () =&gt; {
    const wrapper = shallowMount(UserDropDownMenu)
    const vm = wrapper.vm
    const data = vm.$data
    expect(data.UserDropDownMenu).to.equal(false)
  })
})
</code></pre>
",https://stackoverflow.com/questions/57401630/when-unit-testing-with-headless-chrome-vuex-store-is-undefined,"['vue.js', 'mocha.js', 'karma-runner', 'vuetify.js']",265,False,0,0
Error:- Can&#39;t read property variable of undefined during unit testing,"<p>variable from service is coming as undefined </p>

<p>Below is my ts file    </p>

<pre><code>ngOnInit() {

        this.serviceElectionForm.form = this.formBuilder.group({});

     /****
         * commenting below, if condition,  doesnt cause any error in spec file
         */
        if (this.registerService.submitReg.isAdminFlow) {
          this.companyDesignationForm.form = this.formBuilder.group({});
        }


        this.userAuthenticationForm.form = this.formBuilder.group({});
        this.roleDesignationForm.form = this.formBuilder.group({});

      }
</code></pre>

<p>below is my spec file </p>

<pre><code>fdescribe('RegisterComponent', () =&gt; {
  let component: RegisterComponent;
  let fixture: ComponentFixture&lt;RegisterComponent&gt;;



  const MockRegisterService = {
    isAdminFlow: true,
  }

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        RegisterComponent,

      ],
      imports: [
        AngularMaterialsGlobalModule,
        RouterTestingModule,
        ReactiveFormsModule,
        NoopAnimationsModule,
        HttpClientTestingModule
      ],
      providers: [
        { provide: RegisterService, useValue: MockRegisterService },
        CookieService
      ]
    }).compileComponents();
  }));

  describe('Base instantiation and component creation', () =&gt; {

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

    it('should create register component ', () =&gt; {
      expect(component).toBeTruthy();
    });
  });
</code></pre>

<p>The error which I am getting is </p>

<p>typeError: Cannot read property 'isAdminFlow' of undefined
TypeError: Cannot read property 'isAdminFlow' of undefined
    at RegisterComponent../src/app/pages/registration/register.component.ts.RegisterComponent.<code>ngOnInit</code></p>
",https://stackoverflow.com/questions/56653684/error-cant-read-property-variable-of-undefined-during-unit-testing,"['angular', 'angular-unit-test']",64,True,0,1
javascript unit testing - return different objects from jest virtual mocks,"<p>I've a jest unit test which uses a virtual mock.</p>

<p>The virtual mock return an object with apiName = ""standard__abc""</p>

<p>I test a function(isApiNameABC()) which uses the mocked object to return true if apiName === ""standard__abc"" else it returns false.</p>

<p>Using the code below, I'm able to test the condition where true is returned...</p>

<p>My question is, how do I modify my test code so that the virtual mock returns some other value for apiName. I want to do this to test the case where isApiNameABC() returns false.</p>

<pre><code>import * as utils from '../utils';

jest.mock('mdl/appContextService', () =&gt; {
    return { 
        appContext: {
            apiName: ""standard__abc""
        }
    }
}, {virtual: true});

describe(""utils"", () =&gt; { 
    test(""test return value of apiName is EQUAL to standard__abc"", () =&gt; {
        expect(utils.isApiNameABC()).toEqual(true);      
    });
});
</code></pre>
",https://stackoverflow.com/questions/57919158/javascript-unit-testing-return-different-objects-from-jest-virtual-mocks,"['javascript', 'unit-testing', 'jestjs', 'es6-modules']",910,True,0,1
Spring Boot 2 MockMVC unit testing with RequestPart and MultipartFile,"<p>I have the below email controller for sending email with RequestPart DTO object (userDTO) and Multipart file (3 files upload max). where userDTO is a JSON object</p>

<p>I tried using postman and it works perfectly for sending email with attachments, however i need to develop unit testing using MockMVC and I am not able to find any suitable examples on these combinations of Multipart and Request Part. When i tried using the below test class, i'm not able to hit  my controller which will trigger email.</p>

<p><strong>My Controller</strong></p>

<pre><code>   @PostMapping(path = ""/api/email/sendEmail)
    public ResponseEntity&lt;UserDto&gt; sendEmail(@RequestPart(value = ""file"", required = false) MultipartFile[] uploadfile,
            @RequestPart UserDto userDTO, WebRequest webRequest) {

            webRequest.setAttribute(""userDTO"", userDTO, RequestAttributes.SCOPE_REQUEST);
            UserDto obj = emailService.sendEmail(userDTO, uploadfile);
            return new ResponseEntity&lt;&gt;(obj, HttpStatus.OK);

    }
</code></pre>

<p><strong>My JSON (userDTO) which comes in request part</strong></p>

<pre><code>{
""sender"":""sender@gmail.com"",
""recipients"":""receiver@gmail.com"",
""subject"":""Hi Testing Mail API"",
""content"":""This is my email""
}

</code></pre>

<p><strong>My Test Class</strong></p>

<pre><code>@ContextConfiguration
@WebAppConfiguration
public class ServicesApplicationTests {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;


      @Test
        public void testEmail() throws Exception {
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();            
             mockMvc.perform(post(""/api/email/sendEmail"")
            .contentType(MediaType.APPLICATION_JSON)
               .content(""{ \""sender\"":\""sender@gmail.com\"",\""recipients\"":\""receiver@gmail.com\"",\""subject\"":\""Hi Testing Mail API\"",\""content\"":\""This is my email\""}"")
               .accept(MediaType.APPLICATION_JSON));


        }
</code></pre>

<p>Any leads would be much appreciated. Thanks</p>
",https://stackoverflow.com/questions/56301621/spring-boot-2-mockmvc-unit-testing-with-requestpart-and-multipartfile,"['unit-testing', 'spring-boot', 'multipart', 'spring-boot-test', 'mockmvc']",712,False,0,0
Use Moq to do unit testing for datatable export service,"<p>I have a service to export as csv file which inside videmodel in WPF application:</p>

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

        DataTable tblFiltered = _currentTable.AsEnumerable()
                          .Where(r =&gt; r.Field&lt;string&gt;(""Type"") == ExportGridGroup)
                          .CopyToDataTable();

        StringBuilder sb = new StringBuilder();
        IEnumerable&lt;string&gt; columnNames = tblFiltered.Columns.Cast&lt;DataColumn&gt;().
                                          Select(column =&gt; column.ColumnName);
        sb.AppendLine(string.Join("","", columnNames));

        foreach (DataRow row in tblFiltered.Rows)
        {
            IEnumerable&lt;string&gt; fields = row.ItemArray.Select(field =&gt; ""\"""" + field.ToString() + ""\"""");
            sb.AppendLine(string.Join("","", fields));
        }

        String result = sb.ToString();
        try
        {
            StreamWriter sw = new StreamWriter(""export.csv"");
            sw.WriteLine(result);
            sw.Close();
            Process.Start(""export.csv"");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
</code></pre>

<p>So based on this, i have created a test method for it but haven't finished;</p>

<pre><code> [TestMethod()]
    public void ExportToExcelTest()
    {
        //Step 1: Creating a mock table with columns
        DataTable testtable = new DataTable();
        DataRow mydatarow;
        mydatarow = testtable.NewRow();
        //Step 2: Adding the row 
        mydatarow[""ColumnA""] = ""12345"";
        mydatarow[""ColumnB""] = ""test"";

        testtable.Rows.Add(mydatarow);

        StringBuilder sb = new StringBuilder();
        IEnumerable&lt;string&gt; columnNames = testtable.Columns.Cast&lt;DataColumn&gt;().
                                          Select(column =&gt; column.ColumnName);
        sb.AppendLine(string.Join("","", columnNames));

        foreach (DataRow row in testtable.Rows)
        {
            IEnumerable&lt;string&gt; fields = row.ItemArray.Select(field =&gt; ""\"""" + field.ToString() + ""\"""");
            sb.AppendLine(string.Join("","", fields));
        }

        String result = sb.ToString();
        StreamWriter sw = new StreamWriter(""export.csv"");
        sw.WriteLine(result);
        sw.Close();
        Process.Start(""export.csv"");          
        Assert.Fail();
    }
</code></pre>

<p>I am a bit confused because in the test method, I nearly write the exact same code in the project.....
Can I have some suggestions on how to write this unit test and any detailed references on WPF/C# Unit Testing by using Moq for me to start with?</p>
",https://stackoverflow.com/questions/55226460/use-moq-to-do-unit-testing-for-datatable-export-service,"['c#', 'wpf', 'unit-testing', 'moq']",1394,True,0,1
Unexpected result from unit testing CRUD methods from Service layer,"<p>I'm trying to unit test the crud methods from my service layer, I've wrote the correct code (I think) but AssertTrue gives me the opposite result I was expecting.(java.lang.AssertionError:)</p>

<p>My test code looks as following:</p>

<p><strong>StudentServiceTest</strong></p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles(""test"")
@SpringBootTest
public class StudentServiceTest {

    private static final String STUDENT_NAME = ""Henkie"";

    @Autowired
    private StudentServiceImpl studentService;

    @Autowired
    private StudentRepository studentRepository;


    @Test
    public void createStudent(){
        //arrange
        Student student = new Student();
        student.setStudentName(STUDENT_NAME);
        studentService.save(student);

        List&lt;Student&gt; students = studentService.findAll();

        assertNotNull(students);
        assertTrue(""created a student"" ,students.contains(student));
    }
</code></pre>

<p><strong>StudentService</strong></p>

<pre><code>public interface StudentService {

    List&lt;Student&gt; findAll();

    Student save(Student student);

    Optional&lt;Student&gt; findById(Long id);

    void deleteById(Long id);

    Iterable&lt;Student&gt; findAllIteratable();      
}
</code></pre>

<p><strong>StudentServiceImpl</strong></p>

<pre><code>@Service
@RequiredArgsConstructor
public class StudentServiceImpl implements StudentService {

    @Autowired
    private final StudentRepository studentRepository;


    public List&lt;Student&gt; findAll() {
        return Lists.newArrayList(studentRepository.findAll());
    }    

    public Student save(Student student) {
        return studentRepository.save(student);
    }

    public Optional&lt;Student&gt; findById(Long id) {
        return studentRepository.findById(id);
    }

    public void deleteById(Long id) {
        studentRepository.deleteById(id);
    }

}
</code></pre>

<p><strong>StudentRepository</strong></p>

<pre><code>public interface StudentRepository extends CrudRepository&lt;Student, Long&gt; {

}
</code></pre>

<p>After debugging it's visible the student is succesfully being made, and also added to the List. But as can be seen its saved under Student@10172 , and in the students List its being saved under Student@10482 . All the previous entries in the List are the result from previous test attempts.</p>

<p><a href=""https://i.stack.imgur.com/tzDQ7.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/tzDQ7.jpg"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/56623530/unexpected-result-from-unit-testing-crud-methods-from-service-layer,"['java', 'unit-testing', 'spring-boot', 'spring-mvc', 'junit']",65,True,0,1
Cake3 Fixtures not being built during unit testing cake plugin,"<p>I have a cakephp 3.7 plugin as its own stand-alone project. But am encountering the failures below when running unit tests. It seems after moving this outside of a parent project, the fixtures are no longer being built. Not sure how to instruct cake to build them.</p>

<blockquote>
  <p>Cake\Database\Exception: Cannot describe teams. It has 0 columns.</p>
</blockquote>

<p>Here is my <code>tests/bootstrap file</code>. These tests were previously working until I decided to move this plugin out of the parent project.</p>

<pre><code>&lt;?php
$findRoot = function ($root) {
    do {
        $lastRoot = $root;
        $root = dirname($root);
        if (is_dir($root . '/vendor/cakephp/cakephp')) {
            return $root;
        }
    } while ($root !== $lastRoot);
    throw new Exception(""Cannot find the root of the application, unable to run tests"");
};
$root = $findRoot(__FILE__);
unset($findRoot);
chdir($root);

if (!defined('DS')) {
    define('DS', DIRECTORY_SEPARATOR);
}

define('ROOT', $root);
define('APP_DIR', 'App');
define('WEBROOT_DIR', 'webroot');
define('APP', ROOT . '/tests/');
define('CONFIG', ROOT . '/tests/config/');
define('WWW_ROOT', ROOT . DS . WEBROOT_DIR . DS);
define('TESTS', ROOT . DS . 'tests' . DS);
define('TMP', ROOT . DS . 'tmp' . DS);
define('LOGS', TMP . 'logs' . DS);
define('CACHE', TMP . 'cache' . DS);
define('CAKE_CORE_INCLUDE_PATH', ROOT . '/vendor/cakephp/cakephp');
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
define('CAKE', CORE_PATH . 'src' . DS);

require_once ROOT . '/vendor/cakephp/cakephp/src/basics.php';
require ROOT . '/vendor/autoload.php';

use Cake\Core\Configure;
use Cake\Core\Configure\Engine\PhpConfig;

try {
    Configure::config('default', new PhpConfig());
    Configure::load('app', 'default', false);
} catch (\Exception $e) {
    exit($e-&gt;getMessage() . ""\n"");
}

$TMP = new \Cake\Filesystem\Folder(TMP);
$TMP-&gt;create(TMP . 'cache/models', 0777);
$TMP-&gt;create(TMP . 'cache/persistent', 0777);
$TMP-&gt;create(TMP . 'cache/views', 0777);

$cache = [
    'default' =&gt; [
        'engine' =&gt; 'File',
    ],
    '_cake_core_' =&gt; [
        'className' =&gt; 'File',
        'prefix' =&gt; '_cake_core_',
        'path' =&gt; CACHE . 'persistent/',
        'serialize' =&gt; true,
        'duration' =&gt; '+10 seconds',
    ],
    '_cake_model_' =&gt; [
        'className' =&gt; 'File',
        'prefix' =&gt; '_cake_model_',
        'path' =&gt; CACHE . 'models/',
        'serialize' =&gt; 'File',
        'duration' =&gt; '+10 seconds',
    ],
    '_cake_method_' =&gt; [
        'className' =&gt; 'File',
        'prefix' =&gt; '_cake_method_',
        'path' =&gt; CACHE . 'models/',
        'serialize' =&gt; 'File',
        'duration' =&gt; '+10 seconds',
    ],
];

Cake\Cache\Cache::setConfig($cache);

if (file_exists($root . '/config/bootstrap.php')) {
    require $root . '/config/bootstrap.php';
}

if (!getenv('db_dsn')) {
    putenv('db_dsn=sqlite:///:memory:');
}

Cake\Datasource\ConnectionManager::setConfig('test', [
    'url' =&gt; getenv('db_dsn'),
    'timezone' =&gt; 'UTC'
]);
</code></pre>

<p>phpunit.xml</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;phpunit
    colors=""true""
    stopOnFailure=""false""
    bootstrap=""./tests/bootstrap.php""
    &gt;
    &lt;php&gt;
        &lt;ini name=""memory_limit"" value=""-1""/&gt;
        &lt;ini name=""apc.enable_cli"" value=""1""/&gt;
    &lt;/php&gt;

    &lt;!-- Add any additional test suites you want to run here --&gt;
    &lt;testsuites&gt;
        &lt;testsuite name=""YummySearch Test Suite""&gt;
            &lt;directory&gt;./tests/TestCase&lt;/directory&gt;
        &lt;/testsuite&gt;
    &lt;/testsuites&gt;

    &lt;!-- configure code coverage --&gt;
    &lt;filter&gt;
        &lt;whitelist&gt;
            &lt;directory suffix="".php""&gt;./src/&lt;/directory&gt;
        &lt;/whitelist&gt;
    &lt;/filter&gt;

    &lt;!-- Setup a listener for fixtures --&gt;
    &lt;listeners&gt;
        &lt;listener
                class=""Cake\TestSuite\Fixture\FixtureInjector""&gt;
            &lt;arguments&gt;
                &lt;object class=""Cake\TestSuite\Fixture\FixtureManager"" /&gt;
            &lt;/arguments&gt;
        &lt;/listener&gt;
    &lt;/listeners&gt;
&lt;/phpunit&gt;
</code></pre>
",https://stackoverflow.com/questions/57761037/cake3-fixtures-not-being-built-during-unit-testing-cake-plugin,"['phpunit', 'cakephp-3.0']",156,False,0,0
Unit Testing JavaScript in ASP.NET MVC with Jasmine and Karma,"<p>I am writing a sample ASP .NET MVC application, which has karma and requirejs to test the scripts. I see below error <strong>Uncaught (in promise) Error: No tests were run.</strong></p>

<p>I see below error in command prompt
<strong>Chrome 77.0.3865 (Windows 10.0.0): Executed 0 of 0 ERROR (0.012 secs / 0 secs)</strong></p>

<p>Package.json</p>

<pre><code>{
  ""name"": ""karmawebapp"",
  ""version"": ""1.0.0"",
  ""description"": ""test application for karma tests"",
  ""main"": ""index.js"",
  ""scripts"": {
    ""test"": ""karma start""
  },
  ""author"": """",
  ""license"": ""ISC"",
  ""devDependencies"": {
    ""babel-core"": ""^6.26.3"",
    ""babel-preset-es2015"": ""^6.24.1"",
    ""karma"": ""^4.3.0"",
    ""karma-chrome-launcher"": ""^3.1.0"",
    ""karma-qunit"": ""^4.0.0"",
    ""karma-requirejs"": ""^1.1.0"",
    ""protractor"": ""^5.4.2"",
    ""qunit"": ""^2.9.3"",
    ""requirejs"": ""^2.3.6""
  }
}
</code></pre>

<p>My karma.conf.js</p>

<pre><code>// Karma configuration
// Generated on Tue Oct 15 2019 13:51:47 GMT-0500 (Central Daylight Time)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
      frameworks: ['requirejs', 'qunit'],


    // list of files / patterns to load in the browser
    files: [
      'test-main.js',
      { pattern: './Scripts/tests/*.specs.js', included: false }
    ],


    // list of files / patterns to exclude
    exclude: [
    ],

// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},


// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],


// web server port
port: 9876,


// enable / disable colors in the output (reporters and logs)
colors: true,


// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,


// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,


// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],


// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,

// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
</code></pre>

<p>})
}</p>

<p><strong>My test-main.js</strong></p>

<pre><code>var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;

// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function(file) {
    if (TEST_REGEXP.test(file)) {
        // Normalize paths to RequireJS module names.
        // If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
        // then do not normalize the paths
        var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
        allTestFiles.push(normalizedTestModule)
    };
});

require.config({
    // Karma serves files under /base, which is the basePath from your config file
    baseUrl: '/base',

    // dynamically load all test files
    deps: allTestFiles,

    path: {
        qunit: 'qunit',
        jquery: 'jquery.3.3.1'
    },

    // we have to kickoff jasmine, as it is asynchronous
    callback: window.__karma__.start
});
</code></pre>

<p><strong>my test.specs.js</strong></p>

<pre><code>define(['qunit'], function (qunit) {

    qunit.test(""Second test"", function (assert) {
        assert.ok(true, ""Passed!"");
    });
});
</code></pre>
",https://stackoverflow.com/questions/58401245/unit-testing-javascript-in-asp-net-mvc-with-jasmine-and-karma,"['asp.net-mvc', 'testing', 'karma-runner', 'karma-qunit']",794,True,0,2
How to perform unit testing on void function with coverage,"<p>I am new to unit testing. <br/>
I am trying to perform unit testing on the below code<br/></p>

<pre><code>public void send(Map&lt;String, List&lt;Integer&gt;&gt; mapOf){

     mapOf.forEach((k ,v) -&gt; {
         v.stream().forEach(o -&gt;{
             myList.add(o)
             message.push(o);
         });
     });
    }
</code></pre>

<p><br/></p>

<pre><code>message.push(o), pushes data to the database. &lt;br/&gt;
</code></pre>

<p><br/>
How can I Unit test this method?</p>
",https://stackoverflow.com/questions/54613838/how-to-perform-unit-testing-on-void-function-with-coverage,"['java', 'unit-testing', 'mockito']",118,True,0,1
Unit Testing a Basic Function with npm nock (hostname undefined),"<p>Updated:
I have a basic async function that I want to unit test. I am using npm's nock to mock the response from the server. Everytime I run this small test script I get the error that the hostname is undefined:
I don't understand why I get this error when I try to call the function from a test. It works fine when I run the script and when I make the call in postman. I feel like I'm looking over something that's super basic?</p>

<p>Here's the unit test code:</p>

<pre><code>const assert = require('chai').assert;
const getSorted = require('../src/karma').getSorted;
const nock = require('nock');

describe('Sorting', function () {
    it('should return karma in DESC order', function (done) {
        let expectedKarmas = { users: ['nikki', 'person', 'nolan'], karmas: ['3', '2', '1'] }

        let karmaApi = nock(`http://server:4567/`);
        karmaApi.get('/getsorted/DESC')
            .reply(200,
                [['bmlra2k=', '3'], ['cGVyc29u', '2'], ['bm9sYW4=', '1']]
            );

        let recievedKarmas = getSorted(""DESC"");
        console.log('recievedKarmas:::', recievedKarmas)
        assert.equal(recievedKarmas, expectedKarmas);
    });
});
</code></pre>

<p>Here's the original function:</p>

<pre><code>let axios = require(""axios"");
let atob = require('atob');

//end point is ""server:4567""
let KARMABOT_API_ENDPOINT = process.env.KARMABOT_API_ENDPOINT;
module.exports = {

getSorted: async function (direction) {
        if (direction !== ""ASC"" &amp;&amp; direction !== ""DESC"") {
            console.error(""INVALID SORTING DIRECTION: %s. PLEASE PROVIDE ASC OR DESC"", direction);
            return;
        }
        try {
            let url = `http://${KARMABOT_API_ENDPOINT}/getsorted/${direction}`;
            console.log('URL IS:', url)
            let jsonResult = await axios.get(url);
            let sorted = { users: [], karmas: [] };
            jsonResult.data.forEach(element =&gt; {
                //users are stored in the database encoded, atob() decodes them back into strings
                sorted.users.push(atob(element[0]));
                sorted.karmas.push(element[1]);
            });
            return sorted
        } catch (error) {
            console.error('ERROR HERE', error)
        }
    }
</code></pre>

<p>Full error:</p>

<pre><code>
  Sorting
URL IS: http://undefined/getsorted/DESC
recievedKarmas::: Promise { &lt;pending&gt; }
    1) should return karma in DESC order
ERROR HERE { Error: getaddrinfo ENOTFOUND undefined undefined:80
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
  errno: 'ENOTFOUND',
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'undefined',
  host: 'undefined',
  port: 80,
  config:
   { url: 'http://undefined/getsorted/DESC',
     method: 'get',
     headers:
      { Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/0.19.0' },
     transformRequest: [ [Function: transformRequest] ],
     transformResponse: [ [Function: transformResponse] ],
     timeout: 0,
     adapter: [Function: httpAdapter],
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     data: undefined },
  request:
   Writable {
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        emitClose: true,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     _events:
      [Object: null prototype] {
        response: [Function: handleResponse],
        error: [Function: handleRequestError] },
     _eventsCount: 2,
     _maxListeners: undefined,
     _options:
      { protocol: 'http:',
        maxRedirects: 21,
        maxBodyLength: 10485760,
        path: '/getsorted/DESC',
        method: 'GET',
        headers: [Object],
        agent: undefined,
        auth: undefined,
        hostname: 'undefined',
        port: 80,
        nativeProtocols: [Object],
        pathname: '/getsorted/DESC',
        proto: 'http',
        host: 'undefined:80' },
     _redirectCount: 0,
     _redirects: [],
     _requestBodyLength: 0,
     _requestBodyBuffers: [],
     _onNativeResponse: [Function],
     _currentRequest:
      ClientRequest {
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Socket],
        connection: [Socket],
        _header:
         'GET /getsorted/DESC HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.19.0\r\nHost: undefined\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/getsorted/DESC',
        _ended: false,
        res: null,
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Circular],
        [Symbol(isCorked)]: false,
        [Symbol(outHeadersKey)]: [Object] },
     _currentUrl: 'http://undefined:80/getsorted/DESC' },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function] }


  0 passing (24ms)
  1 failing

  1) Sorting
       should return karma in DESC order:
     AssertionError: expected {} to equal { Object (users, karmas) }
      at Context.&lt;anonymous&gt; (test/test-karma.js:21:16)



npm ERR! Test failed.  See above for more details.
</code></pre>

<p>So I know the test is at least hitting the original <code>getSorted()</code> function because <code>ERROR HERE</code> gets logged. But I don't understand why the host and host name is undefined. I'm explicitly saying 'server:4567'.</p>

<p>I think I'm making a silly mistake because this is just me trying to call a function from a basic unit test. </p>

<p>Thanks for your help!</p>
",https://stackoverflow.com/questions/56893640/unit-testing-a-basic-function-with-npm-nock-hostname-undefined,"['node.js', 'axios', 'chai']",768,True,0,1
"When Unit Testing with headless chrome, Vuex Store is undefined","<p>I'm just trying to test a simple component. I inherited a project and it was set up with Vue CLI 2 and it looks very boilerplatey. My issue is I'm trying to unit test anything I devote to the project. However, I'm having issues with the vuex store coming up as undefined. It's preventing me from testing and I haven't figured it out yet. </p>

<p>I googled around and found multiple things including this. <a href=""https://stackoverflow.com/questions/47814626/vue-js-and-vuex-this-store-is-undefined"">Vue.js and vuex: this.$store is undefined</a></p>

<p>This is the error message I'm receiving</p>

<pre><code>&gt; cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run

07 08 2019 14:52:06.948:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/07 08 2019 14:52:06.958:INFO [launcher]: Launching browser ChromeHeadless with unlimited
concurrency
07 08 2019 14:52:07.006:INFO [launcher]: Starting browser ChromeHeadless
07 08 2019 14:52:17.675:INFO [HeadlessChrome 75.0.3770 (Windows 10.0.0)]: Connected on socket KXXgp_cAT4JbkbufAAAA with id 2108708
HeadlessChrome 75.0.3770 (Windows 10.0.0) WARN LOG: '[vue-router] Duplicate named routes
definition: { name: ""load-balancing"", path: ""/networking/load-balancing/:ServiceRequestId/edit"" }'
07 08 2019 14:52:20.798:WARN [web-server]: 404: /static/img/oops.png
HeadlessChrome 75.0.3770 (Windows 10.0.0) WARN LOG: '[vue-router] Duplicate named routes
definition: { name: ""resource-groups"", path: ""/portal/resource-groups/:ResourceGroupId"" }'
HeadlessChrome 75.0.3770 (Windows 10.0.0) WARN LOG: '[vue-router] Duplicate named routes
definition: { name: ""manage-service-offerings"", path: ""/portal/admin/service-offerings/new"" }'
HeadlessChrome 75.0.3770 (Windows 10.0.0) WARN LOG: '[vue-router] Duplicate named routes
definition: { name: ""manage-service-offerings"", path: ""/portal/admin/service-offerings/:Id"" }'
HeadlessChrome 75.0.3770 (Windows 10.0.0) ERROR LOG: '[Vue warn]: Cannot find element: #app'
HeadlessChrome 75.0.3770 (Windows 10.0.0) WARN LOG: '[Vuetify] Unable to locate target [data-app]

found in

---&gt; &lt;VDialog&gt;
       &lt;VApp&gt;
         &lt;App&gt; at src/App.vue
           &lt;Root&gt;'
HeadlessChrome 75.0.3770 (Windows 10.0.0) WARN LOG: '[Vuetify] Unable to locate target [data-app]

found in

---&gt; &lt;VDialog&gt;
       &lt;VApp&gt;
         &lt;App&gt; at src/App.vue
           &lt;Root&gt;'
ERROR LOG: '[Vuetify] Image load failed

src: /static/img/oops.png

found in

---&gt; &lt;VImg&gt;
       &lt;VCard&gt;
         &lt;ThemeProvider&gt;
           &lt;VDialog&gt;
             &lt;VApp&gt;
               &lt;App&gt; at src/App.vue
                 &lt;Root&gt;'
ERROR LOG: '[Vue warn]: Error in config.errorHandler: ""TypeError: Cannot read property 'state' of undefined""'
ERROR LOG: TypeError{}
ERROR LOG: '[Vue warn]: Error in render: ""TypeError: Cannot read property 'state' of undefined""

found in

---&gt; &lt;UserDropdownMenu&gt; at src/components/common/UserDropDownMenu.vue
       &lt;Root&gt;'
ERROR LOG: TypeError{}

  User.vue
    × should have a default value of false for user-menu
        TypeError: Cannot read property 'state' of undefined
            at VueComponent.mappedState (webpack:///node_modules/vuex/dist/vuex.esm.js:791:0 &lt;- index.js:5858:31)
            at Watcher.get (webpack:///node_modules/vue/dist/vue.esm.js:3142:0 &lt;- index.js:10010:25)
            at Watcher.evaluate (webpack:///node_modules/vue/dist/vue.esm.js:3249:0 &lt;- index.js:10117:21)
            at VueComponent.computedGetter [as User] (webpack:///node_modules/vue/dist/vue.esm.js:3507:0 &lt;- index.js:10375:17)
            at VueComponent.userPhoto (webpack:///src/components/common/UserDropDownMenu.vue:35:0 &lt;- index.js:25280:49)
            at Watcher.get (webpack:///node_modules/vue/dist/vue.esm.js:3142:0 &lt;- index.js:10010:25)
            at Watcher.evaluate (webpack:///node_modules/vue/dist/vue.esm.js:3249:0 &lt;- index.js:10117:21)
            at VueComponent.computedGetter [as userPhoto] (webpack:///node_modules/vue/dist/vue.esm.js:3507:0 &lt;- index.js:10375:17)
            at Object.get (webpack:///node_modules/vue/dist/vue.esm.js:1943:0 &lt;- index.js:8811:20)
            at Proxy.render (webpack:///src/components/common/UserDropDownMenu.vue?bfff:19:26 &lt;- index.js:85974:37)


HeadlessChrome 75.0.3770 (Windows 10.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.746 secs / 0.01 secs)

</code></pre>

<p>I just want to know why store isn't rendering correctly</p>

<p>Here is the simple test that I wrote</p>

<pre><code>import {expect} from 'chai'
import {shallowMount} from '@vue/test-utils'
import UserDropDownMenu from '@/components/common/UserDropDownMenu.vue'

describe('User.vue', () =&gt; {
  it('should have a default value of false for user-menu', () =&gt; {
    const wrapper = shallowMount(UserDropDownMenu)
    const vm = wrapper.vm
    const data = vm.$data
    expect(data.UserDropDownMenu).to.equal(false)
  })
})
</code></pre>
",https://stackoverflow.com/questions/57401630/when-unit-testing-with-headless-chrome-vuex-store-is-undefined,"['vue.js', 'mocha.js', 'karma-runner', 'vuetify.js']",265,False,0,0
Node.js and Mocha unit testing rollback transaction after each test,"<p>I'm using <code>node v10.16.0</code> and npm packages <code>mssql 5.1.0</code> and <code>mocha 6.2.1</code>.
What I want to do is write a sql unit test helper class (ES6) that handles transactions and rolls back after each unit test.</p>

<p><strong>db.js</strong></p>

<pre><code>const mssql  = require(""mssql"");
const config = require(""./config"");

class DbAccess{
    constructor(){
        this.connection = new mssql.ConnectionPool(config.dbConfig);

        this.connection.connect(err =&gt; {
        // ...
        })

        this.transaction = new mssql.Transaction(this.connection);

    }

    beginTransaction(){
        this.transaction.begin();
    }


    rollbackTransaction(){
        this.transaction.rollback();
    }


    executeSql (sql, callback) {
        this.connection.connect().then(() =&gt; {
            var req = new mssql.Request(conn);          
            req.query(sql).then((recordset) =&gt; {
                callback(recordset);
            })
        .catch ((err) =&gt; {
            console.log(err);
            logger.error(err);
            callback(null, err);
        });})
        .catch ((err) =&gt; {
            console.log(err);
            logger.error(err);
            callback(null, err);
        });
    }
}
</code></pre>

<p><strong>test.js</strong></p>

<pre><code>before(() =&gt; {
    dbAccess.beginTransaction();
});

after(() =&gt; {
    dbAccess.rollbackTransaction();
});
describe('Test',function(){    
    describe('SelectAll()', function(){
        it('returns all',function(){                      
            dbAccess.insertrecords();                
        });
    });
});    
</code></pre>

<p>That setup is not working as I'm getting a <code>UnhandledPromiseRejectionWarning: ConnectionError: Connection not yet open.</code></p>

<p>I can't figure out how to </p>

<ol>
<li>Begin the transaction (in the before handler), </li>
<li>Execute the sql queries (in the test, e.g. inserting records),</li>
<li>Rollback the transaction (in the after handler)</li>
</ol>
",https://stackoverflow.com/questions/58385502/node-js-and-mocha-unit-testing-rollback-transaction-after-each-test,"['node.js', 'sql-server', 'database', 'transactions', 'mocha.js']",1175,False,0,0
Should I refactor code for unit testing in mvp android?,"<p>I made an mvp application in kotlin and in each function of my presenter I call a view method so should I refactor my code for unit-testing or i just let this like that?</p>

<p>For exemple i have a function that make a regex</p>

<pre><code>private fun checkPassword(isRegister: Boolean, pass: String, confirmPass: String): Boolean {
    val regex = Regex(""^(?=.{8,}\$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])"")
    if (isRegister) {
        if (pass != confirmPass) {
            loginView.showNotMatchingPassword() // display an alert on a inputtext
            return false
        }
        if (!pass.contains(regex)) {
            loginView.showInvalidPassword() // display an alert on a inputtext
            return false
        }
    }
    return true
}
</code></pre>
",https://stackoverflow.com/questions/56360749/should-i-refactor-code-for-unit-testing-in-mvp-android,"['android', 'unit-testing', 'kotlin', 'android-mvp']",92,True,0,1
Xaml resources (like a string table) in WPF unit testing,"<p>I have a StringTable.xaml in my WPF project, with <code>&lt;system:String x:Key=""IDS_DATA_HEADER_TIMED_TEST_RECORD_NUMBER""&gt;Record Number&lt;/system:String&gt;</code>. My model makes use of this StringTable, with <code>public static string foobar = (string)Application.Current.FindResource(""PLACEHOLDER_TEXT"");</code> Thus, I cannot Unit Test my model in MSTest without it being aware of xaml. </p>

<p>This question fills a niche because many questions about xaml are how to unit to the GUI. Yes, good practice is to use the MVVM pattern to separate model from GUI, and only test the model. Yes, I probably have the model too tightly coupled to the GUI framework, and so I will not be able to easily switch from WPF to some other. </p>

<p>In my unit tests, if I try to use a function which uses StringTable.xaml, I noticed any one of three errors:</p>

<blockquote>
  <p>System.Windows.ResourceReferenceKeyNotFoundException: 'PLACEHOLDER_TEXT' resource not found.</p>
</blockquote>

<p>or </p>

<blockquote>
  <p>Null pointer exception when I try to use the variable foobar</p>
</blockquote>

<p>or </p>

<blockquote>
  <p>Casting / Conversion error when trying to cast the unfound resource to string with (string)Application.Current.FindResource(""PLACEHOLDER_TEXT"");</p>
</blockquote>

<p>For clarification, StringTable.xaml is added as a merged dictionary within my App.xaml file: </p>

<pre><code>  &lt;Application.Resources&gt;
        &lt;ResourceDictionary&gt;
            &lt;ResourceDictionary.MergedDictionaries&gt;
                &lt;ResourceDictionary Source=""PlaceholderNamespace/SomeStyles.xaml""/&gt;
                &lt;ResourceDictionary Source=""PlaceholderNamespace/NumberTable.xaml""/&gt;
                &lt;ResourceDictionary Source=""PlaceholderNamespace/StringTable.xaml""/&gt;
            &lt;/ResourceDictionary.MergedDictionaries&gt;
        &lt;/ResourceDictionary&gt;
  &lt;/Application.Resources&gt;
</code></pre>

<p>I have followed <a href=""https://stackoverflow.com/questions/9121191/how-to-make-unit-tests-aware-of-application-resources"">Wesley's</a> post in a similar Stack Overflow and added (code snippet exactly duplicated):</p>

<pre><code>var app = new App(); //magically sets Application.Current
app.InitializeComponent(); //parses the app.xaml and loads the resources
</code></pre>

<p>to the top of my tests. This works well when running one unit test at a time. If I try to run multiple unit tests sequentially, however, I recieve the error:</p>

<blockquote>
  <p>Cannot create more than one System.Windows.Application instance in the same AppDomain</p>
</blockquote>

<p>Thus, I have to run each unit test. One. At. A. Time. This is annoying, so I will either start shoving all of my testing code into as few tests as possible (which kind of defeats the purpose), or run them less frequently than I should because it takes so long to get thru my test suite (which kind of defeats the purpose). If I only have it at the top of the first unit test in a sequence, I noticed the previously stated errors. This implies that the resources seemed to unload after the first test. But the AppDomain is still there. </p>

<p>I use MSTest, but have read that <a href=""https://social.msdn.microsoft.com/Forums/vstudio/en-US/226392e9-20bf-41a4-abf7-20c0348f44e6/testing-a-wpf-application-using-nunit-causes-quotsysteminvalidoperationexception-cannot-create?forum=wpf"" rel=""nofollow noreferrer"">NUnit</a> <a href=""https://stackoverflow.com/questions/9634438/run-unit-tests-in-different-appdomain-with-nunit"">also</a> suffers the same issue of not creating new app domains. <a href=""https://stackoverflow.com/questions/9634438/run-unit-tests-in-different-appdomain-with-nunit"">Jeremy Wiebe's</a> answer to a Stack Overflow about MSTest mentions that creating a new AppDomain is expensive. This would answer why it is not created more than once, but not how to get around this for my case. </p>

<p>Interestingly, I actually see the first test succeed while the second one is processing. When both tests complete, they will both fail. It's as if a test can retroactively fail because the app domain tried to change. </p>

<p>Anyone know how I can load all the StringTable.xaml resources into Application.Current, and have it persist through all unit tests in a sequence?</p>
",https://stackoverflow.com/questions/54333913/xaml-resources-like-a-string-table-in-wpf-unit-testing,"['wpf', 'unit-testing', 'mstest']",901,True,0,1
React Component Typescript: Error while unit testing react typescript component,"<p>I am trying to write unit test code of a react component written in typescript. I am getting the below issue. When I am trying to test using jest and enzyme. Can anyone. Please, help in writing it as I am new to testing.</p>

<blockquote>
  <p>Argument of type 'LoginComponent' is not assignable to parameter of
  type 'ReactElement
  ReactElement Component)> | null) | (new (props: any) => Component)>'.</p>
</blockquote>

<p>Did lot of search. But was not able to find the proper solution. Still I am getting the same error.</p>
",https://stackoverflow.com/questions/57198858/react-component-typescript-error-while-unit-testing-react-typescript-component,"['javascript', 'reactjs', 'typescript', 'jestjs', 'enzyme']",54,False,0,0
Unit testing - Getting issue with Alert Controller in Ionic Framework,"<p>I am trying to write a testcase for a method which has been called or not. Inside that method, I am calling an alert confirmation box. </p>

<p>I am getting an error like </p>

<blockquote>
  <p>Failed: this.alertCtrl.create is not a function</p>
</blockquote>

Component.ts

<pre><code>submitTicket(comments) {
if (comments.length &gt; 0) {
  const prompt = this.alertCtrl.create({
    title: ""&lt;span&gt;  Improve Solution  &lt;/span&gt;"",
    message: ""&lt;span&gt;"" + 'Are you sure you want  &lt;br&gt;' + ""&lt;/span&gt;"" +
      ""&lt;span&gt;"" + 'to submit this improvement' + ""&lt;/span&gt;"",
    enableBackdropDismiss: false,
    buttons: [
      {
        text: 'Cancel',
        handler: data =&gt; {
          // Some stuff
        }            
      },
      {
        text: 'Improve Solution',
        handler: data =&gt; {
         //Some stuff
        }
      }
    ]
  });
  prompt.present();
} else {
  this.errorMsg = true;
}
}
</code></pre>

component.spec.ts

<pre><code>import {AlertControllerMock } from 'ionic-mocks';

beforeEach(async(()=&gt; {
TestBed.configureTestingModule({
    declarations: [ImprovedsolutionsPage],
    imports: [
        IonicModule.forRoot(ImprovedsolutionsPage),
        HttpClientTestingModule
    ],
    providers: [
        NavController,
        AppService,
        AlertController,
        ImprovedsolutionsPage,
        {provide: ViewController, useClass: ViewControllerMock},
        {provide: LoadingController, useClass: LoadingControllerMock},
        {provide: AlertController, useClass: AlertControllerMock},          
    ]
}).compileComponents
}))
beforeEach(()=&gt; {
    fixture=TestBed.createComponent(ImprovedsolutionsPage)
    component=fixture.componentInstance
   fixture.detectChanges()
})

it('should be call submitTicket method', async(()= &gt; {
spyOn(component, 'submitTicket').and.callThrough()

let comment='Needs to improve in detailing '
component.submitTicket(comment)
expect(component.submitTicket).toHaveBeenCalled()

}))
</code></pre>

<p>Here I am using ionic-mocks module and I imported AlertControllerMock as shown in the above code. And I am using ionic version 3. For testing I am using Karma and jasmine</p>

<p>Could someone please help me out in this issue. </p>
",https://stackoverflow.com/questions/56446872/unit-testing-getting-issue-with-alert-controller-in-ionic-framework,"['ionic-framework', 'jasmine', 'karma-runner']",1625,True,0,1
Xamarin.Forms - Unit Testing a method that uses ServiceLocator from Autofac,"<p>I am trying to unit test a method in my <code>MyViewModel</code> which extends from <code>BaseViewModel</code>.  The <code>BaseViewModel</code> has a method like this</p>

<pre><code>protected bool DoSomething()
{
   if (something)
   {
      ServiceLocator.Current.GetInstance ...; //ERROR
      return true;
   }
   else
   {
      return false;
   }
}
</code></pre>

<p><code>DoSomething</code> is called pretty much in every view model.  The app works as expected but I am trying to unit test (NUnit) and every method that calls <code>DoSomething</code> is failing in unit tests</p>

<p>The error I get is</p>

<pre><code>error CS0119: 'ServiceLocator' is a type, which is not valid in the given context
</code></pre>

<p>The <code>ServiceLocator</code> is coming from <code>Autofac.CommonServiceLocator</code></p>
",https://stackoverflow.com/questions/54392566/xamarin-forms-unit-testing-a-method-that-uses-servicelocator-from-autofac,"['unit-testing', 'xamarin.forms', 'nunit', 'autofac', 'service-locator']",147,False,0,0
Rxjava 2 on error is not called while unit testing,"<p>Rxjava 2 on error is not called while unit testing . I am using kotlin with rxJava 2 .</p>

<blockquote>
  <p>method</p>
</blockquote>

<pre><code>  @SuppressLint(""CheckResult"")
    override fun fetchFilms() {
        view.showLoader(true)
        disposable = getRetrofitInstance(false).create(API::class.java)
                .fetchFilms()
                .subscribeOn(io)
                .observeOn(main)
                .subscribeWith(object : DisposableObserver&lt;Response&gt;() {
                    override fun onComplete() {
                    }

                    override fun onNext(t: Response) {
                        println(t)
                        view.setAdapter(t?.results as List&lt;ResultsItem&gt;)
                        view.showLoader(false)
                    }

                    override fun onError(e: Throwable) {
                        e.printStackTrace()
                        view.showLoader(false)
                        view.showError(e.message.toString())                    }

                })


    }
</code></pre>

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

<pre><code>@Test
    fun  fetchInvalidDataShouldThrowError(){

        `when`(api.fetchFilms()).thenReturn(Observable.error(IOException()))
   filmsPresenter.fetchFilms()
        val subscriber = TestSubscriber&lt;Response&gt;()

        subscriber.awaitTerminalEvent(5,TimeUnit.SECONDS)

        verify(filmsView, times(1)).showLoader(true)
        verify(filmsView).showError(""t"")
        verify(filmsView).showLoader(false)


    }
</code></pre>
",https://stackoverflow.com/questions/55135379/rxjava-2-on-error-is-not-called-while-unit-testing,"['android', 'kotlin', 'junit']",2429,True,0,3
Async await Node.js Unit Testing code using Chai and mocha,"<p>I'm quite new to node and express. And have been trying to write test code using mocha, chai. Here's the part of the source code.</p>

<p><strong>googleService.js:</strong></p>

<pre><code>const axios = require('./axios');

exports.hitGoogle = async (requestUrl, payload) =&gt; {
  let response = {};
  await axios.post(`${requestUrl}`, payload)
    .then((resp) =&gt; {
      response = resp;
      console.log(response);
    })
    .catch((err) =&gt; {
      console.error(err);
    });
  return response;
};
</code></pre>

<p><strong>readGoogle.js</strong></p>

<pre><code>const googleService = require('./googleService');

exports.execute = async (data) =&gt; {
  console.log(`data ${JSON.stringify(data)}`);
  console.log(`Name ${data.name}`);
  console.log(`Salary ${data.salary}`);
  console.log(`Age ${data.age}`);
  const payload = { name: data.name, salary: data.salary, age: data.age };

  await googleService.hitGoogle('http://dummy.restapiexample.com/api/v1/create', payload)
    .then((response) =&gt; {
      if (response.status === 200 || response.status === 201) {
        console.log(response.status);
        return true;
      }
      return false;
    })
    .catch((err) =&gt; {
      console.log(err);
    });
  return true;
};
</code></pre>

<p><strong>And here is my unit test file:</strong></p>

<pre><code>const readGoogle = require('./readGoogle');

const jmsPayload = { age: '23', name: 'test', salary: '123' };

describe('Google ', () =&gt; {
  it('POST: Google.', async () =&gt; {
     readGoogle.execute(jmsPayload).then((result) =&gt; {
     results = result;
    console.log(`Final Result : ${results.toString()}`);
  });
});
</code></pre>

<p>When I execute this test file, post is successful ,</p>

<pre><code>hitGoogle url=http://dummy.restapiexample.com/api/v1/create
hitGoogle payload=[object Object]
{ status: 200,
  statusText: 'OK',
</code></pre>

<p>Input values passed from test class to readGoogle.js is also read inside that,</p>

<pre><code>data {""age"":""23"",""name"":""test"",""salary"":""123""}
Name test
Salary 123
Age 23

**But I am getting Promise as output.** 

**SO I have rendered the promised value to a normal string and getting 'true' as final output.**
</code></pre>

<p>Also,</p>

<ul>
<li><p>1)Is this is the right way of testing the async-await module?</p>

<p>2) Do we need to add anything else in this test code like Settimeout
or beforeEach or afterEach blocks?</p>

<p>3) Do we need to use Sinon for spying or adding a stub to 'payload'
in googleService.js?</p></li>
</ul>

<p>Can anyone help or suggest me the right path?</p>

<p>Tried async way for executing test cases one by one in order as below,</p>

<pre><code>const readGoogle = require('./readGoogle');

const jmsPayload = { age: '23', name: 'test', salary: '123' };

const common = require('./common');
const chaiHttp = common.chaiHttp;
common.chai.use(chaiHttp);

describe('Google ', () =&gt; {
  common.mocha.before((done) =&gt; {
    // Wait for the server to start up
    setTimeout(() =&gt; {
      done();
    }, 1000);
  });

  it('POST: Google.', async () =&gt; {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () =&gt; {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
    setTimeout(() =&gt; {
    }, 1000);
  });
  it('POST: Google.', async () =&gt; {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () =&gt; {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () =&gt; {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () =&gt; {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () =&gt; {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
});
</code></pre>

<p>But then I am getting,</p>

<p><strong>Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure ""done()"" is called; if returning a Promise, ensure it resolves</strong></p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/58668318/async-await-node-js-unit-testing-code-using-chai-and-mocha,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'chai']",1303,True,0,1
Unit testing a service class with dependency on httpclient response,"<p>I have a service-class that gets a <code>FlurlHttpClient</code> injected in the constructor.</p>

<p>It has a public method which makes a call using the <code>httpClient</code> and then parses the response and returns a class. So basically I want to fake the response from the API and test the parse-method, which is private.</p>

<p>How do I unit test this? I am using NUnit and FakeItEasy for testing. So far I got this, but how do I ensure that the <code>ParseResult</code>-method gets tested with the faked result from the API?</p>

<p>Code so far:</p>

<p>Unit-test:</p>

<pre><code>[Test]
public void GetShipmentData_SuccessfullTracking_ReturnsValidEntity() {
  //Fake the service-class
  var sut = A.Fake&lt;IApiClient&gt;();
  using (var httpTest = new HttpTest()) {
    httpTest.RespondWithJson(GetJsonFromFile(""../../../Assets/SuccessfullApiTrackingResponse.json""), 200);

    //This does not actually run the function on the service-class.
    var response = sut.TrackShipmentUsingReferenceNumber(""fakeReferenceNumber"");

    Assert.IsTrue(response.SuccessfullShipmentTracking);
    Assert.IsNotNull(response.ApiResponseActivity);
  }
}
</code></pre>

<p>Api-class:</p>

<pre><code>public class ApiClient : IApiClient {

    readonly ILogger _logger;
    private readonly IFlurlClient _httpClient;

    public ApiClient(IFlurlClientFactory flurlClientFac) {
      _httpClient = flurlClientFac.Get(ApiClientConfiguration.BaseAdress);
    }

    public ApiResponse TrackShipmentUsingReferenceNumber(string referenceNumber) {
      var request = GenerateApiRequestUsingReferenceNumber(referenceNumber);
      var response = _httpClient.Request(""Track"").PostJsonAsync(request).ReceiveString();

      return ParseResult(response.Result);
    }

    private ApiResponse ParseResult(string input) {
        //Shortened
      return = JObject.Parse&lt;ApiResponse&gt;(input);
    }
}
</code></pre>
",https://stackoverflow.com/questions/57823167/unit-testing-a-service-class-with-dependency-on-httpclient-response,"['c#', '.net', 'nunit', 'fakeiteasy', 'flurl']",584,True,0,1
Unit Testing a method that creates a table with indexes,"<p>I created this fake db for the test, but i don't know how to continue from here. I know that i need to create expected scenarios with yield return and compare the results with expected resulsts and so forth but i can't figure out how to start, I just need a starting point. This is all new to me , so apologies from everyone if this is a dumb question.</p>

<pre class=""lang-cs prettyprint-override""><code>public class IndexTests : DataAccessFixture
{
    [Test]
    public void CreateTableWithIndex()
    {
        var db = this.database.Create();
        var table = db.DefineTable(""IndexedTable"");

        table.Columns.Add(""Id"", FieldType.Guid, false, true);
        table.Columns.Add(""CustomerNumber"", FieldType.VarChar, 50);
        table.Columns.Add(""Name"", FieldType.VarChar, 50);

        table.Indices.Add(""IX_Name"", false, ""Name"");
        table.Indices.Add(""IX_CustomerNumber"", true, ""CustomerNumber"");

        db.Execute();

        this.database.DropTable(table.Name);
    }
}
</code></pre>
",https://stackoverflow.com/questions/58743179/unit-testing-a-method-that-creates-a-table-with-indexes,"['c#', 'sql', 'unit-testing', 'nunit']",441,True,-1,1
angular unit testing a component with an http service call,"<p>First of all, I am new to angular testing, so please bear that in mind.
I have a component which invokes a service in the <strong>ngOnInit</strong> method. The method looks like this:</p>

<pre><code>ngOnInit() {
    this.selectorService.category.subscribe(category =&gt; {
        if (!category) return;

        this.fieldService.list(category, false).subscribe(fields =&gt; {
            let rangeFields = fields.filter(field =&gt; !field.isSpecification);
            let specificationFields = fields.filter(field =&gt; field.isSpecification);

            this.fields = specificationFields;

            this.productService.listValidatedRangeProducts(category).subscribe(range =&gt; {
                if (!range.length) return;
                this.products = range;
                this.range = this.productModelService.mapProducts(rangeFields, range);
                this.saveForm = this.toFormGroup(range[0]);
            });
        });
    });
}

private toFormGroup(product: any): FormGroup {
    let group: any = {};

    this.fields.forEach(field =&gt; {
        group[field.name] = new FormControl(product[field.name]);
    });

    return new FormGroup(group);
}
</code></pre>

<p>I already have the tests for each service setup and working. Now I want to write tests for this component. I tried this:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientTestingModule } from '@angular/common/http/testing';

import { SharedModule } from '@shared';
import { SpecificationsSaveComponent } from './specifications-save.component';
import { ToastrModule, ToastrService } from 'ngx-toastr';

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

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [ReactiveFormsModule, HttpClientTestingModule, SharedModule, ToastrModule.forRoot()],
            declarations: [SpecificationsSaveComponent],
            providers: [ToastrService],
        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(SpecificationsSaveComponent);
        component = fixture.componentInstance;
        component.range = [
            {
                gtin: 0,
            },
            {
                gtin: 1,
            },
        ];

        component.fields = [
            {
                id: 0,
                canCopy: false,
                categoryId: 'cameras',
                dataType: 0,
                display: false,
                isSpecification: true,
                name: 'gtin',
                order: 0,
                required: true,
            },
        ];
        fixture.detectChanges();
    });

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

    it('should save and get next', () =&gt; {
        expect(component.saveForm.controls['gtin'].value).toBe(1);
    });

    it('should save and get reset', () =&gt; {
        expect(component.saveForm.controls['gtin'].value).toBeNull();
    });
});
</code></pre>

<p>Basically I tried to set the public properties but it doesn't work. I get this error:</p>

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

<p>Which I suspect is because there is a getter which looks like this:</p>

<pre><code>// convenience getter for easy access to form fields
get f() {
    return this.saveForm.controls;
}
</code></pre>

<p><strong>saveForm</strong> should be created in the <strong>ngOnInit</strong> method as you can see from this line:</p>

<pre><code>this.saveForm = this.toFormGroup(range[0]);
</code></pre>

<p>So, it looks like what I need to do is mock up the <strong>selectorService</strong>, <strong>fieldService</strong> and <strong>productService</strong> before I can continue.
Can someone show me how to do that?</p>

<p>Here is the full component:</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

import { Field } from '@models';
import { SelectorService, ProductModelService } from '@core';
import { ProductService, FieldService } from '@services';

@Component({
    selector: 'app-specifications-save',
    templateUrl: './specifications-save.component.html',
    styleUrls: ['./specifications-save.component.scss'],
})
export class SpecificationsSaveComponent implements OnInit {
    range: any[];
    saveForm: FormGroup;
    fields: Field[];
    submitted: boolean = false;

    private products: any[];

    constructor(
        private fieldService: FieldService,
        private productModelService: ProductModelService,
        private productService: ProductService,
        private selectorService: SelectorService,
    ) {}

    ngOnInit() {
        this.selectorService.category.subscribe(category =&gt; {
            if (!category) return;

            this.fieldService.list(category, false).subscribe(fields =&gt; {
                let rangeFields = fields.filter(field =&gt; !field.isSpecification);
                let specificationFields = fields.filter(field =&gt; field.isSpecification);

                this.fields = specificationFields;

                this.productService.listValidatedRangeProducts(category).subscribe(range =&gt; {
                    if (!range.length) return;
                    this.products = range;
                    this.range = this.productModelService.mapProducts(rangeFields, range);
                    this.saveForm = this.toFormGroup(range[0]);
                });
            });
        });
    }

    // convenience getter for easy access to form fields
    get f() {
        return this.saveForm.controls;
    }

    onSubmit(): void {
        this.submitted = true;

        if (this.saveForm.invalid) {
            return;
        }

        let categoryId = this.fields[0].categoryId;
        let product = {
            categoryId: categoryId,
        };

        let valid = true;
        this.fields.forEach(field =&gt; {
            let value = this.f[field.name].value;
            if (valid) {
                valid = !!value;
            }
            product[field.name] = value;
        });

        console.log(this.fields);
        console.log(product);
        console.log(valid);

        // TODO: save the product

        if (valid) {
            let gtin = product['gtin'];
            let index = 0;

            this.range.forEach((item, i) =&gt; {
                if (item.gtin !== gtin) return;
                index = i;
            });

            console.log(gtin);
            console.log(index);

            this.saveForm = this.toFormGroup(this.range[index + 1]);
            this.range.splice(index, 1);
        }

        // TODO: reset the form
    }

    private toFormGroup(product: any): FormGroup {
        let group: any = {};

        this.fields.forEach(field =&gt; {
            group[field.name] = new FormControl(product[field.name]);
        });

        return new FormGroup(group);
    }
}
</code></pre>
",https://stackoverflow.com/questions/58690987/angular-unit-testing-a-component-with-an-http-service-call,"['angular', 'unit-testing']",37,True,0,1
Class Validator error in Php Unit Testing in Laravel 5.5,"<p>I am working on phpUnit test in laravel 5.5. When I am trying to test the method on controller with 2 different methods by creating request object and pass it as a parameter, I am getting same error but It is working fine when I am testing on Postman</p>

<blockquote>
  <p>""ReflectionException: Class validator does not exist
  /src/vendor/laravel/framework/src/Illuminate/Container/Container.php:752 /src/vendor/laravel/framework/src/Illuminate/Container/Container.php:631 /src/vendor/laravel/framework/src/Illuminate/Container/Container.php:586 /src/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:732 /src/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:110 /src/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php:96 /src/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php:44""</p>
</blockquote>

<p>Two method of writing test cases</p>

<p>1) </p>

<pre><code>$response = $this-&gt;withHeaders([ 'Content-type' =&gt; 'application/json' ])-&gt;json('POST', '/account', $jsonArr);
</code></pre>

<p>2) </p>

<pre><code>$request = Request::create('/account', 'POST', $jsonArr); 
   $request-&gt;headers-&gt;set('Content-type', 'application/json'); 
   $controller = new AccountController;
   $response = $controller-&gt;create($request);
</code></pre>

<p>My Code:</p>

<p>********************AccountController.php**********************************</p>

<pre><code>&lt;?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Validator;
use App\Models\Account;

class AccountController extends Controller
{
    public function create(Request $request)
        {
        $this-&gt;validate($request, $this-&gt;rules());          
        $service_name = ""seller-registration-accepted"";
        $id_array = array();
        $link_array = array();
        $account = new Account;
        $account-&gt;id = $account_id;
        $account-&gt;company_name = $request-&gt;company_name;
        $account-&gt;email = $request-&gt;email;
        $account-&gt;phone = $request-&gt;phone;
        $account-&gt;address = $request-&gt;address;
        $account-&gt;language = $request-&gt;language;
        $account-&gt;account_type_id = 5;
        $this-&gt;insertCompanyDescription($request, $account_id);
        $customerRes = PaymentGatewayUtil::createCustomer();
        if (((json_decode($customerRes))-&gt;status == ""success"")) {
            $customer = new Customer;
            $customer-&gt;account_id = $account_id;
            $customer-&gt;id =  ((json_decode($customerRes))-&gt;data)-&gt;customer_id;
            $customer-&gt;save();
        }
        return JSendResponse::success(['message' =&gt;
        'Seller registration accepted successfully, seller account created.',
        'id' =&gt; $account-&gt;id]);
    }

    private function rules()
    {
        return [
            'company_name' =&gt; 'sometimes',
            'email' =&gt; 'required|email',
            'phone' =&gt; 'required',
            'language' =&gt; 'required',
            'account_type' =&gt; 'required',
            'translations' =&gt; 'sometimes',
            'translations.*.company_description' =&gt; 'required',
            'translations.*.locale' =&gt; 'required',
            'website_link' =&gt; 'sometimes|URL'
        ];
    }

} 
</code></pre>

<p>**************************AccountControllerTest.php*********************</p>

<pre><code>&lt;?php
namespace Tests\Feature;

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\AccountController;
use Exception;

class AccountControllerTest extends TestCase
{
    public function testCreateTest()
    {
        $uniqueEmailAddress = ""test_"".rand(1000, 9999).""@gmail.com"";
        $jsonArr = array();
        $jsonArr['email'] = $uniqueEmailAddress;
        $jsonArr['company_name'] = ""test_47"";
        $jsonArr['address'] = ""XYZ"";
        $jsonArr['service_type'] = 'partner';
        $jsonArr['account_type'] = 'seller';
        $jsonArr['language'] = 'en';
        $jsonArr['phone'] = '00000000000';
        $response =  $this-&gt;withHeaders([
              'Content-type' =&gt; 'application/json'
         ])-&gt;json('POST', '/account', $jsonArr);
    }



    public function testCreateTest2()
    {
        $uniqueEmailAddress = ""test2_"".rand(1000, 9999).""@gmail.com"";
        $jsonArr = array();
        $jsonArr['email'] = $uniqueEmailAddress;
        $jsonArr['company_name'] = ""test_23"";
        $jsonArr['address'] = ""XYU"";
        $jsonArr['service_type'] = 'partner';
        $jsonArr['account_type'] = 'seller';
        $jsonArr['language'] = 'en';
        $jsonArr['phone'] = '00000000000';


        $request = $this-&gt;convertToRequest($jsonArr);
        $request = Request::create('/account', 'POST', $jsonArr);
        $request-&gt;headers-&gt;set('Content-type', 'application/json');
        $controller = new AccountController;
        $response = $controller-&gt;create($request);
        }
    } 
</code></pre>

<p>**********************routes/api.php***********************</p>

<pre><code>&lt;?php


Route::post('/account', 'AccountController@create'); 
</code></pre>
",https://stackoverflow.com/questions/58511564/class-validator-error-in-php-unit-testing-in-laravel-5-5,"['php', 'laravel', 'phpunit']",520,False,0,1
Cake3 Fixtures not being built during unit testing cake plugin,"<p>I have a cakephp 3.7 plugin as its own stand-alone project. But am encountering the failures below when running unit tests. It seems after moving this outside of a parent project, the fixtures are no longer being built. Not sure how to instruct cake to build them.</p>

<blockquote>
  <p>Cake\Database\Exception: Cannot describe teams. It has 0 columns.</p>
</blockquote>

<p>Here is my <code>tests/bootstrap file</code>. These tests were previously working until I decided to move this plugin out of the parent project.</p>

<pre><code>&lt;?php
$findRoot = function ($root) {
    do {
        $lastRoot = $root;
        $root = dirname($root);
        if (is_dir($root . '/vendor/cakephp/cakephp')) {
            return $root;
        }
    } while ($root !== $lastRoot);
    throw new Exception(""Cannot find the root of the application, unable to run tests"");
};
$root = $findRoot(__FILE__);
unset($findRoot);
chdir($root);

if (!defined('DS')) {
    define('DS', DIRECTORY_SEPARATOR);
}

define('ROOT', $root);
define('APP_DIR', 'App');
define('WEBROOT_DIR', 'webroot');
define('APP', ROOT . '/tests/');
define('CONFIG', ROOT . '/tests/config/');
define('WWW_ROOT', ROOT . DS . WEBROOT_DIR . DS);
define('TESTS', ROOT . DS . 'tests' . DS);
define('TMP', ROOT . DS . 'tmp' . DS);
define('LOGS', TMP . 'logs' . DS);
define('CACHE', TMP . 'cache' . DS);
define('CAKE_CORE_INCLUDE_PATH', ROOT . '/vendor/cakephp/cakephp');
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
define('CAKE', CORE_PATH . 'src' . DS);

require_once ROOT . '/vendor/cakephp/cakephp/src/basics.php';
require ROOT . '/vendor/autoload.php';

use Cake\Core\Configure;
use Cake\Core\Configure\Engine\PhpConfig;

try {
    Configure::config('default', new PhpConfig());
    Configure::load('app', 'default', false);
} catch (\Exception $e) {
    exit($e-&gt;getMessage() . ""\n"");
}

$TMP = new \Cake\Filesystem\Folder(TMP);
$TMP-&gt;create(TMP . 'cache/models', 0777);
$TMP-&gt;create(TMP . 'cache/persistent', 0777);
$TMP-&gt;create(TMP . 'cache/views', 0777);

$cache = [
    'default' =&gt; [
        'engine' =&gt; 'File',
    ],
    '_cake_core_' =&gt; [
        'className' =&gt; 'File',
        'prefix' =&gt; '_cake_core_',
        'path' =&gt; CACHE . 'persistent/',
        'serialize' =&gt; true,
        'duration' =&gt; '+10 seconds',
    ],
    '_cake_model_' =&gt; [
        'className' =&gt; 'File',
        'prefix' =&gt; '_cake_model_',
        'path' =&gt; CACHE . 'models/',
        'serialize' =&gt; 'File',
        'duration' =&gt; '+10 seconds',
    ],
    '_cake_method_' =&gt; [
        'className' =&gt; 'File',
        'prefix' =&gt; '_cake_method_',
        'path' =&gt; CACHE . 'models/',
        'serialize' =&gt; 'File',
        'duration' =&gt; '+10 seconds',
    ],
];

Cake\Cache\Cache::setConfig($cache);

if (file_exists($root . '/config/bootstrap.php')) {
    require $root . '/config/bootstrap.php';
}

if (!getenv('db_dsn')) {
    putenv('db_dsn=sqlite:///:memory:');
}

Cake\Datasource\ConnectionManager::setConfig('test', [
    'url' =&gt; getenv('db_dsn'),
    'timezone' =&gt; 'UTC'
]);
</code></pre>

<p>phpunit.xml</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;phpunit
    colors=""true""
    stopOnFailure=""false""
    bootstrap=""./tests/bootstrap.php""
    &gt;
    &lt;php&gt;
        &lt;ini name=""memory_limit"" value=""-1""/&gt;
        &lt;ini name=""apc.enable_cli"" value=""1""/&gt;
    &lt;/php&gt;

    &lt;!-- Add any additional test suites you want to run here --&gt;
    &lt;testsuites&gt;
        &lt;testsuite name=""YummySearch Test Suite""&gt;
            &lt;directory&gt;./tests/TestCase&lt;/directory&gt;
        &lt;/testsuite&gt;
    &lt;/testsuites&gt;

    &lt;!-- configure code coverage --&gt;
    &lt;filter&gt;
        &lt;whitelist&gt;
            &lt;directory suffix="".php""&gt;./src/&lt;/directory&gt;
        &lt;/whitelist&gt;
    &lt;/filter&gt;

    &lt;!-- Setup a listener for fixtures --&gt;
    &lt;listeners&gt;
        &lt;listener
                class=""Cake\TestSuite\Fixture\FixtureInjector""&gt;
            &lt;arguments&gt;
                &lt;object class=""Cake\TestSuite\Fixture\FixtureManager"" /&gt;
            &lt;/arguments&gt;
        &lt;/listener&gt;
    &lt;/listeners&gt;
&lt;/phpunit&gt;
</code></pre>
",https://stackoverflow.com/questions/57761037/cake3-fixtures-not-being-built-during-unit-testing-cake-plugin,"['phpunit', 'cakephp-3.0']",156,False,0,0
Unit Testing JavaScript in ASP.NET MVC with Jasmine and Karma,"<p>I am writing a sample ASP .NET MVC application, which has karma and requirejs to test the scripts. I see below error <strong>Uncaught (in promise) Error: No tests were run.</strong></p>

<p>I see below error in command prompt
<strong>Chrome 77.0.3865 (Windows 10.0.0): Executed 0 of 0 ERROR (0.012 secs / 0 secs)</strong></p>

<p>Package.json</p>

<pre><code>{
  ""name"": ""karmawebapp"",
  ""version"": ""1.0.0"",
  ""description"": ""test application for karma tests"",
  ""main"": ""index.js"",
  ""scripts"": {
    ""test"": ""karma start""
  },
  ""author"": """",
  ""license"": ""ISC"",
  ""devDependencies"": {
    ""babel-core"": ""^6.26.3"",
    ""babel-preset-es2015"": ""^6.24.1"",
    ""karma"": ""^4.3.0"",
    ""karma-chrome-launcher"": ""^3.1.0"",
    ""karma-qunit"": ""^4.0.0"",
    ""karma-requirejs"": ""^1.1.0"",
    ""protractor"": ""^5.4.2"",
    ""qunit"": ""^2.9.3"",
    ""requirejs"": ""^2.3.6""
  }
}
</code></pre>

<p>My karma.conf.js</p>

<pre><code>// Karma configuration
// Generated on Tue Oct 15 2019 13:51:47 GMT-0500 (Central Daylight Time)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
      frameworks: ['requirejs', 'qunit'],


    // list of files / patterns to load in the browser
    files: [
      'test-main.js',
      { pattern: './Scripts/tests/*.specs.js', included: false }
    ],


    // list of files / patterns to exclude
    exclude: [
    ],

// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},


// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],


// web server port
port: 9876,


// enable / disable colors in the output (reporters and logs)
colors: true,


// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,


// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,


// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],


// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,

// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
</code></pre>

<p>})
}</p>

<p><strong>My test-main.js</strong></p>

<pre><code>var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;

// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function(file) {
    if (TEST_REGEXP.test(file)) {
        // Normalize paths to RequireJS module names.
        // If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
        // then do not normalize the paths
        var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
        allTestFiles.push(normalizedTestModule)
    };
});

require.config({
    // Karma serves files under /base, which is the basePath from your config file
    baseUrl: '/base',

    // dynamically load all test files
    deps: allTestFiles,

    path: {
        qunit: 'qunit',
        jquery: 'jquery.3.3.1'
    },

    // we have to kickoff jasmine, as it is asynchronous
    callback: window.__karma__.start
});
</code></pre>

<p><strong>my test.specs.js</strong></p>

<pre><code>define(['qunit'], function (qunit) {

    qunit.test(""Second test"", function (assert) {
        assert.ok(true, ""Passed!"");
    });
});
</code></pre>
",https://stackoverflow.com/questions/58401245/unit-testing-javascript-in-asp-net-mvc-with-jasmine-and-karma,"['asp.net-mvc', 'testing', 'karma-runner', 'karma-qunit']",794,True,0,2
Unit testing a public method that calls multiple private methods,"<p>I want to test a public method that calls multiple private methods. What I read from all the answers to previously asked questions are varying. Some say if one encounters such situation, then probably the structure is wrong, or methods that call other methods without any logic should not be tested, etc. </p>

<p>What is not clear for me is that, should I mock these private methods (using PowerMock or any reflection based library) and unit test just this method, or should I provide different types of inputs, so that all the cases will be tested, but private methods will be invoked as well. In the latter case, is it gonna be unit testing still, since I will call other methods, as well.</p>

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

    public void publicMethod (Argument argument) {
        try {
            privateMethod1();

            privateMethod2(argument);

            privateMethod3();
        } catch (Exception ex) {
            privateMethod4();
        }
    }

}
</code></pre>
",https://stackoverflow.com/questions/56660602/unit-testing-a-public-method-that-calls-multiple-private-methods,"['java', 'unit-testing', 'junit']",1151,True,0,1
Mocking a Context.ConnectionId for Unit Testing Signalr .NetCore Messaging Hubs,"<p>My question is regarding getting a context.connection ID value to insert into one of my methods when i'm unit testing my Signalr hubs in .Net CORE. My method looks like this in my test class:</p>
<pre class=""lang-cs prettyprint-override""><code>
    [Fact]
    public async Task TestWorkstationCreation()
    {
        Mock&lt;IHubCallerClients&lt;IWorkstation&gt;&gt; mockClients = new Mock&lt;IHubCallerClients&lt;IWorkstation&gt;&gt;();
        Mock&lt;IWorkstation&gt; mockClientProxy = new Mock&lt;IWorkstation&gt;();
        mockClients.Setup(clients =&gt; clients.All).Returns(mockClientProxy.Object);
        _workstationHub.Clients = mockClients.Object;
        await _workstationHub.RegisterWorkstation(&quot;WKS16&quot;, &quot;Ready&quot;, new Dictionary&lt;string, string&gt; {{&quot;OS&quot;, &quot;Windows 10&quot;}, {&quot;Exam&quot;, &quot;GRE, TOEFL&quot;}});
        mockClientProxy.Verify(c =&gt; c.WorkstationRegistered(It.IsAny&lt;WorkstationDataModel&gt;(), It.IsAny&lt;string&gt;()), Times.AtLeastOnce);
    }
</code></pre>
<p>In my hub class, this is the method:</p>
<pre class=""lang-cs prettyprint-override""><code>    public async Task RegisterWorkstation(string id, string status, Dictionary&lt;string, string&gt; capabilities)
    {
        _logger.LogInformation(
            &quot;Registering a Workstation with id: {id}, status: {status}, and capabilities: {capabilities}&quot;,
            id, status, string.Join(&quot;,&quot;, capabilities));
        var workstationAdded = AddWorkstation(id, status, capabilities, Context.ConnectionId);
        var message = workstationAdded == null
            ? $&quot;A workstation with the id: {id} already exists!&quot;
            : $&quot;A workstation with the id: {id}, status: {status}, and capabilities: {string.Join(&quot;,&quot;, capabilities)} &quot; +
              &quot;was added to the current list of workstations available.&quot;;
        await Clients.All.WorkstationRegistered(workstationAdded, message);
    }
</code></pre>
<p>When testing, it throws an Object reference not set null pointer exception at Context.ConnectionId. Is there someway to mock a Context.Connection Id that can be used?</p>
",https://stackoverflow.com/questions/56871939/mocking-a-context-connectionid-for-unit-testing-signalr-netcore-messaging-hubs,"['asp.net-core', '.net-core', 'signalr', 'xunit', 'asp.net-core-signalr']",2004,True,0,1
How do I mock factory pattern to support unit testing?,"<p>I have two operations to be done. One is for <code>Air transport</code> and one for <code>Road transport</code>. both processes some <code>message</code>.</p>

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

<pre><code>   public interface IProcess
   {
        void Process(string message);
   }
</code></pre>

<p>Here is my implementation of <code>Road transport</code></p>

<pre><code>     public class RoadTransport: IProcess 
     {
         public void Process(string msg)
         {
             // do some road related operation
          }
     }
</code></pre>

<p>Here is my implementation of <code>Air transport</code></p>

<pre><code>     public class AirTransport: IProcess 
     {
         public void Process(string msg)
         {
             // do some air related operation
         }
     }
</code></pre>

<p>Now, I will show the factory class, which will return different objects based on  <code>ID</code></p>

<pre><code>   public class MyFactory
   {
        private readonly AirTransport airtransport = null;
        private readonly RoadTransport roadtransport = null;

        public MyFactory(AirTransport, RoadTransport)// dependency injected
        {
             airtransport =  AirTransport;
             roadtransport = RoadTransport;
        }
        IProcess process = null;
        public IProcess GetInstance(int id)
        {
              swicth(id)
              {
                    case ""1"":
                    process = airtransport;
                    break;

                    case ""2"":
                    process = roadtransport;
                    break; 
              }
             return process;
        }
   }
</code></pre>

<p>Here is my class which supposed to be tested</p>

<pre><code>  public class HomeController:Controller
  {
        private readonly MyFactory _myfactory;
        private readonly MyConfigurations _myConfigurations;

        public HomeController(MyFactory factory, MyConfigurations configurations)
        {
             _myfactory = factory;
        }

        public IActionResult Index()
        {
             return View();
        }

        Public ActionResult Process(string message, string id)
        {
            var configurations =  _myConfigurations;
            if(configurations!=null)
            {
               IProcess processor=  _myfactory.GetInstance(id);
               processor.Process(message);
               return View(""Index"");
            }
        }
  }
</code></pre>

<p>How do I unit test this controller, because there is no <code>interface</code> defined for <code>factor</code> class? do I have to <code>mock</code> the factory class or is it wrong design?</p>
",https://stackoverflow.com/questions/58215283/how-do-i-mock-factory-pattern-to-support-unit-testing,"['c#', 'unit-testing', 'dependency-injection', 'tdd']",2460,True,0,1
Proper approach to change a class functionality for unit testing?,"<p>I'm working on an old and large C++ codebase and I've been in the process of creating unit tests for components that have been missing them.</p>

<p>What's the proper way to mocking the functionality of these classes for testing purposes?  Currently I'm using virtual functions, and in my test module, I'm deriving a mock class from the base ""production"" class, and overriding functionality as needed.</p>

<p>Here's an example:</p>

<p>Production.cpp</p>

<pre><code>class Production {
protected:
    int Servers = 0;
public:

    virtual bool IsValInRegistry(const std::string&amp; regVal);
};

bool Production::IsValInRegistry(const std::string&amp; regVal)
{
    HRESULT hr = GOOD;
    hr = WinSysCallToRegistry(regVal);

    if (HR)
        return true;
    else
        return false;
}
</code></pre>

<p>Mock.cpp</p>

<pre><code>class Mock : public Production {
public:
    bool IsValInRegistry(const std::string&amp; regVal) override final;
};

Mock::IsValInRegistry(const std::string&amp; regVal)
{
    return true;
}
</code></pre>

<p>Is this a proper way forward?  I'm concerned if I introduce too many <code>virtual</code> functions, I may see a performance hit which I would like to avoid.  If this <code>virutal</code> model is not ideal, what's a good method?</p>
",https://stackoverflow.com/questions/54119739/proper-approach-to-change-a-class-functionality-for-unit-testing,"['c++', 'unit-testing']",278,False,-1,1
net core api controller unit testing using xunit and moq,"<p>i have some api controller methods that i would like to add some unit tests to. I am using xunit and moq and writing in c# using asp net core.</p>

<p>example of one method is:</p>

<pre><code>public async Task&lt;ActionResult&lt;List&lt;StatusDTO&gt;&gt;&gt; Get()
{
    return await _statusservice.GetStatusesAsync();
}
</code></pre>

<p>at this point in time my controller method is simply returning the dto that the service layer method is returning. In future it might change to return a specific viewmodel.</p>

<p>i have read <a href=""https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/testing?view=aspnetcore-2.2"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/testing?view=aspnetcore-2.2</a> to get some guidance on testing controllers.</p>

<p>My question is : for example above would the unit test just consist of 
- checking that the return type is <code>ActionResult&lt;StatusDTO&gt;</code> and/or (using moq) verifying the service method has been called. </p>

<p>Should i set up my service method to return a mock <code>StatusDTO</code> and do some assertions against that. I don't see benefit of that in this situation, as that would be testing the service method wouldn't it and i would cover that in the service method tests.</p>

<p>Sorry if this seems quite basic - my knowledge and experience in writing unit tests is very limited.
Thanks for any help.</p>
",https://stackoverflow.com/questions/57057857/net-core-api-controller-unit-testing-using-xunit-and-moq,"['unit-testing', 'asp.net-core', 'xunit']",686,True,-2,1
Angular Unit Testing: How to unit test subscription inside ngOnInIt()?,"<p>Component to be tested:</p>

<pre><code>export class ComponentDetailsComponent implements OnInit {
     ngOnInit() {

            this.componentDetailsService.currentProperties.subscribe((data) =&gt; {
                this.loader.hideLoader();    
                 this.showPopup = data.showPopup;
         .....more code....
    }
</code></pre>

<p><strong>Spec:</strong></p>

<pre><code>class ComponentDetailsServiceStub {
  defaultProperties ={       
    showToolbar: false,        
    showPopup: true, //show popup is set to true here       
    refresh: false,
  };

    propertiesSource = new BehaviorSubject(this.defaultProperties);
  currentProperties = this.propertiesSource.asObservable();

  setDefaultCancelClicked(){}
}


it('should set showPopup to correct value', () =&gt; {

    componentDetailsService.propertiesSource.next({         
      showToolbar: true,         
      showPopup: false, // show popup is set to false          
      refresh: false,

    }); 

    expect(subject.showPopup).toBe(true) ///this always passes

   });
</code></pre>
",https://stackoverflow.com/questions/56688964/angular-unit-testing-how-to-unit-test-subscription-inside-ngoninit,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",918,True,0,1
"Unit testing with Jest, expect problem receiving empty/undefined object","<p>i am new to unit testing and i am trying to test the length of a navigation bar, below you can see the nav bar component which is within a class</p>

<pre><code>&lt;AppBar className={classes.appBar} position=""static""&gt;
        &lt;Toolbar className={classes.toolbar}&gt;
            {authenticated &amp;&amp; this.state.layoutMode ==='desktop' ? (
                &lt;Grid container
                    direction =""row""
                    justify=""flex-end""
                    alignItems=""center""&gt;
                    &lt;div className={classes.root}&gt;
                        &lt;Tabs id=""Tab"" className = {classes.tabBar} value={value} onChange={this.handleChange}&gt;
                            &lt;Tab label=""example"" alt=""example"" onClick={() =&gt; Router.push('/example')}/&gt;
                            &lt;Tab label=""example"" alt=""example"" onClick={() =&gt; Router.push('/example')}/&gt;
                            &lt;Tab label=""example"" alt=""example"" onClick={() =&gt; Router.push('/example')}/&gt;
                            &lt;Tab label=""example"" alt=""example"" onClick={() =&gt; Router.push('/example')}/&gt;
                            &lt;Tab label=""example"" alt=""example"" onClick={() =&gt; Router.push('/example')}/&gt;
                            &lt;Tab label=""example"" alt=""example"" onClick={() =&gt; Router.push('/example')}/&gt;
                        &lt;/Tabs&gt;
                    &lt;/div&gt;
                &lt;/Grid&gt;
            ) : (
                authenticated &amp;&amp; &lt;BurgerMenu/&gt;
            )}
</code></pre>

<p>Below is the test i have written so far</p>

<pre><code>describe('NavBar', () =&gt; {
const intialState = {
    ui: { width: 1361 },
    auth: { authenticated: true }
}

let container;
beforeEach(() =&gt; {
    container = shallow(&lt;Nav /&gt;);
});

it('should render self and subcomponents', () =&gt; {
    expect(container).toMatchSnapshot();
});

it('should contain an AppBar', () =&gt; {
    console.log(container.find(AppBar));
    expect(container.find(AppBar)).toHaveLength(1);
});
</code></pre>

<p>})</p>

<p>however my problem is that the .find(AppBar) doesnt seem to be found, when using a console log(container.find(AppBar)) it shows the following ""ShallowWrapper {}"" this would mean that the object is empty and therefore not equal to 1, however i do not know where to point the find to correctly find the tabs to test</p>
",https://stackoverflow.com/questions/55007479/unit-testing-with-jest-expect-problem-receiving-empty-undefined-object,"['reactjs', 'unit-testing', 'testing', 'jestjs', 'sinon']",1856,False,0,1
Unit Testing using Jasmine returning TypeError: this.changeDetectorReference.markForCheck is not a function,"<p>I'm writing a test for an Angular pipe. The pipe has an injected ChangeDetectorRef and <code>this.changeDetectorRef.markForCheck()</code> is been called in a function.</p>

<p>However, when I write and run my Unit test, it fails with the error <code>TypeError: this.changeDetectorReference.markForCheck is not a function</code></p>

<p>How can I fix this please? Below the code blocks</p>

<p>percent.pipe.ts</p>

<pre><code>@Pipe({
  name: 'percent',
  pure: false
})
export class PercentPipe extends BasePercentPipe implements PipeTransform, OnDestroy {
  private onDestroy$: Subject&lt;boolean&gt;;
  private subscription: Subscription;
  private latestValue: any;

  constructor(private gbTranslateService: GbTranslateService, private changeDetectorReference: ChangeDetectorRef, @Inject(LOCALE_ID) locale: string) {
    super(locale);
    this.onDestroy$ = new Subject&lt;boolean&gt;();
  }

  public ngOnDestroy(): void {
    this.changeDetectorReference.detach();
    this.onDestroy$.next(true);
    this.onDestroy$.complete();
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }

  transform(value: any, digitsInfo?: string, locale?: string): any {

    if (value !== this.latestValue) {
      this.update(value, digitsInfo, locale);
    }
    return WrappedValue.wrap(this.latestValue);
  }

  private update(value: any, digitsInfo?: string, locale?: string): void {
    locale = locale || this.gbTranslateService.currentLang || undefined;
    this.latestValue = super.transform(value, digitsInfo, locale);

    this.changeDetectorReference.markForCheck();
  }
}
</code></pre>

<p>percent.pipe.spec.ts</p>

<pre><code>describe('Pipes', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [ChangeDetectorRef, GbTranslateService]
    }).compileComponents();
  });

  describe('Percent pipe: ', () =&gt; {
    it('create an instance of Percent pipe', inject([ChangeDetectorRef, GbTranslateService], (changeDetectorRef: ChangeDetectorRef, gbTranslateService: GbTranslateService) =&gt; {
      const decimalPipe = new DecimalPipe(gbTranslateService, changeDetectorRef, 'en');
      expect(decimalPipe).toBeTruthy();
    }));

    it(`should transform decimal to percentage of any given number e.g. '0.2 =&gt; 20%'`,
      inject([ChangeDetectorRef], (changeDetectorRef: ChangeDetectorRef) =&gt; {
        const decimalPipe = new PercentPipe(changeDetectorRef, 'en');
        const testNumber = 0.2;
        const expectedResult = new WrappedValue('20%');
        expect(decimalPipe.transform(testNumber)).toEqual(expectedResult);
      }));
  });
});
</code></pre>

<p>ERROR</p>

<pre><code> TypeError: this.changeDetectorReference.markForCheck is not a function
            at &lt;Jasmine&gt;
            at PercentPipe.update (http://localhost:9876/_karma_webpack_/src/app/pipes/percent.pipe.ts:49:34)
            at PercentPipe.transform (http://localhost:9876/_karma_webpack_/src/app/pipes/percent.pipe.ts:40:12)
            at UserContext.Object (http://localhost:9876/_karma_webpack_/src/app/pipes/pipe.spec.ts:90:28)
            at TestBedViewEngine.execute (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/testing.js:3791:1)
            at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/testing.js:4143:22)
            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)

</code></pre>

<p>I appreciate your help</p>
",https://stackoverflow.com/questions/59176496/unit-testing-using-jasmine-returning-typeerror-this-changedetectorreference-mar,"['angular', 'jasmine', 'angular-changedetection']",563,False,5,0
Cannot read property &#39;afterClosed&#39; of undefined when unit testing MatDialog in Jasmine,"<p>I get the following error from Karma Jasmine:<br>
<code>TypeError: Cannot read property 'afterClosed' of undefined</code></p>

<p>I searched sincerely, but I could not find a solution in Stack Overflow or in other sources.</p>

<p>This is how I open the <code>MatDialog</code> in my component:<br >
(Like <a href=""https://material.angular.io/components/dialog/overview"" rel=""noreferrer"">documented</a>)</p>

<pre><code>constructor(public dialog: MatDialog) {}

public openDialog(): void {
    const dialogReference: MatDialogRef&lt;any, any&gt; = this.dialog.open(myDialogComponent, {
        width: '1728px'
    });

    dialogReference.afterClosed().subscribe((result) =&gt; {
    });
}
</code></pre>

<p>This is my unit test config:</p>

<pre><code>beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
        declarations: [
            myRequestComponent
        ],
        imports: [
            MatDialogModule,
            ReactiveFormsModule
        ],
        providers: [
            { provide: MatDialog, useValue: {} },
        ],
        schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
}));

beforeEach(() =&gt; {
    fixture = TestBed.createComponent(myRequestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});
</code></pre>

<p>Here is my unit test:</p>

<pre><code>it('openDialog() should open a dialog', () =&gt; {
    spyOn(component.dialog, 'open');

    component.openDialog();

    expect(component.dialog.open).toHaveBeenCalled();
});
</code></pre>

<p>Do I have to mock the MatDialog or the MatDialogReference?</p>
",https://stackoverflow.com/questions/54767811/cannot-read-property-afterclosed-of-undefined-when-unit-testing-matdialog-in-j,"['angular', 'typescript', 'dialog', 'jasmine', 'angular-material']",14710,True,11,2
Angular unit testing - stubbing/mocking a directive with reference in ViewChild,"<p>How do you stub/mock a directive/component that is read as a <code>ViewChild</code>?</p>
<p>For example, using the simple directive from angular.io:</p>
<pre><code>@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor() { }
}
</code></pre>
<p>Let's say that I am testing <code>AppComponent</code> and reads the <code>HighlightDirective</code> using <code>ViewChild</code> as:</p>
<pre><code>@ViewChild(HighlightDirective) theHighlightDirective: HighlightDirective
</code></pre>
<p>And the stubbed directive is:</p>
<pre><code>@Directive({
  selector: '[appHighlight]'
})
export class StubbedHighlightDirective {
  constructor() { }
}
</code></pre>
<p>Since the component is trying to read <code>HighlightDirective</code>, even if you declare <code>StubbedHighlightDirective</code> in your unit tests, <code>theHighlightDirective</code> will be <code>undefined</code>.</p>
<p>Example:</p>
<pre><code>it('HighlightDirective is defined', () =&gt; {
    // This test fails
    expect(component.theHighlightDirective).toBeDefined();
});
</code></pre>
<p>You can get around this if you ignore some things in tslint or use the <code>as</code> keyword:</p>
<pre><code>Version 1: Just ignore some things in tslint so compiler doesn't complain
it('HighlightDirective is defined', () =&gt; {
    // Compiler will typically complain saying that
    // StubbedHighlightDirective isn't assignable to type of HighlightDirective
    component.theHighlightDirective = new StubbedHighlightDirective();

    // this passes
    expect(component.theHighlightDirective).toBeDefined();
});

Version 2: Use &quot;as&quot; keyword
it('HighlightDirective is defined', () =&gt; {
    // Actually compiler will still complain with warnings
    component.theHighlightDirective = new StubbedHighlightDirective() as HighlightDirective;

    // this passes
    expect(component.theHighlightDirective).toBeDefined();
});
</code></pre>
<p>Is there another way to cleanly stub out these kinds of ViewChild references?</p>
",https://stackoverflow.com/questions/54468500/angular-unit-testing-stubbing-mocking-a-directive-with-reference-in-viewchild,"['angular', 'unit-testing', 'jasmine', 'viewchild']",2242,True,4,1
Can I use C# for doing unit testing on VB code?,"<p>I've done a little bit of Unit Testing using JUnit with a Java program, and I am new to the .NET unit testing space. I'm sure it can't be so different, though.</p>

<p>At work, we have a legacy VB .NET codebase, with zero unit testing going on. I want to start adding some unit testing to this thing, and I see the option in Visual Studio to use C# for unit testing. </p>

<p>My question is, am I even able to use C# for testing the VB code? I would definitely want to use this as an opportunity to work with C# instead of more VB. I can't find this question anywhere else online, interestingly enough, and would love some insight. It seems like I'm asking a dumb question, but I hope to get an answer that would help me understand this, especially as to why it's a dumb question, if it is.</p>
",https://stackoverflow.com/questions/55498754/can-i-use-c-for-doing-unit-testing-on-vb-code,"['c#', '.net', 'vb.net', 'unit-testing']",822,True,4,1
How to properly mock a node module for jest unit testing,"<p>I'm new to jest and just want to implement a unit test for a simple function that uses a third party node module.</p>

<p>function to test (say it lives in utilFolder.js):</p>

<pre><code>import moduleName from 'third_party_module'
const util = {
   simple_function() {
      const name = moduleName.func1();
   }
}

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

<p>test file:</p>

<pre><code>import util from ""utilFolder"";
import moduleName  from 'third_party_module';
jest.mock(""third_party_module"", () =&gt; ({
   func1: jest.fn()
}));

describe(""was mocked functions called"", () {
  test(""was mocked functions called??"", () =&gt; {
      util.simple_function();
      expect(moduleName.func1).toHaveBeenCalled();
  });
});

</code></pre>

<p>Error:</p>

<blockquote>
  <p>Expected mock function to have been called, but it was not called.</p>
</blockquote>

<p>Any help please?</p>
",https://stackoverflow.com/questions/54729837/how-to-properly-mock-a-node-module-for-jest-unit-testing,"['javascript', 'reactjs', 'jestjs']",914,True,4,1
Does keeping cyclomatic complexity between 5-10 makes unit testing easier?,"<p>I'm planning to keep track of cyclomatic complexity for method and classes in between 5-10. 
Will it be easier to write unit tests if we keep it in that range?
Does it help us write effective unit tests which can be valuable in long run?</p>

<p>I know unit tests can be written properly without tracking cyclomatic complexity.</p>

<p>Any thoughts?</p>
",https://stackoverflow.com/questions/59001603/does-keeping-cyclomatic-complexity-between-5-10-makes-unit-testing-easier,"['java', 'spring', 'unit-testing', 'maintainability', 'code-maintainability']",236,True,4,1
Why is unit testing harder in MVC than in MVP and MVVM,"<p>I've been doing some research on pros and cons of MVC/MPV/MVVM and one common theme is that MVC is harder to unit test than MVP and MVVM but I don't fully understand why.</p>

<p>From my current understanding, in MVC, the view is dependent on the model and and controller so to test the view, both the controller and the model must be mocked. How is MVP/MVVM improve on this?</p>
",https://stackoverflow.com/questions/56686819/why-is-unit-testing-harder-in-mvc-than-in-mvp-and-mvvm,"['android', 'model-view-controller', 'mvvm', 'mvp', 'android-mvvm']",1539,True,9,2
Minimal audio (wav or mp3) file in bytes for unit testing,"<p>I want to find a minimal audio file (like the <code>testfile_gif</code> below) for unit testing. </p>

<p>I don't want to load it from the hard drive (like <a href=""https://stackoverflow.com/a/4287271/2275286"">here</a>). </p>

<p>I want the second test to perform like the first one. </p>

<pre class=""lang-py prettyprint-override""><code>import magic
from django.core.files.uploadedfile import SimpleUploadedFile


class TestFiles(TestCase):
    def test_working(self):
        # Test an Image File #
        testfile_gif = (
            b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04'
            b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02'
            b'\x02\x4c\x01\x00\x3b')
        gif_file = SimpleUploadedFile(name='image.gif', content=testfile_gif,
                                      content_type='image/gif')
        mime = magic.from_buffer(gif_file.read(1024), mime=True)
        self.assertEqual('image/gif', mime)

    def test_not_working(self):
        # Test an Audio File #
        testfile_audio = b'What should be written in here?'
        audio_file = SimpleUploadedFile(name='music.mp3',
                                        content=testfile_audio,
                                        content_type='audio/mpeg')
        mime = magic.from_buffer(audio_file.read(1024), mime=True)
        self.assertEqual('audio/mpeg', mime)
</code></pre>

<p>Preferably, I don't want to use any packages (like <code>import mock</code>). </p>

<p><strong>UPDATE</strong></p>

<p>Here is an <code>mp3</code> file with <code>audio/mpeg</code> mime:</p>

<pre><code>b'MM\x00*\x00\x00\x00\x08\x00\x03\x01\x00\x00\x03\x00\x00\x00\x01\x00\x01'
b'\x00\x00\x01\x01\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00\x01\x11\x00\x03'
b'\x00\x00\x00\x01\x00\x00\x00\x00'
</code></pre>
",https://stackoverflow.com/questions/57192090/minimal-audio-wav-or-mp3-file-in-bytes-for-unit-testing,"['python', 'django', 'unit-testing']",961,True,3,1
Karma unit testing error: Unexpected value imported by the module. Please add a @NgModule annotation,"<p>I've created a fresh new component via:</p>

<pre><code>ng g mytest1
</code></pre>

<p>Then I changed the constructor line to this:</p>

<pre><code>constructor(private dialogRef: MatDialogRef&lt;Mytest1Component&gt;) { }
</code></pre>

<p>, and added the required import:</p>

<pre><code>import { MatDialogRef } from '@angular/material';
</code></pre>

<p>After that I ran the Karma unit test project via:</p>

<pre><code>ng test
</code></pre>

<p>The test failed. I got this error message:</p>

<blockquote>
  <p>Error: StaticInjectorError(DynamicTestModule)[Mytest1Component -> MatDialogRef]: StaticInjectorError(Platform: core)[Mytest1Component -> MatDialogRef]: NullInjectorError: No provider for MatDialogRef!</p>
</blockquote>

<p>To fix that I added the Import statement in the beforeEach section:</p>

<pre><code>import { MatDialogRef } from '@angular/material';

//...

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

<p>Now I got this new error, which I am not able to fix:</p>

<blockquote>
  <p>Failed: Unexpected value 'MatDialogRef' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.</p>
</blockquote>

<p>Can someone clarify where I should be adding the @NgModule annotation, or if I had done something completely wrong?</p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/54772990/karma-unit-testing-error-unexpected-value-imported-by-the-module-please-add-a,"['angular', 'unit-testing', 'electron', 'karma-jasmine', 'ng-modules']",77633,True,26,2
Unit testing code that references Rails models without loading the models,"<p>I am trying to unit test a Plain Old Ruby Object that has a method which calls a class method on a Rails model. The Rails app is quite large (10s of seconds to load) so I'd prefer to avoid loading all of Rails to do my unit test which should run in under 1s.</p>

<p>Example:</p>

<pre><code>class Foo
  def bar
    SomeRailsModel.quxo(3)
  end
end

RSpec.describe Foo do
  let(:instance) { Foo.new }

  it 'calls quxo on SomeRailsModel' do
    expect(SomeRailsModel).to receive(:quxo)
    instance.bar
  end
end
</code></pre>

<p>The problem here is that I need to <code>require 'rails_helper'</code> to load up Rails in order for <code>app/models/some_rails_model</code> to be available. This leads to slow unit tests due to Rails dependency.</p>

<p>I've tried defining the constant locally and then using regular <code>spec_helper</code> which kind of works.</p>

<p>Example:</p>

<pre><code>RSpec.describe Foo do
  let(:instance) { Foo.new }
  SomeRailsModel = Object.new unless Kernel.const_defined?(:SomeRailsModel)

  it 'calls quxo on SomeRailsModel' do
    expect(SomeRailsModel).to receive(:quxo)
    instance.bar
  end
end
</code></pre>

<p>This code lets me avoid loading all of Rails and executes very fast. Unfortunately, by default (and I like this) RSpec treats the constant as a partial double and complains that my <code>SomeRailsModel</code> constant doesn't respond to the <code>quxo</code> message. Verifying doubles are nice and I'd like to keep that safety harness. I can individually disable the verification by wrapping it in a special block defined by RSpec.</p>

<p>Finally, the question. What is the recommended way to have fast unit tests on POROs that use Rails models without requiring all of Rails while also keeping verifying doubles functionality enabled? Is there a way to create a ""slim"" <code>rails_helper</code> that can just load <code>app/models</code> and the minimal subset of <code>ActiveRecord</code> to make the verification work?</p>
",https://stackoverflow.com/questions/54373597/unit-testing-code-that-references-rails-models-without-loading-the-models,"['ruby-on-rails', 'ruby', 'unit-testing', 'rspec']",427,True,3,1
How can I remove &quot;@oidc.login_required&quot; for unit testing from a view?,"<p>I use <a href=""/questions/tagged/flask-oidc"" class=""post-tag"" title=""show questions tagged &#39;flask-oidc&#39;"" rel=""tag"">flask-oidc</a> for user login and <a href=""/questions/tagged/pytest"" class=""post-tag"" title=""show questions tagged &#39;pytest&#39;"" rel=""tag"">pytest</a> for testing. For unit testing, I would like to ""remove"" <code>@oidc.require_login</code>. How can I do that?</p>

<h2>What I tried</h2>

<p>The way flask-o works is roughly:</p>

<pre><code>from flask import Flask, url_for, redirect
from flask_oidc import OpenIDConnect

app = Flask(__name__)
app.config['OIDC_CLIENT_SECRETS'] = 'client_secrets.json'
# Contents:
# Create client_id and client_secret at https://console.developers.google.com/apis/credentials
# {
#     ""web"": {
#         ""client_id"": ""123456789012-abc123hi09123.apps.googleusercontent.com"",
#         ""client_secret"": ""ab123456789ABCDEFGHIJKLM"",
#         ""redirect_uris"": [""http://localhost:5000""],
#         ""auth_uri"": ""https://accounts.google.com/o/oauth2/auth"",
#         ""token_uri"": ""https://accounts.google.com/o/oauth2/token"",
#         ""userinfo_uri"": ""https://www.googleapis.com/oauth2/v3/userinfo""
#     }
# }
app.config['SECRET_KEY'] = 'uq4aKjUvWXTPTIyfCz7mTtcG'
app.config['OIDC_ID_TOKEN_COOKIE_SECURE'] = False
app.config['OIDC_SCOPES'] = [""openid"", ""profile"", ""email""]
app.config['OIDC_CALLBACK_ROUTE'] = '/authorization-code/callback'
oidc = OpenIDConnect(app)


@app.route('/')
@oidc.require_login
def index():
    return redirect(url_for('personalized'))


@app.route('/personalized')
@oidc.require_login
def personalized():
    info = oidc.user_getinfo(['email', 'openid_id'])
    return 'Hello, {} ({})'.format(info.get('email'), info.get('openid_id'))


@app.route('/hello')
@oidc.require_login
def constant():
    return 'Hello'


if __name__ == '__main__':
    app.run(port=5000)
</code></pre>

<p>Then I hoped the unit test could mock the <code>@oidc.require_login</code> away:</p>

<pre><code># core modules
from unittest import mock

# 3rd party modules
import pytest

# internal modules
import exampleapp


@pytest.fixture
def client():
    app = exampleapp.app
    client = app.test_client()
    yield client


@mock.patch(""flask_oidc.OpenIDConnect"")
def test_private(mock_require_login, client):
    rv = client.get('/hello')
    assert rv.data == b'Hello'
</code></pre>
",https://stackoverflow.com/questions/57251349/how-can-i-remove-oidc-login-required-for-unit-testing-from-a-view,"['unit-testing', 'mocking', 'pytest', 'flask-oidc']",1134,True,3,1
How to fix error &quot;Disconnectedreconnect failed before timeout of&quot; in angular unit testing,"<p>I have around 50 test cases written in Angular. On executing those it says <code>Disconnectedreconnect failed before timeout of 10000ms</code>. I did some configuration settings like </p>

<pre><code>captureTimeout: 60000, // it was already there
browserDisconnectTimeout : 10000,
browserDisconnectTolerance : 1,
browserNoActivityTimeout : 60000,//by default 10000
</code></pre>

<p>Nothing seems to be working. If I extend the <code>browserDisconnectTimeout</code> time to <code>100000ms</code>, then its working fine, but upon adding more test cases it again throws the timeout error.</p>
",https://stackoverflow.com/questions/54309064/how-to-fix-error-disconnectedreconnect-failed-before-timeout-of-in-angular-uni,"['angular', 'typescript']",3595,False,14,1
Unit Testing a Vue.js Router with JEST - How to mock pages?,"<p>I am trying to unit test my router routes and, following various examples, I have come up with some test cases. I have split my router out into separate modules for routes, guards and the router itself to make it easier to test, so I'm effectively only testing the route definitions here. Here's a sample of my routes...</p>

<pre><code>import Guards from './guards'
import Views from '@/views'

export default [
    {
        path: '/',
        props: true,
        components: {
            default: Views.Pages.Wizard,
            header: Views.Headers.Wizard
        },
        children: [
            {
                path: '',
                name: 'Welcome',
                component: Views.Welcome
            },
            {
                path: 'verify-guest',
                name: 'ReCaptcha',
                component: Views.ReCaptcha
            }
        ]
    },
    {
        path: '/:postcode/:id/:address',
        props: true,
        components: {
            default: Views.Pages.Main,
            header: Views.Headers.Main
        },
        children: [
            {
                path: '',
                name: 'MyHome',
                props: true,
                component: Views.MyHome,
                beforeEnter: Guards.requireSelectedProperty
            },
            {
                path: 'improvements',
                name: 'Improvements',
                props: true,
                component: Views.Improvements,
                beforeEnter: Guards.requireSelectedProperty
            }
        ]
    }
]
</code></pre>

<p>I have written some tests and the tests to load the lading page (welcome) pass but everything else seems to fail that I try - It's as if the router only ever loads the landing page.</p>

<p>The tests look like this...</p>

<pre><code>import Helper from '../../test-helper'
import { mount, createLocalVue } from '@vue/test-utils'

import VueRouter from 'vue-router'

import App from '../../templates/app-bare.vue'
import Views from '@/views'

import routes from '@/router/routes.js'
import MockGuards from '@/router/guards.js'

jest.mock('@/router/guards.js', () =&gt; ({
    requireUser: jest.fn(),
    requireFullUser: jest.fn(),
    requireCurrentProject: jest.fn(),
    requireSelectedProperty: jest.fn()
}))

jest.mock('@/views/headers/main.vue', () =&gt; ({
    name: 'MainHeader',
    render: h =&gt; h('div')
}))

jest.mock('@/views/headers/wizard.vue', () =&gt; ({
    name: 'WizardHeader',
    render: h =&gt; h('div')
}))

jest.mock('@/views/welcome.vue', () =&gt; ({
    name: 'Welcome',
    render: h =&gt; h('span')
}))

jest.mock('@/views/my-home.vue', () =&gt; ({
    name: 'MyHome',
    render: h =&gt; h('section')
}))

const localVue = createLocalVue()
localVue.use(VueRouter)

describe('router', () =&gt; {
    let router
    let wrapper

    beforeEach(() =&gt; {
        router = new VueRouter({ base: '/', routes })
        wrapper = mount(App, {
            localVue,
            router,
            mocks: Helper.vueMockPlugins()
        })
    })

    describe('can load the landing page', () =&gt; {

        it('via a path', () =&gt; {
            router.push('/')
            expect(wrapper.find(Views.Welcome).exists()).toBeTruthy()
            expect(wrapper.find(Views.Headers.Wizard).exists()).toBeTruthy()
        })

        it('via a name', () =&gt; {
            router.push({ name: 'Welcome' })
            expect(wrapper.find(Views.Welcome).exists()).toBeTruthy()
            expect(wrapper.find(Views.Headers.Wizard).exists()).toBeTruthy()
        })
    })

    /*

    None of these work - can only ever make the router render 'Welcome'

    describe('can load the root of my home', () =&gt; {

        it('via a path', () =&gt; {
            router.push('/KT18%207LJ/1/3%20The%20Crescent/')
            console.log(wrapper.html())
            expect(wrapper.find(Views.MyHome).exists()).toBeTruthy()
            expect(wrapper.find(Views.Headers.Main).exists()).toBeTruthy()
        })

        it('via a name with parameters', () =&gt; {
            router.push({ name: 'MyHome', params: {
                id: 1,
                postcode: 'KT18 7LJ',
                address: '3 The Crescent'
            } })
            console.log(wrapper.html())
            expect(wrapper.find(Views.MyHome).exists()).toBeTruthy()
            expect(wrapper.find(Views.Headers.Main).exists()).toBeTruthy()
        })
    })

    */
})
</code></pre>

<p>Any ideas? I'm very new to JEST and unit testing with Vue at all - I've much more prior experience with Jasmine and Mocha / Chai / Sinon.</p>
",https://stackoverflow.com/questions/57558032/unit-testing-a-vue-js-router-with-jest-how-to-mock-pages,"['javascript', 'vuejs2', 'jestjs']",2807,True,2,1
SWI-Prolog - Unit testing library plunit - How is forall option used?,"<p>For my lexer (<a href=""https://en.wikipedia.org/wiki/Lexical_analysis#Tokenization"" rel=""nofollow noreferrer"">tokenizer</a>) all of the <a href=""https://en.wikipedia.org/wiki/ASCII"" rel=""nofollow noreferrer"">ASCII</a> <a href=""https://en.wikipedia.org/wiki/ASCII#7-bit_codes"" rel=""nofollow noreferrer"">7-bit</a> characters (0x00 to 0x7F) have a specific token. As SWI-Prolog <a href=""http://www.swi-prolog.org/pldoc/man?section=unicodesyntax"" rel=""nofollow noreferrer"">supports</a> <a href=""https://en.wikipedia.org/wiki/Unicode"" rel=""nofollow noreferrer"">Unicode</a>, the character codes go from 0x0000 to 0xFFFF. </p>

<p>In my lexer, since there are many characters that will not map to a specific token there is an unknown token (tokUnknown).</p>

<p>To ensure that all of the characters with code between 0 and 127 (0x00 to 0x7F) do not have  <code>tokUnknown</code>, test cases are needed. </p>

<p>The test case needs a simple lexer to convert the character to a token.</p>

<pre><code>tokenizer_unknown(Token) --&gt;
    (
        white_space_char(W), !, white_space(W, S),
        { Token = tokWhitespace(S) }
    ;
        [S],
        { special_character(S,Token) }
    ;
        digit(D), !, number(D, N),
        { Token = tokNumber(N) }
    ;
        letter(L), !, word(L, W),
        { Token = tokWord(W) }
    ;
        [_],
        { Token = tokUnknown }
    ), !.
</code></pre>

<p>Here is the test case for the character with code 0.</p>

<pre><code>:- begin_tests(unknown).

test(001) :-
    Code = 0,
    char_code(Char,Code),
    Chars = [Char],
    phrase(tokenizer_unknown(Token),Chars,Rest),
    assertion(Rest == []),
    assertion(Token \== tokUnknown).

:- end_tests(unknown).
</code></pre>

<p>Writing test in this manner requires 128 different test to check for <code>tokUnknown</code>.</p>

<p>SWI-Prolog unit testing library <a href=""http://www.swi-prolog.org/pldoc/doc_for?object=section(%27packages/plunit.html%27)"" rel=""nofollow noreferrer"">plunit</a> has an option <a href=""http://www.swi-prolog.org/pldoc/man?section=unitbox"" rel=""nofollow noreferrer"">forall</a> to generate data.</p>

<p>Based on the documentation the test should look like this:</p>

<pre><code>test(002, [forall(???)]) :-
    char_code(Char,Code),
    Chars = [Char],
    phrase(tokenizer_unknown(Token),Chars,Rest),
    assertion(Rest == []),
    assertion(Token \== tokUnknown).
</code></pre>

<p>Can the <code>forall</code> option be used to write just one test case instead of 128 individual test cases for this test series? </p>

<p>Can you give a working version of the test case using forall?</p>

<hr>

<p>Follow-up</p>

<p>The template for forall is <code>forall(:Generator)</code>. </p>

<p>When I first saw this I was totally confused and almost walked away going back to writing large numbers of test, but stuck with it knowing how valuable and easily this should be for making parameterized tests, e.g. <a href=""https://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests"" rel=""nofollow noreferrer"">JUnit 5 </a> or <a href=""https://github.com/nunit/docs/wiki/Parameterized-Tests"" rel=""nofollow noreferrer"">NUnit 3</a>. Parameterized  test can then be used for <a href=""https://en.wikipedia.org/wiki/Fuzzing"" rel=""nofollow noreferrer"">fuzzing</a> and fuzzing can be enhanced to generate <a href=""https://en.wikipedia.org/wiki/Counterexample"" rel=""nofollow noreferrer"">counter examples</a>, e.g. <a href=""http://www.cse.chalmers.se/~rjmh/QuickCheck/"" rel=""nofollow noreferrer"">QuickCheck</a>, <a href=""https://github.com/fscheck/FsCheck"" rel=""nofollow noreferrer"">FsCheck</a></p>

<hr>

<p>Example 1</p>

<p>In the hard coded test </p>

<pre><code>test(001) :-
    Code = 0,
    char_code(Char,Code),
    Chars = [Char],
    phrase(tokenizer_unknown(Token),Chars,Rest),
    assertion(Rest == []),
    assertion(Token \== tokUnknown).
</code></pre>

<p>I wanted to make <code>Code</code> a variable that changed for each test. I also knew the constraints for <code>Code</code>, i.e. 0 to 127.</p>

<p>So for this simple generator all that was needed was a predicate that generated values from 0 to 127 when called and returned them as a variable, e.g. <code>Code</code>.</p>

<p><a href=""http://www.swi-prolog.org/pldoc/man?predicate=between/3"" rel=""nofollow noreferrer"">between/3</a> fills the requirement, e.g.  </p>

<pre><code>?- between(0,3,Code).
Code = 0 ;
Code = 1 ;
Code = 2 ;
Code = 3.
</code></pre>

<p>As can be seen by looking at the answer, just give the predicate to <code>forall</code>, e.g. </p>

<pre><code>forall(between(0, 127, Code))
</code></pre>

<hr>

<p>Example 2</p>

<p>This test is to check that all individual <a href=""https://en.wikipedia.org/wiki/Whitespace_character"" rel=""nofollow noreferrer"">whitespace</a> characters or sequence of whitespace characters for ASCII 7-bit characters return as <code>tokWhitespace</code> and that the whitespace character(s) are a string value of the token. </p>

<p>The custom with whitespace tokens is not to include the characters in the token, but here they are included because it is easier to remove them if needed then wonder why the OP didn't do it. Since this is for learning they are included.</p>

<p>Hard coded tests</p>

<pre><code>:- begin_tests(white_space).

test(001) :-
    String = ""\t"",
    string_codes(String,Codes),
    phrase(whitespace(Tokens),Codes,Rest),
    assertion(Tokens == tokWhitespace(""\t"")),
    assertion(Rest == []).

test(011) :-
    String = ""\t\r"",
    string_codes(String,Codes),
    phrase(whitespace(Tokens),Codes,Rest),
    assertion(Tokens == tokWhitespace(""\t\r"")),
    assertion(Rest == []).

test(043) :-
    String = ""\s\s\s"",
    string_codes(String,Codes),
    phrase(whitespace(Tokens),Codes,Rest),
    assertion(Tokens == tokWhitespace(""\s\s\s"")),
    assertion(Rest == []).

:- end_tests(white_space).
</code></pre>

<p>In this example the variables are <code>String</code>, e.g. <code>""\t""</code>, and the value in the token <code>tokWhitespace</code>, e.g. <code>""\t""</code>. </p>

<p>The single whitespace characters are:</p>

<pre><code>?- code_type(Char,space).
Char = 9 ;        % tokHorizontalTab   \t
Char = 10 ;       % tokLineFeed        \n
Char = 11 ;       % tokVerticalTab     \v
Char = 12 ;       % tokFormFeed        \f
Char = 13 ;       % tokCarriageReturn  \r
Char = 32 ;       % tokSpace           \s
Char = 160 ;      % Yes, there are space characters defined beyond 7-bit ASCII. See: https://en.wikipedia.org/wiki/Whitespace_character#Unicode
Char = 5760 ; 
...
</code></pre>

<p>One lesson learned from decades of writing lexer/tokenization tests is that each individual character needs to be tested. Also the test should not generate the values in the same manner as the check in lexer/tokenizer. In this case the test should not rely on <code>code_type/2</code> because that is used in the lexer/tokenizer and if <code>code_type/2</code> where some how to get a bug the tests would not detect it. So the test cases will get the characters via a different means, in this example they will be from a list.</p>

<p>A second lesson learned from decades of testing recursive code is that the test needs to test at least three levels deep. In this example the test of whitespace characters will test sequences up to three characters.</p>

<p>A third lesson is that using functional composition with functions such as combinations, permutations, type constructors, and type destructors, etc. reduce the <a href=""https://en.wikipedia.org/wiki/Combinatorial_explosion"" rel=""nofollow noreferrer"">combinatorial explosion</a> of writing test data generators; conversely they contribute to combinatorial explosion of test cases. To do this in Prolog requires translating functional concepts to Prolog predicates.</p>

<p>Based on these lessons some helper predicates are needed.</p>

<pre><code>comb(0,_,[]).
comb(N,[X|T],[X|Comb]) :-
    N&gt;0,
    N1 is N-1,
    comb(N1,T,Comb).
comb(N,[_|T],Comb) :-
    N&gt;0,
    comb(N,T,Comb).

variation_string(N,L,String) :-
    between(1,N,N0),
    comb(N0,L,L1),
    permutation(L1,L2),
    string_chars(String,L2).

variation_number(N,L,String,Number) :-
    between(1,N,N0),
    comb(N0,L,L1),
    permutation(L1,L2),
    string_chars(String,L2),
    number_chars(Number,L2).
</code></pre>

<p>Example usage:</p>

<pre><code>?- variation_string(3,['\t','\r','\n'],String).
String = ""\t"" ;
String = ""\r"" ;
String = ""\n"" ;
String = ""\t\r"" ;
String = ""\r\t"" ;
String = ""\t\n"" ;
String = ""\n\t"" ;
String = ""\r\n"" ;
String = ""\n\r"" ;
String = ""\t\r\n"" ;
String = ""\t\n\r"" ;
String = ""\r\t\n"" ;
String = ""\r\n\t"" ;
String = ""\n\t\r"" ;
String = ""\n\r\t"" ;
false.
</code></pre>

<p>To keep the reading of <code>forall</code> simpler a helper predicate is created.</p>

<pre><code>generator_ascii_7bit_char_type_white(R) :-
    variation_string(3,['\t','\n','\v','\f','\r','\s'],R).
</code></pre>

<p>Now to simply use the generator with <code>forall</code> in the test.</p>

<pre><code>:- begin_tests(white_space).

test(000, [forall(generator_ascii_7bit_char_type_white(String))]) :-
    string_codes(String,Codes),
    phrase(whitespace(Tokens),Codes,Rest),
    assertion(Tokens == tokWhitespace(String)),
    assertion(Rest == []).

:- end_tests(white_space).
</code></pre>

<p>With such little code all these test were created and run (each dot represents a separate test case).</p>

<pre><code>% PL-Unit: white_space ............................................................................................................................................................ done
</code></pre>

<hr>

<p>Example 3</p>

<p>This example <a href=""http://www.swi-prolog.org/pldoc/man?section=testnondet"" rel=""nofollow noreferrer"">test a non-deterministic predicate</a> so needs to use <a href=""http://www.swi-prolog.org/pldoc/man?section=allsolutions"" rel=""nofollow noreferrer"">findall</a>. This also has two input parameters and two output parameters for the predicate. </p>

<p>The signature of findall/3 is</p>

<pre><code>findall(+Template, :Goal, -Bag)
</code></pre>

<p>To use two values with <code>finall/3</code> the <code>Template</code> is not a tuple, e.g. <code>(A,B)</code>, but a list, e.g. <code>[A,B]</code>, and the <code>Bag</code> is a list of list, e.g. <code>[[""1"",1],[""2"",2]]</code> where each item in the list is a result and items in the inner list are the values for corresponding <code>Template</code> parameters.</p>

<p>This example test <code>variation_number/4</code></p>

<pre><code>:- begin_tests(variation_number_4).

variation_number_4(0,[],[]).
variation_number_4(1,[],[]).
variation_number_4(2,[],[]).
variation_number_4(3,[],[]).
variation_number_4(0,['1'],[]).
variation_number_4(1,['1'],[[""1"",1]]).
variation_number_4(2,['1'],[[""1"",1]]).
variation_number_4(3,['1'],[[""1"",1]]).
variation_number_4(0,['1','2'],[]).
variation_number_4(1,['1','2'],[[""1"",1],[""2"",2]]).
variation_number_4(2,['1','2'],[[""1"",1],[""2"",2],[""12"",12],[""21"",21]]).
variation_number_4(3,['1','2'],[[""1"",1],[""2"",2],[""12"",12],[""21"",21]]).
variation_number_4(0,['1','2','3'],[]).
variation_number_4(1,['1','2','3'],[[""1"",1],[""2"",2],[""3"",3]]).
variation_number_4(2,['1','2','3'],[[""1"",1],[""2"",2],[""3"",3],[""12"",12],[""21"",21],[""13"",13],[""31"",31],[""23"",23],[""32"",32]]).
variation_number_4(3,['1','2','3'],[[""1"",1],[""2"",2],[""3"",3],[""12"",12],[""21"",21],[""13"",13],[""31"",31],[""23"",23],[""32"",32],[""123"",123],[""132"",132],[""213"",213],[""231"",231],[""312"",312],[""321"",321]]).
variation_number_4(0,['1','2','3','4'],[]).
variation_number_4(1,['1','2','3','4'],[[""1"",1],[""2"",2],[""3"",3],[""4"",4]]).
variation_number_4(2,['1','2','3','4'],[[""1"",1],[""2"",2],[""3"",3],[""4"",4],[""12"",12],[""21"",21],[""13"",13],[""31"",31],[""14"",14],[""41"",41],[""23"",23],[""32"",32],[""24"",24],[""42"",42],[""34"",34],[""43"",43]]).
variation_number_4(3,['1','2','3','4'],[[""1"",1],[""2"",2],[""3"",3],[""4"",4],[""12"",12],[""21"",21],[""13"",13],[""31"",31],[""14"",14],[""41"",41],[""23"",23],[""32"",32],[""24"",24],[""42"",42],[""34"",34],[""43"",43],[""123"",123],[""132"",132],[""213"",213],[""231"",231],[""312"",312],[""321"",321],[""124"",124],[""142"",142],[""214"",214],[""241"",241],[""412"",412],[""421"",421],[""134"",134],[""143"",143],[""314"",314],[""341"",341],[""413"",413],[""431"",431],[""234"",234],[""243"",243],[""324"",324],[""342"",342],[""423"",423],[""432"",432]]).

test(000, forall(variation_number_4(Len,L,R0s))) :-
    findall([R,N],variation_number(Len,L,R,N),Rs),
    assertion(Rs == R0s).

:- end_tests(variation_number_4).
</code></pre>
",https://stackoverflow.com/questions/54334567/swi-prolog-unit-testing-library-plunit-how-is-forall-option-used,"['unit-testing', 'prolog', 'swi-prolog', 'parameterized-unit-test', 'plunit']",464,True,2,1
Angular Unit Testing on a component async / await function in jasmine,"<p>I wanted to test if the the object returned by the service calls a specific method.</p>

<p>The component method is <code>async</code> since the service will return a <code>Promise</code>.</p>

<p>Here's the component code.</p>

<pre><code>// component
export class FilterComponent {
  constructor(
    private modalController: ModalController,
  ) { }

  async onFilterClicked() {
    const modal = await this.modalController.create({
      component: FilterModalPage,
    });

    modal.onDidDismiss().then(res =&gt; {
      if (res.data) {
        // do something
      }
    });

    await modal.present();
  }
}
</code></pre>

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

<pre><code>describe('FilterComponent', () =&gt; {
  let fixture: ComponentFixture&lt;FilterComponent&gt;;
  let component: FilterComponent;
  let modalControllerSpy;
  let modalSpy;

  beforeEach(async () =&gt; {
    modalControllerSpy = jasmine.createSpyObj('modalController', ['create']);
    modalSpy = jasmine.createSpyObj('modal', ['present']);

    TestBed.configureTestingModule({
      declarations: [FilterComponent],
      providers: [
        { provide: ModalController, useValue: modalControllerSpy },
      ]
    }).compileComponents();
  });

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

  describe('onFilterClicked', () =&gt; {
    it('should `present` the modal', () =&gt; {
      modalControllerSpy.create.and.returnValue(modalSpy);

      component.onFilterClicked();
      fixture.detectChanges();

      expect(modalControllerSpy.create).toHaveBeenCalled(); // success
      expect(modalSpy.present).toHaveBeenCalled(); // fail :( how to test `present` is called????
    });
  });
});
</code></pre>

<p>I created spy object on the first <code>beforeEach</code> callback.</p>

<pre><code>modalControllerSpy = jasmine.createSpyObj('modalController', ['create']);
modalSpy = jasmine.createSpyObj('modal', ['present']);
</code></pre>

<p>I wanted to test if my <code>modalSpy</code> calls <code>present</code> function.
Perhaps I did something wrong here.</p>
",https://stackoverflow.com/questions/58297595/angular-unit-testing-on-a-component-async-await-function-in-jasmine,"['angular', 'typescript', 'unit-testing', 'jasmine']",2628,True,2,2
how to mock KStream in spring cloud stream for unit testing,"<p>How can I write a unit test for the below method:</p>

<pre><code> public KStream&lt;String, Object&gt; process(KStream&lt;String, Object&gt; kstream) {
        return kstream
            .filter((key, value) -&gt; isFilterRequired(value))
            .mapValues(this::mapValues);
</code></pre>

<p>I am using Spring Cloud Stream framework, how could I mock KStream in order to invoke process method or how could I test this piece of code in Spring Kafka world.</p>
",https://stackoverflow.com/questions/56659262/how-to-mock-kstream-in-spring-cloud-stream-for-unit-testing,['apache-kafka-streams'],1803,False,2,1
TypeScript unit testing cannot use import statement outside of a module,"<p>Guys, I'm following this <a href=""https://medium.com/swlh/typescript-unit-testing-with-test-coverage-2cc0cc6f3fd1"" rel=""nofollow noreferrer"">Link</a> to learn how to unit test in TypeScript.
Followed exactly that but running npm test generates this error:</p>

<p><a href=""https://i.stack.imgur.com/NaCEc.png"" rel=""nofollow noreferrer"">Error print</a></p>

<p>My code is as follow:</p>

<p>---- Normal constructor ----</p>

<pre><code>export class Cliente {

    payment_method: String;

    constructor(payment_method: String) {
        this.payment_method = payment_method;
    }
}
</code></pre>

<p>---- Test ----</p>

<pre><code>import { expect } from 'chai';
import { Cliente } from '../src/client';

let payment_method: String = 'paypal';

it('constructorTest', () =&gt; {
        let clientObj = new Cliente(payment_method);
        expect(clientObj.payment_method).to.be('paypal');
    })
</code></pre>

<p>---- TS Config and Package.json ----</p>

<pre><code>{
    ""compilerOptions"": {
      ""module"": ""commonjs"",
      ""sourceMap"": true,
      ""target"": ""es2015""
    }
  }
</code></pre>

<pre><code>{
  ""name"": ""testTS"",
  ""type"": ""module"",
  ""version"": ""1.0.0"",
  ""description"": """",
  ""main"": ""index.js"",
  ""scripts"": {
    ""test"": ""cross-env TS_NODE_FILES=true mocha — exit — require ts-node/register — colors test/**/*.ts""
  },
  ""keywords"": [],
  ""author"": """",
  ""license"": ""ISC"",
  ""devDependencies"": {
    ""@types/chai"": ""^4.2.7"",
    ""@types/mocha"": ""^5.2.7"",
    ""@types/node"": ""^12.12.18"",
    ""chai"": ""^4.2.0"",
    ""cross-env"": ""^5.2.0"",
    ""mocha"": ""^6.2.0"",
    ""nyc"": ""^14.1.1"",
    ""ts-node"": ""^8.3.0"",
    ""typescript"": ""^3.5.3""
  }
}
</code></pre>

<p>I have already tried some of the solutions out there but nothing solves this. Its probably something easy that I'm overlooking and cant seem to fix!</p>

<p>Would appreciate any help.</p>
",https://stackoverflow.com/questions/59374918/typescript-unit-testing-cannot-use-import-statement-outside-of-a-module,"['typescript', 'visual-studio', 'unit-testing']",388,False,2,0
How to disable security feature for Unit testing in Spring Webflux,"<p>My <code>Unit tests are passed</code> already. After I added the Security with <code>JWT token</code>, the passed unit tests are <code>failed</code> cos of Security features. I would like to <code>disable security features</code> for unit tests. I don't want to <code>rewrite</code> all the test cases.</p>

<p>Can I <code>disable the security features</code> for unit tests?</p>

<p>I used <code>Spring Boot 2.1.1</code>, <code>Webflux</code>, and <code>RouterFunction</code> instead of controller.</p>
",https://stackoverflow.com/questions/54103790/how-to-disable-security-feature-for-unit-testing-in-spring-webflux,"['unit-testing', 'spring-boot', 'spring-webflux']",313,False,2,1
How to mock custom UserServiceDetails in SpringSecurity Bean for unit-testing?,"<p>I have <code>Spring Boot</code> application with basic auth enabled. <code>UserServiceDetails</code> consumed from DB. For the unit-testing purpose, I want to mock it, so the data will be consumed from elsewhere.</p>

<p>How can I do it?</p>

<p>My question is not how to mock <code>UserServiceDetails</code> itself but how to mock the way that I can use it to test Controllers with basic auth.</p>

<p>The below is my <code>SpringSecurity</code> config:</p>

<pre><code>@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            ""/"",
            ""/csrf"",
            ""/swagger-resources"",
            ""/swagger-resources/**"",
            ""/configuration/ui"",
            ""/configuration/security"",
            ""/swagger-ui.html"",
            ""/webjars/**""
    };

    @Autowired
    @Qualifier(""customUserDetailsService"")
    private UserDetailsService userDetailsService;

    private final static Integer bCryptEncryptionLevel = 8;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder(bCryptEncryptionLevel);
    }

    public SecurityConfig() {
        super();
    }

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder.authenticationProvider(authenticationProvider());
        authManagerBuilder.userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
        return authenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                    .antMatchers(AUTH_WHITELIST).permitAll()
                    // allow default swagger docket
                    .regexMatchers(""\\A/v2/api-docs\\Z"").permitAll()
                    // require auth for any other swagger docket
                    .regexMatchers(""\\A/v2/api-docs?.*\\Z"").authenticated()
                    .antMatchers(""/**"").authenticated()
                .and()
                .httpBasic()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
</code></pre>

<p>To summarize, how can I mock <code>UserServiceDetails</code> into <code>SpringSecurity</code> config, so I can unit-test controllers into my <code>Spring Boot</code> app?</p>
",https://stackoverflow.com/questions/58353403/how-to-mock-custom-userservicedetails-in-springsecurity-bean-for-unit-testing,"['java', 'spring-boot', 'unit-testing', 'spring-security']",235,False,2,1
Running an In-Memory Sandboxed Neo4J Database for NodeJS Unit Testing,"<p>Is there a way to spin up small in-memory Neo4J database instances for use when unit testing NodeJS code? I am currently using Jest.</p>
",https://stackoverflow.com/questions/58356178/running-an-in-memory-sandboxed-neo4j-database-for-nodejs-unit-testing,"['javascript', 'node.js', 'unit-testing', 'neo4j', 'jestjs']",193,True,2,1
ngx-translate instant function is not a function thrown: Unit testing,"<p>I'm fairly new for unit testing and Angular, and i'm trying to write some unit tests for my project.</p>

<p>The error i'm getting is;</p>

<pre><code>Uncaught TypeError: _this.translate.instant is not a function thrown
Expected null to be truthy.
</code></pre>

<p>The imports of the component.spec file includes</p>

<pre><code>beforeEach(async(() =&gt; {
TestBed.configureTestingModule({
  imports:[
    ClarityModule,
    RouterTestingModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (http: HttpClient) =&gt; new TranslateHttpLoader(http, 'assets/i18n/', '.json'),
        deps: [HttpClient]
      }
    }),
    HttpClientModule
  ],
  declarations: [
    HeaderComponent,
    LanguageSelectorComponent
  ],
  providers: [
    { provide: Store, useClass: TestStore },
    { provide: TranslateService, useClass: TranslateServiceStub },
    { provide: NGXLogger, useClass: NGXLoggerMock }
  ]
})
.compileComponents();
}));
</code></pre>

<p>I understand that <code>TranslateServiceStub</code> does not include a 'instant' function. Is this the cause of this error? if so, how can i mock translate.instant function?</p>

<p>Or is there any way to load the translations file in the spec file before instant method gets called?</p>

<p>Any suggestion would be greatly helpful. Thanks a lot!</p>
",https://stackoverflow.com/questions/57112046/ngx-translate-instant-function-is-not-a-function-thrown-unit-testing,"['angular', 'typescript', 'unit-testing', 'karma-jasmine', 'ngx-translate']",9262,True,2,1
Cannot read property &#39;apply&#39; of undefined when unit testing in chai,"<p>Trying to test a simple express rest, and im getting </p>

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

<p>Not sure what i am doing wrong. </p>

<p>I referenced similar threads but it wasn't specific to unit testing </p>

<p><a href=""https://stackoverflow.com/questions/52767617/cannot-read-property-apply-of-undefined"">Cannot read property &#39;apply &#39; of undefined</a></p>

<p>referencing this</p>

<p><a href=""https://codehandbook.org/unit-test-express-route/"" rel=""nofollow noreferrer"">https://codehandbook.org/unit-test-express-route/</a></p>

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

<pre><code>import chai from 'chai';
import chaiHttp from 'chai-http';
import router from '../routes/';

chai.use(chaiHttp);
chai.should();

const expect = chai.expect();

describe('index page should render, hello world', () =&gt; {
    it('should render hello world 200', (done) =&gt; {     
        chai.request(router).get('/').end( (err, res) =&gt; {   
            expect(200, ""ok"").
            expect(res.text).to.equal('Hello World');

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

<p><strong>index.js</strong></p>

<pre><code>import express from 'express';

const router = express.Router();

router.get('/', (req, res) =&gt; {
    return res.status(200).json({
        message: ""Hello World""
    })
})




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

<p><strong>.babelrc</strong></p>

<pre><code>{
    ""presets"": [""@babel/preset-env""]  
}
</code></pre>

<p><strong>package.json</strong></p>

<pre><code>{
  ""name"": ""elinodereactapp"",
  ""version"": ""1.0.0"",
  ""description"": """",
  ""scripts"": {
    ""start"": ""nodemon --exec babel-node ./app.js"",
    ""test"": ""mocha --require @babel/register tests/*.js --exit"",
    ""build"": ""babel src --out-dir ./dist --source-maps"",
    ""serve"": ""node ./app.js""
  },
  ""author"": """",
  ""license"": ""ISC"",
  ""dependencies"": {
    ""assert"": ""^1.4.1"",
    ""body-parser"": ""^1.18.3"",
    ""chai-http"": ""^4.2.1"",
    ""cookie-parser"": ""^1.4.4"",
    ""cors"": ""^2.8.5"",
    ""dotenv"": ""^7.0.0"",
    ""express"": ""^4.16.4"",
    ""morgan"": ""^1.9.1"",
    ""node-mocks-http"": ""^1.7.3""
  },
  ""devDependencies"": {
    ""@babel/cli"": ""^7.4.3"",
    ""@babel/core"": ""^7.4.3"",
    ""@babel/node"": ""^7.2.2"",
    ""@babel/preset-env"": ""^7.4.3"",
    ""@babel/register"": ""^7.4.0"",
    ""babel-cli"": ""^6.26.0"",
    ""babel-core"": ""^7.0.0-bridge.0"",
    ""babel-loader"": ""^8.0.5"",
    ""babel-preset-env"": ""^1.7.0"",
    ""chai"": ""^4.2.0"",
    ""mocha"": ""^6.1.1"",
    ""nodemon"": ""^1.18.10""
  }
}
</code></pre>
",https://stackoverflow.com/questions/55580740/cannot-read-property-apply-of-undefined-when-unit-testing-in-chai,"['javascript', 'express', 'mocha.js', 'chai']",4600,True,2,1
Kotlin coroutines unit testing with runBlocking does not wait for execution,"<p>Is there any way to wait for a suspending function that is running in a scope, like what runBlocking does for its running suspending functions?</p>

<p>For example,</p>

<pre><code>class CoroutineTestCase : CoroutineScope {
    val job = Job()
    var value = 1
    override val coroutineContext: CoroutineContext
        get() = job + Dispatchers.Unconfined


    fun testFunction() {
         async {
             delay(2000)
             value = 2
        }
    }
}

@Test
fun testCoroutine() = runBlocking {
    val coroutineTestCase = CoroutineTestCase()
    coroutineTestCase.testFunction()
    assertEquals(2, coroutineTestCase.value)
}
</code></pre>

<p>The above test fails with value being 1 and not changed (since the <code>launch</code> was not being waited to finish). If the <code>testFunction</code> had been a suspending function and I ran it with runBlocking inside my unit test, everything would have worked.</p>

<p>I've tried with other custom dispatchers (like the one below) that can blockingly run their tasks, but no luck</p>

<pre><code>class TestUiContext : CoroutineDispatcher() {
     override fun dispatch(context: CoroutineContext, block: Runnable) {
         block.run()
    }
}
</code></pre>
",https://stackoverflow.com/questions/54061539/kotlin-coroutines-unit-testing-with-runblocking-does-not-wait-for-execution,"['android', 'kotlin', 'kotlinx.coroutines']",8532,True,2,1
Cannot read property of undefined &#39;ngOnInit&#39; &#39;getData&#39;-Angular-Unit testing-jasmine,"<p>I'm trying of write a unit test for my component file which is subscribing to a method in service layer</p>

<p>Homecomponent.ts</p>

<pre><code>import { Data } from './../model/data.model';
import { DataService } from './../services/data.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  data: Data[];
  constructor(private service: DataService) {}

  ngOnInit() {
    this.getData();
  }
  getData() {
    this.service.getData().subscribe(
      (data) =&gt; {
        console.log(data);
        this.data = data;
      },
      (err) =&gt; {
        console.log(err);
      },
    );
  }
}
</code></pre>

<p>HomeComponent.spec.ts</p>

<pre><code>import { Data } from './../model/data.model';
import { HttpClientModule } from '@angular/common/http';
import { HomeComponent } from './home.component';
import { ComponentFixture, async, TestBed } from '@angular/core/testing';
import { DataService } from '../services/data.service';
import { Observable } from 'rxjs';
import 'rxjs/add/observable/of';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { results } from '../model/home';

class MockMyService {
  public data: Data[];
  public getData(): Observable&lt;Data[]&gt; {
    this.data = results;
    return Observable.of(this.data);
  }
}

describe('HomeComponent', () =&gt; {
  let component: HomeComponent;
  let fixture: ComponentFixture&lt;HomeComponent&gt;;
  let mockSomeService: MockMyService;
  describe('Async', () =&gt; {
    beforeEach(async(() =&gt; {
      TestBed.configureTestingModule({
        declarations: [HomeComponent],
        providers: [
          {
            provide: DataService,
            useValue: mockSomeService,
          },
        ],
        imports: [HttpClientModule],
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
      });
      TestBed.compileComponents();
      fixture = TestBed.createComponent(HomeComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
      mockSomeService = fixture.debugElement.injector.get(DataService);
      spyOn(mockSomeService, 'getData').and.returnValue(Observable.of(results));
      component.ngOnInit();
      fixture.detectChanges();
    }));
  });

  // afterEach(() =&gt; {
  //   fixture = undefined;
  // });

  it('method should be called', async () =&gt; {
    component.ngOnInit();
    mockSomeService.getData();
    expect(fixture.debugElement.componentInstance.data.length).toEqual(2);
  });
});
</code></pre>

<p>if I use 
 component.ngOnInit();
it is giving error as</p>

<pre><code>TypeError: Cannot read property 'ngOnInit' of undefined
</code></pre>

<p>if I'm not using component.ngOnInit()
it is giving me error as</p>

<pre><code>TypeError: Cannot read property 'getData' of undefined
</code></pre>

<p>How can I overcome this problem?
Thanks in advance.</p>
",https://stackoverflow.com/questions/55149165/cannot-read-property-of-undefined-ngoninit-getdata-angular-unit-testing-jasm,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",5345,True,2,1
Material-UI createShallow to retrieve component for enzyme unit testing fails,"<p>I'm trying to implement a simple unit test with Enzyme on Material-UI with a component inside MuiThemeProvider. To test a basic version I took the example from the <a href=""https://material-ui.com/guides/testing/"" rel=""nofollow noreferrer"">manual</a> but whenever I run <code>npm test</code> I get the error below. </p>

<p>Any advice on how I can retrieve a component from inside a MuiThemeProvider to use later in a dive and finally in a unit test? </p>

<pre><code>  Cannot find module 'react' from 'MuiThemeProvider.js'

    However, Jest was able to find:
        './MuiThemeProvider.d.ts'
        './MuiThemeProvider.js'

    You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'json', 'jsx', 'ts', 'tsx', 'node'].

    See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

      at Resolver.resolveModule (node_modules/jest-runtime/node_modules/jest-resolve/build/index.js:259:17)
      at Object.&lt;anonymous&gt; (../../../node_modules/@material-ui/core/styles/MuiThemeProvider.js:26:37)
</code></pre>

<p>My minimal test and component are defined below in file <code>test/ButtonTest.js</code>:</p>

<pre><code>import * as React from 'react'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import RaisedButton from 'material-ui/RaisedButton'

import { createShallow } from '@material-ui/core/test-utils';

export function MyComponent() {
    return (&lt;MuiThemeProvider&gt;
      &lt;React.Fragment&gt;
        &lt;RaisedButton
                    label='Next'
                    primary={true}
                /&gt;
        &lt;/React.Fragment&gt;
        &lt;/MuiThemeProvider&gt;
        );
}

describe('&lt;MyComponent /&gt;', () =&gt; {
  let shallow;

  beforeAll(() =&gt; {  
    shallow = createShallow();
  });

  it('should work', () =&gt; {
    const wrapper = shallow(&lt;MyComponent /&gt;);
    // TODO: write test
    });
});
</code></pre>

<p>My setup is defined as below in <code>test/setupTests.js</code>,</p>

<pre><code>import React from 'react'
import Enzyme, { shallow, render, mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

// React 16 Enzyme adapter
Enzyme.configure({ adapter: new Adapter() })

// Make Enzyme functions available in all test files without importing
global.React = React
global.shallow = shallow
global.render = render
global.mount = mount
</code></pre>

<p>I found that the problem can be related to babel and therefore configured the <code>.babelrc</code> in the project as follows,</p>

<pre><code>{
  ""env"": {
    ""test"": {
      ""presets"": [""@babel/preset-env"", ""@babel/preset-react""],
      ""plugins"": [""transform-export-extensions""],
      ""only"": [
        ""./**/*.js"",
        ""node_modules/jest-runtime""
      ]
    }
  },
  ""presets"": [""@babel/preset-react""]
}
</code></pre>

<p>The essential bits from my package.json are,</p>

<pre><code>""dependencies"": {
    ""enzyme"": ""~3.10.0"",
    ""enzyme-adapter-react-16"": ""~1.14.0"",
    ""material-ui"": ""~0.20.2"",
    ""react"": ""~16.9.0"",
    ""react-dom"": ""~16.9.0"",
    ""react-icons"": ""~3.7.0"",
    ""react-scripts"": ""~3.1.1"",
    ""react-test-renderer"": ""~16.9.0"",
    ""react-validation-framework"": ""^5.1.0""
  },
  ""devDependencies"": {
    ""@babel/preset-react"": ""^7.0.0"",
    ""babel-plugin-transform-export-extensions"": ""^6.22.0"",
    ""babel-preset-env"": ""~1.7.0"",
    ""enzyme-to-json"": ""^3.4.0""
  }
</code></pre>
",https://stackoverflow.com/questions/57779082/material-ui-createshallow-to-retrieve-component-for-enzyme-unit-testing-fails,"['javascript', 'reactjs', 'jestjs', 'material-ui', 'enzyme']",436,False,2,0
Import Kafka MockAdminClient for unit testing my Kafka application using maven,"<p>I would like to use <code>MockAdminClient</code> for unit testing my Kafka application. How can I make <code>MockAdminClient</code> imported using <code>maven</code>?</p>

<p><a href=""https://github.com/apache/kafka/blob/2.3.0/clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java"" rel=""nofollow noreferrer"">https://github.com/apache/kafka/blob/2.3.0/clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java</a></p>

<p><strong>UPDATE:</strong></p>

<p>My kafka-client related pom.xml</p>

<pre><code>&lt;dependency&gt;
   &lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
   &lt;artifactId&gt;kafka-clients&lt;/artifactId&gt;
    &lt;version&gt;${kafka.version}&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>

<p>By referring test by maven I found sth like this
<a href=""https://stackoverflow.com/questions/29653914/how-can-i-reference-unit-test-classes-of-a-maven-dependency-in-my-java-project"">How can I reference unit test classes of a maven dependency in my java project?</a></p>
",https://stackoverflow.com/questions/57256737/import-kafka-mockadminclient-for-unit-testing-my-kafka-application-using-maven,"['java', 'apache-kafka']",1027,True,2,2
How to make runBlocking wait for &quot;all threads&quot; in Unit Testing?,"<p>I'm trying to write a unit test for <code>getUser()</code> function:</p>

<pre><code>fun getUser(userId:Int) {
    // some code...

    launchDataOperation { api.getUser(userId) }
}
</code></pre>

<p>The issue I can see (but don't know how to resolve in a clean way) is  <code>launchDataOperation(...)</code> creates a coroutine to call suspend function <code>api.getUser</code>:</p>

<pre><code>fun launchDataOperation(block: suspend () -&gt; Unit): Job {
    return coroutineScope.launch {
        try {
            setLoading(true)
            block()
        } catch (error: NetworkConnectionException) {
            setError(Errors.NETWORK_CONNECTION_ERROR)
        } catch (error: DataOperationException) {
            setMessage(error.getErrors())
        } finally {
            setLoading(false)
        }
    }
}
</code></pre>

<p>This is my failing test:</p>

<pre><code>@Test
fun `error message is displayed if api error occurred`() {
    val exception = DataOperationException(listOf(""FATAL ERROR""))

    runBlocking {
        `when`(api.getUser(anyInt())).thenAnswer { throw exception }

        subject.getUser(userId)

        // execution fails if the below line is commented
        // this is not the correct way to wait for other coroutines
        delay(500)  // wait for 500ms till the other coroutines finish

        assertThat(subject.messages.value).isEqualTo(exception.getErrors())
    }
}
</code></pre>
",https://stackoverflow.com/questions/55768536/how-to-make-runblocking-wait-for-all-threads-in-unit-testing,"['mockito', 'kotlin-coroutines']",339,False,2,0
How to fix @testable import failed to load module in xcode unit testing,"<p>I had created an Xcode project without unit testing. I have added cocoa pods when I try to create a new unit testing and try to import @testable import 'ProjectName' it gives an error  Failed to load module 'ProjectName'. can u please help me out to solve the problem</p>

<p>@testable import 'ProjectName' Failed to load module</p>
",https://stackoverflow.com/questions/56163189/how-to-fix-testable-import-failed-to-load-module-in-xcode-unit-testing,"['xcode', 'unit-testing', 'cocoapods']",5829,True,13,3
Django Unit Testing &#39;else&#39; statement in a View to achieve coverage,"<p>I'm running django test coverage for my <code>interface</code> app. The view below calls a <code>WelcomeMessage</code> model and basically says if there are no messages in that queryset it defaults to the ""Welcome.."" and if there are more than 1 ""active"" it will show the most recent one. Basically, how do I test the <code>else</code> line, when there there are more than 1 active messages?</p>

<p>I've tried creating two different instances of <code>WelcomeMessage</code> with one being more recent, but when I run coverage it still highlights the <code>else</code> segment as red. </p>

<p>Running coverage with:
<code>coverage run --source='.' manage.py test interface</code></p>

<p>view:</p>

<pre><code>def index(request):

    msg = WelcomeMessage.objects.filter(active=True).order_by('-modified_at')
    if len(msg) == 0:
        msg = ""Welcome message""
    else:
        msg = msg[0] # -- Need test coverage here --

    context = {'msg': msg}
    return render(request, 'interface/index.html', context)
</code></pre>

<p>unittest:</p>

<pre><code> def test_indexWelcomeMessage(self):
        welcome1 = WelcomeMessage.objects.create(
            created_at=datetime(2019, 1, 1),
            modified_at=datetime(2019, 1, 1),
            active=True,
            msg=""Welcome message""
        )
        welcome2 = WelcomeMessage.objects.create(
            created_at=datetime.now(),
            modified_at=datetime.now(),
            active=True,
            msg=""Recent welcome message""
        )
        messages = WelcomeMessage.objects.filter(
            active=True).order_by('-modified_at')

        if len(messages) == 0:
            msg = ""testing this message""
        else:
            msg = messages[0]
        recentMsgVal = getattr(welcome2, 'msg')
        msg = messages[0]
        expectedMsgVal = messages.values_list('msg', flat=True).first()
        self.assertNotEqual(len(messages), 0)
        self.assertEqual(recentMsgVal, expectedMsgVal) # These asserts pass, but no coverage.
</code></pre>

<p>WelcomeMessage model:</p>

<pre><code>class WelcomeMessage(models.Model):
    created_at = models.DateTimeField(
        auto_now_add=True, verbose_name='Created')
    modified_at = models.DateTimeField(
        auto_now=True, verbose_name=""Last change"")
    active = models.BooleanField(default=True)
    msg = models.TextField(null=True, verbose_name='Message')
</code></pre>

<p>How do write a test so that it has coverage of the <code>else</code> statement?</p>
",https://stackoverflow.com/questions/57960640/django-unit-testing-else-statement-in-a-view-to-achieve-coverage,"['python', 'django', 'unit-testing', 'code-coverage']",692,True,1,1
how to retrieve response data when unit testing async redux action,"<p>I'm trying to make this test, test the <code>getImages</code> action function. I'm getting this error</p>

<blockquote>
  <p>● should getImages from action function  › should getImages from
  action function</p>

<pre><code>expect(received).toEqual(expected) // deep equality

Expected: {""data"": {}, ""type"": ""GET_IMAGES""}
Received: [Function anonymous]
</code></pre>
</blockquote>

<p>ideally I want to pass in the response data, in the data object. How would I successfully do this to make the test pass?</p>

<p><strong>imageActions</strong></p>

<pre class=""lang-js prettyprint-override""><code>import { GET_IMAGES, POST_COMMENT, DELETE_IMAGE, UPLOAD_IMAGE } from './types';
import Axios from '../Axios';

export const getImages = () =&gt; {
  return dispatch =&gt; {
    return Axios.get('/images/uploads').then(response =&gt; {
      const data = response.data;
      dispatch({
        type: GET_IMAGES,
        data
      });
    });
  };
};
</code></pre>

<p><strong>imageActions.test.js</strong></p>

<pre class=""lang-js prettyprint-override""><code>import React from 'react';
import { shallow, mount } from 'enzyme';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { getImages } from './imageActions';
import { GET_IMAGES } from './types';

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

describe('should getImages from action function ', () =&gt; {
  it('should getImages from action function', () =&gt; {
    const expected = {
      type: GET_IMAGES,
      data: {}
    };
    const actual = getImages();
    expect(actual).toEqual(expected);
  });
});
</code></pre>
",https://stackoverflow.com/questions/56678555/how-to-retrieve-response-data-when-unit-testing-async-redux-action,"['reactjs', 'redux', 'jestjs', 'enzyme']",66,False,2,1
"Why am i getting this error, while unit testing ngrx-effect","<p>I'm writing unit tests for ngrx effects. I tried it all but it seems that i can't get past this error:</p>

<pre><code>Expected $[0].notification.kind = 'E' to equal 'N'.
Expected $[0].notification.value = undefined to equal Object({ vendors: [ Object({ id: 1234, code: 'tst', name: 'test', freePlay: true, freeSpin: false, disabled: true, active: false }) ], type: '[CasinoVendors API] Get Vendors Success' }).
Expected $[0].notification.error = TypeError: Cannot read property 'sort' of undefined to equal undefined.
Expected $[0].notification.hasValue = false to equal true.
</code></pre>

<p>The effect that I'm trying to test is:</p>

<pre><code>getVendors$ = createEffect(() =&gt; this.actions$.pipe(
    ofType(CasinoVendorsActions.getVendors),
    concatMap(() =&gt; this.casinoVendorsSvc.getVendors()
      .pipe(
        map((data: any) =&gt; {
          let vendors: VendorModel[] = data

          return CasinoVendorsActions.getVendorsSuccess({vendors: vendors});
        })
      ))
    )
  );
</code></pre>

<p>the unit test:</p>

<pre><code>describe('getVendors', () =&gt; {
    it('should return a stream with getVendorsSuccess action', () =&gt; {
      const vendors: VendorModel[] = [{
        id: 1234,
        code: 'tst',
        name: 'test',
        freePlay: true,
        freeSpin: false,
        disabled: true,
        active: false,
      }];
      const action = CasinoVendorsActions.getVendors();
      const outcome = CasinoVendorsActions.getVendorsSuccess({vendors: vendors});

      actions$ = hot('-a', { a: action });
      const response = cold('-a|', { a: vendors });

      casinoVendorsSvc.getVendors.and.returnValue(response);

      const expected = cold('--b', { b: outcome });

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

<p>Since the effect returns action ""getVendorsSuccess"" filled with correct data, i suspect that the problem is in this part:</p>

<pre><code>const expected = cold('--b', { b: outcome });

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

<p>Any suggestions would be highly appreciated</p>
",https://stackoverflow.com/questions/57903145/why-am-i-getting-this-error-while-unit-testing-ngrx-effect,"['angular', 'unit-testing', 'jasmine', 'ngrx', 'jasmine-marbles']",1527,False,1,1
Unit testing if file exists in local file system via Spark,"<p>I am able to test the below code successfully in EMR cluster via spark. But I am not able to write unit test case with local file system in intelliJ. Could anyone please help me with how to specify local file system in intelliJ in below code.</p>

<p>Working in EMR cluster</p>

<pre><code>FileSystem.get(new URI(""s3n://bucket""), sc.hadoopConfiguration).exists(new Path(""/path_to_check""))
</code></pre>

<p>Doesn't work in intelliJ. It always returns false</p>

<pre><code>FileSystem.get(new URI(""file://somelocal/bucket""), sc.hadoopConfiguration).exists(new Path(""/some/local/path_to_check""))
</code></pre>
",https://stackoverflow.com/questions/55381765/unit-testing-if-file-exists-in-local-file-system-via-spark,"['amazon-web-services', 'apache-spark', 'amazon-s3', 'apache-spark-sql', 'hdfs']",804,False,1,1
Spring Boot service layer unit testing with Mockito - mocked data nulled,"<p>I'm trying to test service layer using Mockito with JUnit but each time when I run it return object gets nulled.</p>

<p>More info:</p>

<ul>
<li>UserRepository is a plain spring data repository extending CRUDRepository.</li>
<li>User is a plain JPA entity.</li>
</ul>

<p>and test:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService = new UserService();

    private User user;

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

    @Test
    public void tesGetUserIdStatus() {

        // given
        user = new User();
        user.setUserName(userName);
        user.setUserId(userId);

        User newUser = new User();

        // when
        Mockito.when(userRepository.findByUserId(userId)).thenReturn(newUser);
        User result = userService.getUserById(user);

        // then
        Assert.assertEquals(newUser, user);
    }

}
</code></pre>

<p>That test will end up that expected object values get nulled when actual are correct.</p>

<p>Service part which I want to test looks like:</p>

<pre><code>@Component
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
    this.userRepository = userRepository;
}

    public User getUserById(User user) throws EntityNotFoundException {


        String userId = user.getUserId();

        user = userRepository.findByUserId(userId);

        return user;
    }
...
</code></pre>
",https://stackoverflow.com/questions/54952928/spring-boot-service-layer-unit-testing-with-mockito-mocked-data-nulled,"['java', 'spring', 'spring-boot', 'mockito']",4423,True,1,3
How to create a MotionEvent for unit testing in Android Studio?,"<p>I want to test a joystick module, to be more specific i'm trying to test axis movement, but i can't because MotionEvent.obtain seems to be returning a null value.</p>

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

<pre><code>public void test_onGenericMotionEvent() {
    MotionEvent motionEvent;
    // Motion joystick event test
    motionEvent = MotionEvent.obtain(200, 300,
            MotionEvent.ACTION_MOVE, 1.0f, 0.0f, 0);
    motionEvent.setSource(InputDevice.SOURCE_JOYSTICK); // &lt;-- ERROR
    assertTrue(joystickView.onGenericMotionEvent(motionEvent));
}
</code></pre>

<p>And i'm getting this error:</p>

<pre><code>java.lang.NullPointerException
    at com.aquarov.rovcontrollerclient.JoystickViewUnitTest.test_onGenericMotionEvent(JoystickViewUnitTest.java:33)
    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.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/55002864/how-to-create-a-motionevent-for-unit-testing-in-android-studio,"['android', 'unit-testing']",818,True,1,1
&quot;Cannot access disposed object&quot; Error on VS SQL Unit Testing Project,"<p>I have been working on a SQL Server (SSDT) solution on VS 2017, which includes SQL unit test projects that were created by right clicking on items on the SQL project and selecting ""Create Unit Tests..."".</p>

<p>I configure the connections by right clicking on the unit testing projects and selecting ""SQL Server Test Configuration..."", which opens a popup to define which database the tests will run in.</p>

<p>I opened this solution on my second laptop for the first time and realised that when I click on ""SQL Server Test Configuration..."" I get an error that says: ""Cannot access a disposed object. Object name: 'ComboBox'""</p>

<p>I could not find anything related to my situation online, most of which seems to relate to .NET code, whereas I'm struggling with the VS interface. I tried uninstalling and re-installing VS 2017 (15.9.9), created a brand new SQL project and a corresponding unit test. Problem persists.</p>

<p>The problem does not exist in my other laptop and a VM I'm using. My second laptop has a lot more legacy things installed but I need to use it because its specs are much higher and has a SQL server on it.</p>

<p>Any ideas as to what I can try?</p>
",https://stackoverflow.com/questions/55160595/cannot-access-disposed-object-error-on-vs-sql-unit-testing-project,"['visual-studio-2017', 'sql-server-data-tools', 'sql-server-unit-testing']",765,True,1,1
How to do unit testing retrofit api calls with viewmodel + livedata?,"<p>I just learned about Android unit testing. I want to implement a unit testing API retrofit call with viewmodel + livedata to my exercise project.
This is one of the viewmodel class.</p>

<pre><code>class NextMatchViewModel(league : League, application: Application): AndroidViewModel(application) {

// get idLeague passing for call getNextMatch()
private val _idLeague = MutableLiveData&lt;League&gt;()
private val idLeague: LiveData&lt;League&gt;
    get() = _idLeague

// next match liveData
private val _nextMatch = MutableLiveData&lt;List&lt;Match&gt;&gt;()
val nextMatch: LiveData&lt;List&lt;Match&gt;&gt;
    get() = _nextMatch

init {
    //get _idLeague value from argument(SafeArgs)
    _idLeague.value = league

    getNextMatch()
}

private fun getNextMatch() {

    idLeague.value?.idLeague?.let {
        LeagueApi.retrofitService.getNextMatch(it).enqueue(object : Callback&lt;MatchResponse&gt;{
            override fun onFailure(call: Call&lt;MatchResponse&gt;, t: Throwable) {
                Log.d(TAG, t.message!!)
            }

            override fun onResponse(call: Call&lt;MatchResponse&gt;, response: Response&lt;MatchResponse&gt;) {
                _nextMatch.value = response.body()?.events
                Log.d(TAG, ""success"")
            }

        })
    }
}

companion object {
    private val TAG = NextMatchViewModel::class.java.simpleName
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/59172360/how-to-do-unit-testing-retrofit-api-calls-with-viewmodel-livedata,"['android', 'unit-testing']",2272,False,1,2
How to get value of nested props function for unit testing,"<p>I have an issue with getting value of nested props function.</p>

<p><code>this.props.user.getPerson().getData()</code></p>

<p><code>getPerson</code> returns new object with person related data.</p>

<p><code>getData</code> returns person related data.</p>

<p>It's separated for readability and I want to make it work for unit testing.</p>

<p>Test 1: </p>

<pre><code> let _wrapper,
    initialProps

  beforeEach(() =&gt; {
    initialProps = {
      user: {
        getPerson: () =&gt; {}
      }
    }
    _wrapper = shallow(&lt;Test1 {...initialProps} /&gt;)
  })
some tests...
})
</code></pre>

<p>It returned <code>TypeError: Cannot read property 'getData' of undefined</code>.</p>

<p>Test2</p>

<pre><code> let _wrapper,
    initialProps

  beforeEach(() =&gt; {
    initialProps = {
      user: {
        getPerson: () =&gt; { getData: () =&gt; {} }
      }
    }
    _wrapper = shallow(&lt;Test2 {...initialProps} /&gt;)
  })
some tests...
})
</code></pre>

<p>It returned <code>TypeError: Cannot read property 'getData' of undefined</code>
Same error as Test1.</p>

<p>I tried to get value of props function by passing function however it didn't work from second function.</p>

<p>How can I get value of nested props function? </p>
",https://stackoverflow.com/questions/54558581/how-to-get-value-of-nested-props-function-for-unit-testing,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",132,True,1,1
flink unit testing - cannot set the context to process all function,"<p>assuming that I have this </p>

<pre><code>class FooProcess extends ProcessAllWindowFunction[String,String, TimeWindow]{
override def process(context: Context, elements: Iterable[String], out: Collector[String]): Unit = ???
}
</code></pre>

<p>I want to write some unit tests to the process method but I am having issues mocking the context </p>

<pre><code>val context =  mock[Context[FooProcess]]
</code></pre>

<p>This import fails (<code>cannot resolve symbol Context</code>) </p>

<pre><code>import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction.Context
</code></pre>

<p>Any idea / best practices for unit testing in flink ?</p>
",https://stackoverflow.com/questions/56315595/flink-unit-testing-cannot-set-the-context-to-process-all-function,"['apache-flink', 'flink-streaming']",770,True,1,1
Unit testing with MockitoJunitRunner: thenReturn always returns null for any(...) matchers,"<p>Using Spring Boot 2.1.6.RELEASE. In an unit test with MockitoJunitRunner, I'm mocking a REST controller as follows:</p>

<pre><code>  @Mock
  private MyController myController;
</code></pre>

<p>Then, I'm defining the expectations of the endpoint call as follows:</p>

<pre><code>when (myController.myEndpoint(any(MyInputDto.class), any(OAuth2Authentication.class))).thenReturn(new ResponseEntity&lt;MyOutputDto&gt;(myOutputDto, HttpStatus.OK));
</code></pre>

<p>But the following call:</p>

<pre><code>ResponseEntity&lt;MyOutputDto&gt; resp = myController.myEndpoint(any(MyInputDto.class), any(OAuth2Authentication.class));
assertNotNull(resp);
</code></pre>

<p>raises java.lang.AssertionError as resp is null. Why is that ? Of course, the two parameters are different instances between the when(...) clause and the call (probably both null), but my understanding is that they don't have to match as I'm using any(...) matcher, meaning that whatever these instances are, the return should be the same.</p>

<p>What am I missing here ?</p>
",https://stackoverflow.com/questions/59068479/unit-testing-with-mockitojunitrunner-thenreturn-always-returns-null-for-any,"['spring-boot', 'mockito', 'junit4']",330,False,1,1
What additional test cases can be included in my Unit Testing?,"<p>Given the following function <code>RhymeOrNot</code> with contains three parameters: a file defined as a string, the first word defined as a string, and the second word defined as a string. This function will return a boolean indicating whether or not the words rhyme. A word rhyme with another word if the last vowel and every word after are the same. Both words need to be in the file containing a dictionary of the word and their pronunciation. If neither words or in the file, return false. </p>

<p>Sample File Looks Similar To This:</p>

<pre><code>PHOTOGRAPH  F OW1 T AH0 G R AE2 F
STAFF  S T AE1 F
</code></pre>

<p>Here is a Unit Test in Python to test the function</p>

<pre><code>class TestRhyme(object):
    def Test(self):
        assert RhymeOrNot(""dictionary.txt"", ""CAT"", ""HAT"") == True
        assert RhymeOrNot(""dictionary.txt"", ""PHOTOGRAPH"", ""STAFF"") == True
        assert RhymeOrNot(""dictionary.txt"", ""TRAIN"", ""SUSTAIN"") == True
        assert RhymeOrNot(""dictionary.txt"", ""GIRL"", ""BOY"") == False
        assert RhymeOrNot(""dictionary.txt"", ""START"", ""HEART"") == True
        assert RhymeOrNot(""dictionary.txt"", ""BERRY"", ""BUILD"") == False
        assert RhymeOrNot(""dictionary.txt"", ""CLASS"", ""PASS"") == True
</code></pre>

<p>Updated:</p>

<pre><code>class TestRhyme(object):
    def Test(self):
        assert RhymeOrNot(""dictionary.txt"", ""CAT"", ""HAT"") == True
        assert RhymeOrNot(""dictionary.txt"", ""PHOTOGRAPH"", ""STAFF"") == True
        assert RhymeOrNot(""dictionary.txt"", ""TRAIN"", ""SUSTAIN"") == True
        assert RhymeOrNot(""dictionary.txt"", ""GIRL"", ""BOY"") == False
        assert RhymeOrNot(""dictionary.txt"", ""START"", ""HEART"") == True
        assert RhymeOrNot(""dictionary.txt"", ""BERRY"", ""BUILD"") == False
        assert RhymeOrNot(""dictionary.txt"", ""CLASS"", ""PASS"") == True
        assert RhymeOrNot(""dictionary.txt"", """", """") == False
        assert RhymeOrNot(""dictionary.txt"", """", ""HAPPY"") == False
        assert RhymeOrNot(""dictionary.txt"", ""HARRYPOTTER"", ""BTW"") == False
        assert RhymeOrNot(""dictionary.txt"", ""AIRPLANE"", """") == False
        assert RhymeOrNot(""dictionary.txt"", ""ABCDE"", ""FGHJI"") == False
        assert RhymeOrNot(""dictionary.txt"", ""air"", """") == False
        assert RhymeOrNot(""dictionary.txt"", """", ""sofa"") == False
        assert RhymeOrNot(""dictionary.txt"", ""&amp;#116;&amp;#114;&amp;#97;&amp;#105;&amp;#110;"", ""&amp;#102;&amp;#108;&amp;#121;"") == False
        assert RhymeOrNot(""dictionary.txt"", ""chair"", ""declare"") == True
        assert RhymeOrNot(""dictionary.txt"", ""slam"", ""ham"") == True
        assert RhymeOrNot(""dictionary.txt"", ""StAiR"", ""PaIr"") == True
        assert RhymeOrNot(""dictionary.txt"", ""pen"", ""hen"") == True
        assert RhymeOrNot("""", ""pen"", ""hen"") == FileNotFoundError
        assert RhymeOrNot(""def"", ""pen"", ""hen"") == FileNotFoundError
</code></pre>

<p>What other additional test cases can I incorporate in my Unit Testing? I want to test every possible test cases out there that follows the function <code>RhymeOrNot</code>.</p>
",https://stackoverflow.com/questions/54717945/what-additional-test-cases-can-be-included-in-my-unit-testing,"['python', 'file', 'unit-testing']",47,True,1,1
Unit testing hybrid C++ / CLI / C# Code in Visual Studio fails,"<p>We have been given a C# DLL which contains code required for loading and manipulating a proprietary data format. Our codebase is primarily native C++. So we can access the supplied library, I wrote a DLL that consists of </p>

<ul>
<li>a native C++ wrapper class that implements the necessary API</li>
<li>A C++/CLI bridge class that marshals data in and out and and delegates calls to the C# DLL.</li>
</ul>

<p>I wrote a basic (native) C++ console application to test that the API does what I wanted. It did. I then wrote a (native, Microsoft Visual Studio) unit test project that calls the API. Surprisingly, it crashes with some unstated exception when constructing the interface object.</p>

<p>Some minimal code:</p>

<p>InteropAPI.h:</p>

<pre><code>#pragma once
#pragma unmanaged

#if defined(INTEROP_API_EXPORTS)
#define INTEROP_API __declspec(dllexport)
#else
#define INTEROP_API __declspec(dllimport)
#endif

#include &lt;string&gt;

class InteropBridgeArchive;

struct InteropRecord
{
    std::string Name;
    int Id;
    std::string Data;
};

class INTEROP_API InteropAPI
{
public:
    InteropAPI();
    ~InteropAPI();

    InteropRecord GetRecord(int id) const;

private:
    InteropBridgeArchive * impl_;
};
</code></pre>

<p>InteropAPI.cpp:</p>

<pre><code>#pragma managed
#include ""InteropBridge.h""
#pragma unmanaged
#include ""InteropAPI.h""

InteropAPI::InteropAPI()
: impl_(new InteropBridge())
{   
}

InteropAPI::~InteropAPI()
{
    delete impl_;
}

InteropRecord InteropAPI::GetRecord(const int id) const
{
    return impl_-&gt;GetRecord(id);
}
</code></pre>

<p>InteropBridge.h</p>

<pre><code>#pragma once
#pragma unmanaged
#include ""InteropAPI.h""

#pragma managed

#include &lt;vcclr.h&gt;

class InteropBridge
{
public:
    InteropArchive();
    InteropRecord GetRecord(System::Int32 id) const;

private:
    gcroot&lt;InteropCSharpDll::Archive^&gt; archive_;
};
</code></pre>

<p>InteropBridge.cpp:</p>

<pre><code>#pragma unmanaged
#include &lt;string&gt;
#pragma managed
#include ""InteropBridge.h""
#include &lt;msclr/marshal_cppstd.h&gt;

InteropBridge::InteropBridge()
{
    archive_ = gcnew InteropCSharpDll::Archive;
}

InteropRecord InteropBridge::GetRecord(const System::Int32 id) const
{
    auto return_value = archive_-&gt;GetRecord(id);
    InteropRecord record;
    record.Name = msclr::interop::marshal_as&lt;std::string&gt;(return_value.Name);
    record.Id = return_value.Id;
    record.Data = msclr::interop::marshal_as&lt;std::string&gt;(return_value.Data);
    return record;
}
</code></pre>

<p>The test C# DLL has this:</p>

<pre><code>using System.Linq;

namespace InteropCSharpDll
{
    public struct Record
    {
        public string Name;
        public int Id;
        public string Data;
    }

    public class Archive
    {
        public Record GetRecord(int id)
        {
            return _records.First(r =&gt; r.Id == id);
        }

        private readonly Record[] _records = 
        {
            new Record {Name = ""Foo"", Id = 0, Data = ""Foo.Data""},
            new Record {Name = ""Bar"", Id = 2, Data = ""Bar.Data""},
            new Record {Name = ""Egg"", Id = 7, Data = ""Egg.Data""},
        };
    }
}
</code></pre>

<p>Clearly, if this hybrid structure can't be unit tested as native code, we can't test anything that touches it, so it's quite important to get to the bottom of why it crashes. This code runs nicely as a native C++ project:</p>

<pre><code>#include &lt;cstdio&gt;
#include &lt;iostream&gt;
#include ""../InteropCppCliBridgeDll/InteropAPI.h""

#pragma comment(lib, ""../x64/Debug/InteropCppCliBridgeDll.lib"")

int main(int , char ** )
{
    const InteropAPI archive;
    const auto record = archive.GetRecord(0);
    std::cout &lt;&lt; ""Name: "" &lt;&lt; record.Name &lt;&lt; ""\n"";
    std::cout &lt;&lt; ""Id: "" &lt;&lt; record.Id&lt;&lt; ""\n"";
    std::cout &lt;&lt; ""Data: "" &lt;&lt; record.Data&lt;&lt; ""\n\n"";
}
</code></pre>

<p>whereas in a native unit test project, the crash occurs in or around the line</p>

<pre><code>archive_ = gcnew InteropCSharpDll::Archive;
</code></pre>
",https://stackoverflow.com/questions/57807810/unit-testing-hybrid-c-cli-c-code-in-visual-studio-fails,"['c#', 'c++', 'visual-studio', 'unit-testing', 'c++-cli']",759,False,1,0
Having issue with Symfony 3 Unit testing that has session enabled,"<p>I am new in unit testing. I have Symfony 3 console command application which is using symfony session for temporary data store.</p>

<p>In my unit test class I extend KernelTestCase which give me error while I tested it but if I extend <code>Symfony\Component\HttpKernel\EventListener\TestSessionListener</code> class then the error gone and passed the test.</p>

<p>After some time I realize that it always passed test no mater what I write inside the test case.</p>

<h3>My Console class</h3>

<pre><code>protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Retrieve the argument value using getArgument()
        $csv_name = $input-&gt;getArgument('file');

        // Check file name
        if ($csv_name == 'input.csv') {
            // Get input file from filesystem
            $csvData = array_map('str_getcsv', file($this-&gt;base_path.'/../web/'.$csv_name));
            $formatData = Helpers::formatInputData($csvData);

            // Start session
            $session = new Session();
            $session-&gt;start();

            foreach ($csvData as $key =&gt; $data) {
                if (!empty($data[0])) {
                    $validation = Validator::getInformationData($data, $formatData[$data[1]]);
                    if (!empty($validation)) {
                        $output-&gt;writeln($validation);
                    } else {
                        $output-&gt;writeln('valid');
                    }
                }
            }
        } else {
            $output-&gt;writeln('Invalid file!');
        }
    }
</code></pre>

<h3>My test case</h3>

<pre><code>use Symfony\Component\HttpKernel\EventListener\TestSessionListener as BaseTestSessionListener;

class DocumentCommandTest extends BaseTestSessionListener
{
    /**
     * Test Execute
     *
     */
    public function testExecute()
    {
        $kernel = static::createKernel();
        $kernel-&gt;boot();

        $application = new Application($kernel);
        $application-&gt;add(new DocumentCommand($kernel-&gt;getContainer()));

        $command = $application-&gt;find('identification-requests:process');
        $commandTester = new CommandTester($command);
        $commandTester-&gt;execute(array(
            'command' =&gt; $command-&gt;getName(),
            'file' =&gt; 'input.csv'
        ));

        $output = $commandTester-&gt;getOutput();
        $this-&gt;assertContains('valid',$output);
    }
}
</code></pre>

<p>After that I also tried to extend <code>Symfony\Bundle\FrameworkBundle\Tests\Functional\SessionTest</code></p>

<pre><code>use Symfony\Bundle\FrameworkBundle\Tests\Functional\SessionTest;

class DocumentCommandTest extends SessionTest
{
</code></pre>

<p>but it give me the following error</p>

<pre><code>E.........                                                        10 / 10 (100%)

Time: 4.72 seconds, Memory: 20.00MB

There was 1 error:

1) Tests\AppBundle\Command\DocumentCommandTest::testExecute
InvalidArgumentException: The option ""test_case"" must be set.
</code></pre>

<p>My expected output from console is the following that needs to be tested</p>

<pre><code>$ php bin/console identification-requests:process input.csv
valid
valid
valid
document_number_length_invalid
request_limit_exceeded
valid
document_is_expired
valid
document_type_is_invalid
valid
valid
document_number_invalid
valid
document_issue_date_invalid
</code></pre>
",https://stackoverflow.com/questions/57699632/having-issue-with-symfony-3-unit-testing-that-has-session-enabled,"['php', 'unit-testing', 'session', 'console-application', 'symfony-3.4']",303,True,1,2
Redux Container Unit Testing - Unable to access props for wrapped component,"<p>Following the React v6 upgrade, my existing test cases for the component are failing.</p>

<p>Here is my component container code TodoContainer.jsx:</p>

<pre><code>import { connect } from 'react-redux';

import Todo from './Todo';
import { initialLoadExecuted } from '../../actions/LoadActions';

const mapStateToProps = state =&gt; ({
  isCollapsed: true,
  pinnedTiles: false,
});

const mapDispatchToProps = dispatch =&gt; ({
  dispatchInitialLoadExecuted: (tiles) =&gt; {
    dispatch(initialLoadExecuted(tiles));
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(Todo);
</code></pre>

<p>Here is my test code TodoContainer.test.jsx:</p>

<pre><code>    import React from 'react';
    import configureStore from 'redux-mock-store';
    import {Provider} from 'react-redux';
    import TodoContainer from '../../../../src/todo-component/components/Todo/TodoContainer';
    import { initialLoadExecuted } from '../../../../src/todo-component/actions/LoadActions';

    const mockStore = configureStore();
    let store;

    describe('Todo Container', () =&gt; {
      beforeEach(() =&gt; {
        store = mockStore({
        });

      it('maps state props correctly', () =&gt; {
        const wrapper = shallow(&lt;TodoContainer store={store}/&gt;);
        wrapper.prop('dispatchInitialLoadExecuted')('Test String);
        // Expect statements
      });
    });
</code></pre>

<p>The error i am getting is :</p>

<p>Invariant Violation: Passing redux store in props has been removed and does not do anything. To use a custom Redux store for specific components,  create a custom React context with React.createContext(), and pass the context object to React-Redux's Provider and specific components like:  . You may also pass a {context : MyContext} option to connect.</p>

<p>Is there a way to to pass store through provider while accessing the props, the same way?</p>
",https://stackoverflow.com/questions/54115218/redux-container-unit-testing-unable-to-access-props-for-wrapped-component,"['javascript', 'redux', 'react-redux', 'enzyme', 'redux-mock-store']",792,True,1,1
Good practices of writing and unit testing Utility methods in scala,"<p>In particular situations, you need to have some utility methods that are required across different classes. To solve this situation, you create an Util object wherein you place all these methods </p>

<pre><code>object AggregatorUtil {
  def aggregateValues(list : List[BigDecimal]) = //some logic...
}

// Import everything in the Utilities object
import AggregatorUtil._
</code></pre>

<p>and then import whichever members of util are required in your class. However, the downside to this is that, as all your methods are inside the singleton object and <strong>it becomes tricky to mock the object and unit test methods of the class that use utility methods.</strong> </p>

<p>To solve this problem again, the only solution that came to mind was <strong>Extracting the functionality out to a trait and then mocking the trait.</strong></p>

<p>Please let me know if there is any other approach for handling and testing of util methods and which one is a rather cleaner approach. </p>

<p>Thanks in advance !!!</p>

<p>Note: -I am using scalatest and mockito in my project.</p>
",https://stackoverflow.com/questions/54744889/good-practices-of-writing-and-unit-testing-utility-methods-in-scala,"['scala', 'mockito', 'scalatest']",810,True,1,2
Issues when unit testing .net Core app in Azure Dev Ops,"<p>I have a .net core 2.2 project, with some unit tests that test a class library project using Visual Studio Testing</p>

<p>Visual Studio Test - YAML</p>

<pre><code>steps:
  - task: VSTest@2
  displayName: 'VsTest - testAssemblies'
  inputs:
    testAssemblyVer2: |
      **\*test*.dll
     !**\*TestAdapter.dll
     !**\obj\**
     **\$(BuildConfiguration)\*\*unittests.dll
     **\$(BuildConfiguration)\*\*test*.dll
     !**\*Microsoft.VisualStudio.TestPlatform*
  vstestLocationMethod: location
  vstestLocation: 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\TestPlatform\'
  codeCoverageEnabled: true
  otherConsoleOptions: '/Framework:.NETCoreApp,Version=v2.2 /logger:console;verbosity=""normal""'
  platform: '$(buildPlatform)'
  configuration: '$(buildConfiguration)'
  timeoutInMinutes: 1
</code></pre>

<p>And the error message</p>

<h2>[warning]No test assemblies found matching the pattern:</h2>

<p><strong>*test*.dll,!</strong>*TestAdapter.dll,!<strong>\obj**,</strong>\Release**unittests.dll,<strong>\Release**test*.dll,!</strong>*Microsoft.VisualStudio.TestPlatform*.</p>

<p>Can anyone identify what needs to be done to make it work?</p>

<p>I have tried various different options for the above</p>
",https://stackoverflow.com/questions/57037968/issues-when-unit-testing-net-core-app-in-azure-dev-ops,"['unit-testing', 'azure-devops', 'asp.net-core-2.2', 'vs-unit-testing-framework']",637,True,1,1
Unit testing a static C++ library using a higher level language?,"<p>I want to write some static C++ libraries in a test-driven style.</p>

<p>I started looking around for C++ unit test frameworks, bu then I wondered why I needed to write test code in C++ at all.</p>

<p>It should be possible to call static C++ libraries from a higher level language where it would be easier to write the tests.</p>

<p>Is this a sensible thought?</p>

<p>Is there any particular language that makes this particularly simple? Whether that's Python, Lua or something else? Even perhaps a special DSL for it?</p>

<p>Any hints for good tutorials?</p>
",https://stackoverflow.com/questions/55233973/unit-testing-a-static-c-library-using-a-higher-level-language,"['c++', 'unit-testing', 'tdd']",249,False,0,1
VS 2017 Live Unit Testing persisted data directory is read only,"<p>I'm having an issue with live unit testing, and have found that the solution may be to set a different persisted data directory (seen below). I try to do this, but that field is read-only for me. Running VS as administrator does nothing. What could cause this?</p>

<p><a href=""https://i.stack.imgur.com/JR3gD.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/JR3gD.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/57171359/vs-2017-live-unit-testing-persisted-data-directory-is-read-only,"['visual-studio', 'live-unit-tests']",61,True,1,1
Error not found for object and value in Scala Unit Testing,"<p>I want to run a unit test named TestEnterNumbers.scala on the following class. I tried running the following but I am getting error: not found: object controller for <code>import controller.Actions.Number</code> and error: not found: value controller  <code>assert(controller.Actions.Number(changeNum, 1) == 1)</code>.</p>

<p>Directory</p>

<pre><code>   src
    |_ changeNum
        |_ controller
        |    |_ Actions.scala
        |_ model
        |    |_ ChangeNum.scala
        |_ tests
            |_ TestEnterNumbers.scala
</code></pre>

<p>TestEnterNumbers.scala</p>

<pre><code>package changeNum.tests

import org.scalatest._
import controller.Actions.Number

class TestEnterNumbers extends FunSuite{
test(""Use many test cases for ChangeNum""){
    assert(controller.Actions.Number(changeNum, 0) == 0)
    assert(controller.Actions.Number(changeNum, 223) == 223)
    assert(controller.Actions.Number(changeNum, 4061) == 4061)
    assert(controller.Actions.Number(changeNum, 99806) == 99806)
}
}
</code></pre>

<p>ChangeNum.scala</p>

<pre><code>class ChangeNum() {

def current(): Double = {
    0.0
}
}
</code></pre>

<p>Actions.scala</p>

<pre><code>package changeNum.controller

import javafx.event.ActionEvent
import javafx.event.EventHandler

class Number(changeNum: ChangeNum, number: Int) extends 
EventHandler[ActionEvent] {
var changeNumber = changeNum.toString
override def handle(event: ActionEvent): Unit = {
changeNumber.concat(number.toString)
changeNumber.toDouble
}
}
</code></pre>
",https://stackoverflow.com/questions/55107875/error-not-found-for-object-and-value-in-scala-unit-testing,"['scala', 'unit-testing', 'class', 'methods']",902,True,0,1
Unit testing router logic by separating it into its own controller,"<p>I have a route handler as such: <code>app.use('/authorization', authorization);</code> which has a router handler defined as </p>

<pre><code>router.get('/', (req, res, next) {
    handleResponse(err, response, data) {
        // ...
    }

    sessionService.getSession(req, res, req,query.code, handleResponse);
});
</code></pre>

<p>I'm struggling to find a way to unit test this and as my first solution, I considered removing all of the business logic into a separate controller so that it could be tested independently of the router.</p>

<p>This is a sample implementation of my controller:</p>

<pre><code>module.exports = class AuthorizationController {
    constructor(req, res, next) {
        this.req = req;
        this.res = res;
        this.next = next;
    }

    handleResponse(err, response, data) {
        // do things with this.req, this.res and this.next
    }
};
</code></pre>

<p>From my router, I have been calling it as such:</p>

<pre><code>router.get('/', (req, res, next) {
    sessionService.getSession(req, res, req,query.code, (new AuthorizationController(req, res, next)).handleResponse);
});
</code></pre>

<p>The controller is successfully initialized (during its construction) but the <code>this</code> references inside of the <code>handleResponse</code> method are <code>undefined</code> once its called.</p>

<p>Is this the correct way of separating out my methods from my router? If so, is there a way to initialize the <code>req, res and next</code> properties of my controller so that they persist for the lifetime of the class? </p>

<p><code>this</code> is undefined presumably because of where the class is created vs where the method <code>handleResponse</code> is called.</p>
",https://stackoverflow.com/questions/57739557/unit-testing-router-logic-by-separating-it-into-its-own-controller,"['node.js', 'express']",14,False,0,0
Angular Unit Testing: Why my expect(1).toBe(2) always passes?,"<p>I have figured out that probably my test is never getting executed. Because the color of the test description in the output is neither green nor red. 
May be I am wrong. 
I have also figured out that it works fine if I comment out <code>component.ngOnInit();</code>
I am providing all of my spec file code without leaving out anything that could be the problem. </p>

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

<p><strong>SPEC</strong></p>

<pre><code>class AppConstantsStub {
  public userPreferences = {
    modelData: {
      basicDetails: {
        itemId: 3 // some other valid value here is fine
      }
    },
    UserBasicDetails: {
      // some valid values here, maybe
    }
  };
}
class ComponentDetailsServiceStub {
  defaultProperties = {
    editable: false,
    showToolbar: false,
    viewMode: false,
    editMode: false,
    showPopup: true,
    formSavedClicked: false,
    cancelClicked: false,
    refresh: false,
   };

  push(value){
    this.propertiesSource.next(value);
  }
  private propertiesSource = new BehaviorSubject(this.defaultProperties);
  currentProperties = this.propertiesSource.asObservable();



  setDefaultCancelClicked() { }
}
class SearchAPIServiceStub {


}
class UOMServiceStub { }
class BomDetailsServiceStub { }
class FormBuilderUtilsServiceStub { }
class DMServiceStub { }
class GlobalLoaderServiceStub {
  hideLoader() { }
}
class SCNotificationServiceStub { }
class CreateRfxServiceStub { }
class LayoutServiceStub { }
class GridFilterServiceStub {
  searchConfig() { return null; }
}

describe('component details', () =&gt; {
  let componentDetailsComponent: ComponentDetailsComponent;
  let subject: ComponentDetailsComponent;
  let formBuilderUtilsService: FormBuilderUtilsService;
  let appConstants: AppConstants;
  let componentDetailsService: ComponentDetailsServiceStub;
  let dMService: DMService;
  let globalLoaderService: GlobalLoaderServiceStub;
  let sCNotificationService: SCNotificationService;
  let createRfxService: CreateRfxService;
  let layoutService: LayoutService;
  let gridFilterService: GridFilterService;

  let mode: string;

  let fixture: ComponentFixture&lt;ComponentDetailsComponent&gt;;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ComponentDetailsComponent],
      providers: [

        { provide: FormBuilderUtilsService, useClass: FormBuilderUtilsServiceStub },
        { provide: AppConstants, useClass: AppConstantsStub },
        { provide: ComponentDetailsService, useClass: ComponentDetailsServiceStub },
        { provide: DMService, useClass: DMServiceStub },
        { provide: GlobalLoaderService, useClass: GlobalLoaderServiceStub },
        { provide: SCNotificationService, useClass: SCNotificationServiceStub },
        { provide: CreateRfxService, useClass: CreateRfxServiceStub },
        { provide: LayoutService, useClass: LayoutServiceStub },
        { provide: GridFilterService, useClass: GridFilterServiceStub },

      ],

      schemas: [NO_ERRORS_SCHEMA]
    });
    // subject = TestBed.get(ComponentDetailsComponent);

      fixture = TestBed.createComponent(ComponentDetailsComponent);
      subject = fixture.componentInstance;
       componentDetailsService = TestBed.get(ComponentDetailsService);
     fixture.detectChanges();
  });
  it('should create componentDetailsComponent', () =&gt; {
    expect(1).toBe(2);
  });


}
);
</code></pre>
",https://stackoverflow.com/questions/56706235/angular-unit-testing-why-my-expect1-tobe2-always-passes,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",293,False,0,0
angular5: Uncaught SyntaxError: Unexpected token { in app.service.ts:1 for unit testing,"<p>I keep getting this error Uncaught SyntaxError: Unexpected token { whenever I try to run my angular5 application testcases.</p>

<p>karma.config.js</p>

<pre><code>module.exports = function (config) {
    config.set({
        basePath: '.',
        frameworks: ['jasmine', 'karma-typescript'],
        client: {
            clearContext: false // leave Jasmine Spec Runner output visible in browser
        },
        files: [
            { pattern: './boot-tests.ts' },
            { pattern: '../app/**/*.+(ts|html)' }
        ],
        preprocessors: {
            '**/*.ts': ['webpack', 'karma-typescript']
        },
        karmaTypescriptConfig: {
            bundlerOptions: {
                entrypoints: /\.spec\.ts$/,
                transforms: [
                    require(""karma-typescript-angular2-transform"")
                ]
            },
            compilerOptions: {
                lib: [""ES2015"", ""DOM""]
            }
        },
        //proxies: {
          //  ""../app/"": ""/clientApp/app/""
        //},
        coverageReporter: {
            type: 'html',
            dir: 'coverage/'
        },
        reporters: ['progress', 'karma-typescript'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Chrome'],
        mime: { 'application/javascript': ['ts', 'tsx'] },
        singleRun: true,
        webpack: require('../../webpack.config.js')().filter(config =&gt; config.target !== 'node'), // Test against client bundle, because tests run in a browser
        webpackMiddleware: { stats: 'errors-only' }
    });
};
</code></pre>

<p>I configured my karma.config.js file like above. any ideas why i am getting this error.</p>
",https://stackoverflow.com/questions/54499862/angular5-uncaught-syntaxerror-unexpected-token-in-app-service-ts1-for-unit,"['angular', 'jasmine', 'karma-jasmine']",55,False,0,0
How to implement functional unit testing sinon with mocks in NodeJs?,"<p>How to implement sinon.mock on follwing function.</p>

<blockquote>
  <p>function getDashboard(req,res){
      res.send(""success"");
      }</p>
</blockquote>

<pre><code>describe(""GetDashboard test""){
    it(""Response Should be test"", function(){
        const getDashboard = sinon.stub().returns('success');
        let req = {}     
        let res = {
        send: function(){};
        const mock = sinon.mock(res);     
        mock.expect(getDashboard.calledOnce).to.be.true;      
        mock.verify();
      }    
    })
}
</code></pre>

<p>Also how to stubbing data in function.Is it correct way of mocking.</p>
",https://stackoverflow.com/questions/55452585/how-to-implement-functional-unit-testing-sinon-with-mocks-in-nodejs,"['node.js', 'sinon']",97,False,0,1
"Unit testing angular service, Injecting dependencies through beforeeach doesn&#39;t get executed","<p>I am trying to unit test a component that has a @viewChild component and few more services.</p>

<p>Following is my spec.ts file. </p>

<pre><code>  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ UpStoryComponent,ExperienceListComponent, MdToHtmlPipe, SafeUrlPipe, FormatUrlPipe, CurrencyFormatPipe, NoCommaPipe, MoneyPipe, SafeHtmlPipe],
      imports: [ FormsModule, HttpClientTestingModule, RouterTestingModule],
      providers: [{ provide: ActivatedRoute, useValue: {'params': Observable.from([{ 'id': 1}])}, ContentfulService, MatchingFlowService, FormDataService, LocalStorageService, ScrollService, Title, UpnorwayLoaderService, MoneyService, DayCalculatorService],
      schemas: [NO_ERRORS_SCHEMA]    
    }).compileComponents();
  });


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

  beforeEach(() =&gt; {
    contentfulService = TestBed.get(ContentfulService);
    spyOn(contentfulService, 'getEntryBySlug').and.callFake(function (args) {
      return of(blogPost);
    });
    fixture.detectChanges();
  });


  it('should create', () =&gt; { 
    expect(component).toBeTruthy();
  }); 
</code></pre>

<p>The last beforeeach statement gets executed, but does not inject service as expected. If I place the last beforeeach statement as the second beforeeach, then the current second beforeeach doesn't get executed as expected. </p>

<p>There is no dependency between <code>ExperienceListComponent</code> and <code>ContentfulService</code>. But when injecting these two services through beforeach statements, only the first inject works, not the other. </p>

<p>What could be the reason for this? Appreciate if you could provide a solution for this. </p>
",https://stackoverflow.com/questions/58211476/unit-testing-angular-service-injecting-dependencies-through-beforeeach-doesnt,"['angular', 'unit-testing', 'dependency-injection', 'karma-jasmine', 'viewchild']",52,False,0,0
Error: Expected spy MovieService.getWatchListedMovies to have been called. angular Unit Testing,"<ul>
<li><p>A component file called <strong>watchlist</strong> which dependent on
<strong>MovieService(service)</strong> to fetch movie.</p></li>
<li><p>calling ngOnInit() will invoke MovieService.getWatchlistedMovies()</p></li>
<li><p>the component code is given below,</p></li>
</ul>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>export class WatchlistComponent implements OnInit {

  movies: Array&lt;Movie&gt;;
  movieType:string;
  
  constructor(private movieService:MovieService,private route:ActivatedRoute) { 

    this.movies=[];
    this.route.data.subscribe((data)=&gt;{
      this.movieType=data.movieType
    });
   
  }

  ngOnInit() {

    this.movieService.getWatchListedMovies()
    .subscribe((movies)=&gt;{
     this.movies.push(...movies);
       },
       this.handleErrors()
       );

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

<ul>
<li><p>Unit testing on the <strong>component(watchlist)</strong> using <em>jasmine.spy</em> object on <strong>movieService(Service)</strong>  </p></li>
<li><p>watchlist.spec.ts file code as follow,</p></li>
</ul>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe('WatchlistComponent', () =&gt; {
  let component: WatchlistComponent;
  let fixture: ComponentFixture&lt;WatchlistComponent&gt;;
  let movieServiceFake:jasmine.SpyObj&lt;MovieService&gt;;
  let movieService;
  let stubTmdbMovies: Movie[];
  beforeEach(async(() =&gt; {
    movieServiceFake = jasmine.createSpyObj('MovieService', ['getWatchListedMovies']);


    TestBed.configureTestingModule({
      imports: [MovieModule,
        RouterTestingModule,
        HttpClientTestingModule],
      providers: [{ provide: MovieService, useValue: movieServiceFake }]
    })
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(WatchlistComponent);
    component = fixture.componentInstance;
    movieServiceFake = TestBed.get(MovieService);
  });

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

  it('should call ngOnInIt', () =&gt; {
    //Arrange
    let spyOnComponent = spyOn(component, 'ngOnInit');
    movieServiceFake.getWatchListedMovies.and.callFake(() =&gt; { return of(stubTmdbMovies) });
    //Act
    component.ngOnInit();
    //Assert
    expect(spyOnComponent).toHaveBeenCalled();
    expect(movieServiceFake.getWatchListedMovies).toHaveBeenCalled();//error line
  });
});</code></pre>
</div>
</div>
</p>

<p>`<strong>MovieModule</strong> where I have registered <strong>watchlist</strong> and <strong>MovieService.</strong> as below</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>@NgModule({
  imports: [
    CommonModule,
    HttpClientModule,
    MovieRouterModule,
    MatCardModule,
    MatButtonModule,
    MatSnackBarModule,
    FormsModule,
    ReactiveFormsModule,
    MatInputModule
      ],
  declarations: [ContainerComponent,TmdbContainerComponent,TumbnailComponent, WatchlistComponent, MovieDetailsComponent],
  
  exports:[
    MovieRouterModule,
    TumbnailComponent,
    ContainerComponent,
    TmdbContainerComponent
  ],
  providers:[
    MovieService
  ]
})
export class MovieModule { }</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/54843056/error-expected-spy-movieservice-getwatchlistedmovies-to-have-been-called-angul,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'spy']",84,False,0,1
"Unit testing API with supertest, stubbing mongoose model with chained functions","<p>I am trying to unit test a Node.js+Express REST API. It's all very standard CRUD stuff and the backend database library is MongoDB being called with Mongoose. So far, so standard...</p>

<p>I want to use <a href=""https://github.com/visionmedia/supertest"" rel=""nofollow noreferrer"">SuperTest</a> to test my API controllers/routes, so naturally I need to stub out the database calls</p>

<p>This is where I'm struggling, especially with chained calls such as <code>.limit()</code> and <code>.skip()</code> on my query results.</p>

<p>Trying to stub the mongoose DocumentQuery limit function with sinon doesn't work, e.g.</p>

<pre class=""lang-js prettyprint-override""><code>const stubQuery = sinon.stub(mongoose.DocumentQuery, 'limit')
.callsFake(()=&gt;{})
</code></pre>

<p>Results in an error </p>

<blockquote>
  <p>Trying to stub property 'limit' of undefined</p>
</blockquote>

<p>I've tried using the sinon-mongoose library but I can't get that to work in the context of my API calls in SuperTest. It seems to only be for running tests on the models directly which I'm not doing</p>

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

<pre class=""lang-js prettyprint-override""><code>const app = require('../server').app;

// stub out model.find()
const stubModelFind = sinon.stub(mongoose.Model, 'find').callsFake(() =&gt; {
  return [ { foo: ""bar"" /* fake documents */ } ]
})

describe('Thing API', () =&gt; {
  it('returns some things', (done) =&gt; {
    request(app)
      .get('/api/things')
      .expect(function(res) {
        expect(res.body).to.be.an.an('array')
        // Rest of my tests / validation checks here
      })
      .expect(200, done);
  });
})
</code></pre>

<p>This test fails with <code>this.model.find(...).limit is not a function</code> as my service (which is the layer in my code that talks to the DB via Mongoose) looks a little like this (where <code>this.model</code> is an instance of a Mongoose model) </p>

<pre class=""lang-js prettyprint-override""><code>let items = await this.model.find(query)
  .limit(limit)
  .skip(skip);
</code></pre>
",https://stackoverflow.com/questions/58787092/unit-testing-api-with-supertest-stubbing-mongoose-model-with-chained-functions,"['mongodb', 'unit-testing', 'mongoose', 'sinon', 'supertest']",1524,True,0,1
Click button event in Unit testing is not working in Angular,"<p>I'm writing this unit test to verify when clicking back button, then it will show the login page. </p>

<p>The HTML script below is the back button.</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;button [routerLink]=""[url_sep + login]"" class=""btn bigBtn btn-gray"" keep-width type=""button""&gt;
          Back
&lt;/button&gt;</code></pre>
</div>
</div>
</p>

<p>The script below is the unit test which I want to execute.</p>

<pre><code>let de: DebugElement;
let el: HTMLElement;

it('should open login page when click back button', () =&gt; {
    de = fixture.debugElement.query(By.css('.btn-gray'));
    el = de.nativeElement;
    el.click();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('p').textContent).toContain('Welcome');
  });
</code></pre>

<p>After I ran this unit test, the button wasn't clicked, because it verified 'Welcome' word in the same page not in the log in page. </p>
",https://stackoverflow.com/questions/57252651/click-button-event-in-unit-testing-is-not-working-in-angular,"['angular', 'unit-testing', 'jasmine', 'automated-tests']",6508,True,0,2
How to trigger an event in angular app for unit testing?,"<p>I am running unit test in angular, I want to trigger a click event, this is a drop down upon clicking it drops down a list of Customer numbers. I want to trigger this event in my unit test, if this event is successfully triggered, I can update the customer info corresponding to index of clicked button. I have attached necessary code for reference. Please let me know how to trigger click event?</p>

<pre><code>//template.html 
&lt;mat-menu #menuFilter=""matMenu""&gt;
    &lt;button *ngFor=""let customer of customers; let i = index"" (click)=""onCustomerChange(i)"" mat-menu-item class=""selectCustomerData""&gt;{{customer.licenseownerid}}&lt;/button&gt;
 &lt;/mat-menu&gt;
</code></pre>

<pre><code>//angular generated code
&lt;div class=""mat-menu-panel ng-trigger ng-trigger-transformMenu ng-tns-c10-1 mat-menu-after
 mat-menu-below ng-star-inserted mat-elevation-z2"" role=""menu"" tabindex=""-1"" ng-reflect-klass=""mat-menu-panel"" 
 ng-reflect-ng-class=""[object Object]"" style=""transform-origin: left top;""&gt;
    &lt;div class=""mat-menu-content""&gt;
          &lt;button class=""selectCustomerData mat-menu-item ng-star-inserted"" mat-menu-item="""" role=""menuitem"" tabindex=""0"" aria-disabled=""false""&gt;0LPT_id0306
            &lt;div class=""mat-menu-ripple mat-ripple"" matripple="""" ng-reflect-disabled=""false"" ng-reflect-trigger=""[object HTMLButtonElement]""&gt;
            &lt;/div&gt;
          &lt;/button&gt;
          &lt;button class=""selectCustomerData mat-menu-item ng-star-inserted"" mat-menu-item="""" role=""menuitem"" tabindex=""0"" aria-disabled=""false""&gt;0LPT_id03061
           &lt;div class=""mat-menu-ripple mat-ripple"" matripple="""" ng-reflect-disabled=""false"" ng-reflect-trigger=""[object HTMLButtonElement]""&gt;
           &lt;/div&gt;
          &lt;/button&gt;
       &lt;/div&gt;
...and so on
&lt;/div&gt;
</code></pre>

<pre><code>//component.ts
 onCustomerChange(i) {
    this.customerNumber = this.customers[i].licenseownerid;
    this.customerName = this.customers[i].licenseownername;
}
</code></pre>
",https://stackoverflow.com/questions/55588819/how-to-trigger-an-event-in-angular-app-for-unit-testing,"['angular', 'unit-testing']",1406,False,0,1
Is it possible to use dagger at android project unit testing?,"<p>I want to use Dagger + Robolectric in src/test/java package. Is it possible? How?
Somebody wrote their Robolectric tests at src/androidTest/java package then used Dagger, But Robolectric is a framework that runs your tests inside the JVM on your workstation in seconds.
If I write my test in src/androidTest/java package it won't run inside the JVM.</p>

<p>Anyway, Is it right to use Dagger at src/test/java package? Is it possible?</p>
",https://stackoverflow.com/questions/55848221/is-it-possible-to-use-dagger-at-android-project-unit-testing,"['android', 'unit-testing', 'dagger-2', 'robolectric']",52,False,0,1
How to subscribe to error case in angular service unit testing,"<p>I am trying to subscribe to the response and as well the error case but when I see the coverage its not going to err case.</p>

<p>I have the following fake service,</p>

<p>My service,</p>

<pre><code>fakeService: {

     appVersion() : {

        return of({'version':'1.2.3.4'})
     } 
}
</code></pre>

<p>test case1:  </p>

<pre><code> it('Should load version',() =&gt; {

    fakeService.appVersion().subscribe((data) {

      expect(data.version).toBe(1.2.3.4)

  });
</code></pre>

<p>test case 2: [for error case]</p>

<pre><code>  it('Should return error',() =&gt; {
   fakeService: {

     appVersion() : {

        return throwError('Error');
     } 
   }
    fakeService.appVersion().subscribe({
     error : err =&gt; expect(err).toBe('Error');

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

<p>In component</p>

<pre><code>   myService.appVersion.subscribe((data) {
      if (data) {
       //// Covered
      } else (err) {
       //// Not covered
      }

   });
</code></pre>

<p>I am trying to subscribe to the response and as well the error case but when I see the coverage its not going to err case.</p>
",https://stackoverflow.com/questions/57932508/how-to-subscribe-to-error-case-in-angular-service-unit-testing,"['unit-testing', 'jasmine', 'angular6', 'angular2-services', 'angular-test']",288,False,0,1
Unit Testing Troubleshoot in Karma-Jasmine for .sort() function in Angular,"<p>I have a block of code written in Angular:</p>

<pre><code>this.selectedData.sort((a, b) =&gt; {
        if (query === 'poll' &amp;&amp; (a[query] === null || b[query] === null)) {
          return a[query] === null ? 1 : -1;
        } else if (query === 'submit') {
          return moment(a[query]).isBefore(moment(b[query])) ? 1 : -1;
        } else {
          return b[query].localeCompare(a[query]);
        }
});
</code></pre>

<p>I tried writing a callFake for the sort function like below:</p>

<pre><code>spyOn(selectedData, 'sort').and.callFake((a, b) =&gt; {
     expect(query).toBe('poll');
});
</code></pre>

<p>But, the code-coverage shows, it is not going inside the sort function block. Is there any other way of writing the test cases. I also tried using callThrough() and it is showing me the same result.</p>
",https://stackoverflow.com/questions/58534240/unit-testing-troubleshoot-in-karma-jasmine-for-sort-function-in-angular,"['angular', 'unit-testing', 'jasmine', 'karma-runner']",3174,True,0,1
Spring batch unit testing job with external input and db output,"<p>If I understand it correctly normal way of spring batch testing is to basically run my application and let <code>JobLauncherTestUtils</code> run my normal jobs. However my application reads input from external service and writes it to my database. I don't want my tests to write to my production database and I'd like to specify test input to be read rather from the files I'd provide than from external service. </p>

<p>Can anyone direct me to some example how I could do it? I'd like to feed a job with a file then when job has finished check in the database that what I expect is there. I guess I could specify h2 db in application-test.properties but I have no clue about the input.</p>

<p>Docs from <a href=""https://docs.spring.io/spring-batch/4.1.x/reference/html/testing.html#testing"" rel=""nofollow noreferrer"">https://docs.spring.io/spring-batch/4.1.x/reference/html/testing.html#testing</a> don't really cover it for me.</p>
",https://stackoverflow.com/questions/56743579/spring-batch-unit-testing-job-with-external-input-and-db-output,"['spring', 'spring-batch', 'spring-boot-test']",142,True,0,1
Why is IObjectMapper not initialised when unit testing a controller method?,"<p>I am using ASP.NET Boilerplate template for ASP.NET Core. I have some application services which I have successfully unit tested.</p>

<p>I now want to test a controller method which uses these application services.
The controller method includes mapping operation like this:</p>

<pre><code>var client = ObjectMapper.Map&lt;ClientModel&gt;(clientResponse.ClientSummary);
</code></pre>

<p>On executing this method, the test fails with an exception:</p>

<blockquote>
  <p>Message: Abp.AbpException : Abp.ObjectMapping.IObjectMapper should be implemented in order to map objects.</p>
</blockquote>

<p>Interestingly, the stack trace begins with <code>NullObjectMapper.Map</code>.</p>

<p>I am using the same initialisation for <code>AbpAutoMapper</code> in the unit test module as is used in the <code>Web.Mvc</code> module:</p>

<pre><code>Configuration.Modules.AbpAutoMapper().Configurators.Add(cfg =&gt;
{
    cfg.AddProfiles(typeof(PortalTestModule).GetAssembly());
});
</code></pre>

<p>However, when executing in the context of the MVC application, the mapping operations don't cause the exception.</p>

<p>What is it that I am failing to initialise in the <code>Test</code> project in relation to AutoMapper?</p>

<hr>

<p>I have created a repro project. See <a href=""https://github.com/muiscatron/module-zero-core-template"" rel=""nofollow noreferrer"">link</a>. There is a test called <code>GetFoos_Test</code> that tests the controller method <code>Index()</code> on <code>FoosController</code>.</p>

<pre class=""lang-cs prettyprint-override""><code>public async Task GetFoos_Test()
{
    var mockFooService = new Mock&lt;IFooAppService&gt;();
    // ...

    var fooController = new FooController(mockFooService.Object);

    var result = await fooController.Index();

    result.ShouldNotBeNull();
}
</code></pre>

<p>As per @aaron's answer, property injecting IObjectMapper on the controller does solve the original error. However, it doesn't use the mappings that are part of what I am trying to test. I have created mappings in the Initialize method of the MVC module like this:</p>

<pre><code>public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(MyMvcModule).GetAssembly());

            Configuration.Modules.AbpAutoMapper().Configurators.Add(
               // Scan the assembly for classes which inherit from AutoMapper.Profile
               cfg =&gt;
               {
                   cfg.AddProfiles(typeof(MyMvcModule).GetAssembly());

                   cfg.CreateMap&lt;MyDto, MyModel&gt;()
                       .ForMember(dest =&gt; dest.ReportTypeName, src =&gt; src.MapFrom(x =&gt; x.ReportType.Name));
... 

</code></pre>
",https://stackoverflow.com/questions/55500235/why-is-iobjectmapper-not-initialised-when-unit-testing-a-controller-method,"['c#', 'unit-testing', 'dependency-injection', 'aspnetboilerplate', 'property-injection']",2189,True,0,1
Unit Testing Spring Services with actual Repository with in memory database,"<p>I am trying to test my <code>@Service</code> with the actual object of Spring Data Repository, where I am trying to use in memory database.I am using below annotation in my unit test.</p>

<pre><code>@ActiveProfiles(""test"")
@RunWith(SpringRunner.class)
@EnableJpaRepositories
@SpringBootTest(classes = {MyService.class})
public class T24PortfolioRequestHandlerTest {

    @Autowired
    private MyService myService;

    @Autowired
    private MyRepository myRepository;

    @Test
    public void handleRequest() {        
        String output = myService.handleRequest(testData, ""123"", ""TEST"");
        Assert.assertNotNull(output);
        Assert.assertEquals(""TESTING"", output);

    }
}
</code></pre>

<p>I am getting below exception while running the test. </p>

<pre><code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.....respository.MyRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code></pre>

<p>If I specify <code>MyRepository.class</code> in <code>SpringBootConfiguratio(classes={MyService.class, MyRepository.class})</code> I am getting below error. </p>

<pre><code>org.springframework.beans.BeanInstantiationException: Failed to instantiate [...respository.MyRepository]: Specified class is an interface
</code></pre>

<p>Is there any another way to tell spring boot about my repositories?</p>
",https://stackoverflow.com/questions/58179536/unit-testing-spring-services-with-actual-repository-with-in-memory-database,"['junit4', 'spring-boot-test']",21,False,0,0
Angular 7/Jasmine: Issues while unit testing Observable in a service,"<p>I'm having some issues testing a Service that has an Observable being subscribed in the method I want to test.  The Observable itself wraps a Promise using from(), coming from a legacy AngularJS service called 'legacyData', as such:</p>

<p>Service to test:</p>

<pre class=""lang-js prettyprint-override""><code>refreshData(storageService: StorageService): void {
   let dataObs: Observable&lt;IResponse&gt; = from(this.legacyData.get({}));
   console.log(""This is called while testing!!!);  &lt;&lt;&lt;&lt;

   dataObs.subscribe((response: IResponse) =&gt; {
        console.log(""This is NOT called while testing!!!);  &lt;&lt;&lt;&lt;
        let responseData: IResponseData[] = response.data as IResponseData[];
        storageService.set(responseData);
    },
    (error: string) =&gt; loggingService.addError('Failed to get Data', error));
}
</code></pre>

<p>The test, using MockLegacyDataService to mock the legacy service using promises:</p>

<pre class=""lang-js prettyprint-override""><code>describe('dataService', () =&gt; {
    let service: DataService;
    let storageService: StorageService;
    class MockLegacyDataService {
        get(params: object) {
            return Promise.resolve('some response');
        }
    }
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            providers: [
                {provide: 'Data', useClass: MockLegacyDataService},
                DataService,
                StorageService
            ]
        });
        service = TestBed.get(DataService);
        storageService = TestBed.get(StorageService);
    });
    it('should refresh data', () =&gt; {
        spyOn(storageService, 'set');
        service.refreshData(storageService);

        expect(storageService.get()).toEqual('some response');  &lt;&lt;&lt; this is not working!!!
        expect(storageService.set).toHaveBeenCalledTimes(1);  &lt;&lt;&lt; this is not working!!!
    });
 });
</code></pre>

<p>The Observable callback code is never called as expected.</p>

<p>I tried also using async(), fakeAsync()/tick/flush and jasmine done() to wrap the test, but none of this worked.</p>

<p>Anybody has any idea how I could test this?</p>
",https://stackoverflow.com/questions/54795928/angular-7-jasmine-issues-while-unit-testing-observable-in-a-service,"['angular', 'unit-testing', 'promise', 'jasmine', 'observable']",753,False,0,0
How to stub a Facebook&#39;s SDK access token for unit testing,"<p>I'm trying to perform some unit testing in my application and I've ran into a problem. A simple graph request demands an AccessToken object which can only be claimed by - </p>

<pre><code>AccessToken.getCurrentAccessToken() 
</code></pre>

<p>or getting it in an authentication result.
Both of the options requires a real authentication process with ui which makes it impossible to unit test. is there a way to create my own AccessToken object? I've tried to use reflection with no luck. any other suggestions?</p>
",https://stackoverflow.com/questions/54769510/how-to-stub-a-facebooks-sdk-access-token-for-unit-testing,"['android', 'facebook-sdk-4.x']",691,True,-1,2
Unit Testing: No database provider has been configured for this DbContext,"<p>So, I am trying to Unit Test my project, and the UnitTests.cs file has 8 tests, out of which 6 pass but 2 fail, the two that fail gives me the error of ""No database provider has been configured for this DbContext."" the <strong>UnitTests.cs</strong> file:</p>

<pre><code>private readonly CatalogItemContext _context;

private Microsoft.EntityFrameworkCore.DbContextOptionsBuilder&lt;CatalogItemContext&gt; obj;

public UnitTests()
{
    obj = new DbContextOptionsBuilder&lt;CatalogItemContext&gt;();
    _context = new CatalogItemContext(obj.Options);
}

[Fact]
public void Get_WhenCalled_ReturnsAllItems()
{
    CatalogController cc = new CatalogController(_context);
    var test = cc.GetItems().Result;
    var okResult = test.Result as OkObjectResult;

    var items = Assert.IsType&lt;List&lt;CatalogItem&gt;&gt;(okResult.Value);
    Assert.Equal(3, items.Count);
}

[Fact]
public void Get_WhenCalled_ReturnsAllProductsTypes()
{
    CatalogController cc = new CatalogController(_context);
    var test = cc.GetTypes().Result;
    var okResult = test.Result as OkObjectResult;
    var Expected = typeof(OkObjectResult);
    var items = Assert.IsType&lt;List&lt;CatalogType&gt;&gt;(okResult.Value);
    Assert.Equal(3, items.Count);
}
</code></pre>

<p>My <strong>Startup.cs</strong> contains the following:</p>

<pre><code>string connectionString = Configuration.GetConnectionString(""DefaultConnection"");

services.AddDbContext&lt;CatalogItemContext&gt;(opt =&gt; opt.UseSqlServer(connectionString));

services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
</code></pre>

<p>And <strong>Context File</strong> is as follows:</p>

<pre><code>public class CatalogItemContext : DbContext
{
    public CatalogItemContext(DbContextOptions&lt;CatalogItemContext&gt; options) : base(options)
    {
    }
    public DbSet&lt;CatalogItem&gt; CatalogItem { get; set; }
    public DbSet&lt;CatalogType&gt; CatalogType { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.HasDefaultSchema(""Catalog"");
        builder.ApplyConfiguration(new CatalogTypeEntityTypeConfiguration());
        builder.ApplyConfiguration(new CatalogItemEntityTypeConfiguration());
    }     
}


public class CatalogContextDesignFactory : IDesignTimeDbContextFactory&lt;CatalogItemContext&gt;
{
    public CatalogItemContext CreateDbContext(string[] args)
    {
        var optionsBuilder =  new DbContextOptionsBuilder&lt;CatalogItemContext&gt;()
            .UseSqlServer(""--REDACTED CONNECTION STRING--"",
            x =&gt; x.MigrationsHistoryTable(""__EFMigrationHistory"", ""catalog""));

        return new CatalogItemContext(optionsBuilder.Options);
    }
</code></pre>

<p>Can someone please shed some light on what I can do to make it work?</p>

<p>EDIT: Error which are appearing:
PS: I am using VSCode.</p>

<pre><code>    [xUnit.net 00:00:01.26]     UnitTests.Get_WhenCalled_ReturnsAllProductsTypes [FAIL]

[xUnit.net 00:00:01.27]     UnitTests.Get_WhenCalled_ReturnsAllItems [FAIL]

  X UnitTests.Get_WhenCalled_ReturnsAllProductsTypes [2ms]
  Error Message:
   System.AggregateException : One or more errors occurred. (No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext 
is used, then also ensure that your DbContext type accepts a DbContextOptions&lt;TContext&gt; object in its constructor and passes it to the base constructor for DbContext.)
---- System.InvalidOperationException : No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions&lt;TContext&gt; object in its constructor and passes it to the base constructor for DbContext.
  Stack Trace:
     at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at UnitTests.Get_WhenCalled_ReturnsAllProductsTypes() in --Location redacted--\Test\UnitTests.cs:line 33
----- Inner Stack Trace -----
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_Model()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.Microsoft.EntityFrameworkCore.Query.Internal.IAsyncEnumerableAccessor&lt;TEntity&gt;.get_AsyncEnumerable()
   at Microsoft.EntityFrameworkCore.Extensions.Internal.QueryableExtensions.AsAsyncEnumerable[TSource](IQueryable`1 source)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at --Redacted--.Controllers.CatalogController.GetTypes() in --Location Redacted--\src\--Redacted--\Controllers\CatalogController.cs:line 43

  X UnitTests.Get_WhenCalled_ReturnsAllItems [2ms]
  Error Message:
   System.AggregateException : One or more errors occurred. (No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext 
is used, then also ensure that your DbContext type accepts a DbContextOptions&lt;TContext&gt; object in its constructor and passes it to the base constructor for DbContext.)
---- System.InvalidOperationException : No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions&lt;TContext&gt; object in its constructor and passes it to the base constructor for DbContext.
  Stack Trace:
     at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at UnitTests.Get_WhenCalled_ReturnsAllItems() in --Location Redacted--\src\--Redacted--\Test\UnitTests.cs:line 22
----- Inner Stack Trace -----
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_Model()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.Microsoft.EntityFrameworkCore.Query.Internal.IAsyncEnumerableAccessor&lt;TEntity&gt;.get_AsyncEnumerable()
   at Microsoft.EntityFrameworkCore.Extensions.Internal.QueryableExtensions.AsAsyncEnumerable[TSource](IQueryable`1 source)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at --Redacted--.Controllers.CatalogController.GetItems() in --Location Redacted--\src\Redacted\Controllers\CatalogController.cs:line 32


Test Run Failed.
Total tests: 8
     Passed: 6
     Failed: 2
 Total time: 2.1150 Seconds
</code></pre>
",https://stackoverflow.com/questions/58993989/unit-testing-no-database-provider-has-been-configured-for-this-dbcontext,"['c#', 'asp.net-core', 'integration-testing', 'asp.net-core-webapi']",2196,True,0,1
How would I go about unit testing this function in Kotlin?,"<p>I'm pretty new to unit testing. I've been given the task of testing this code. I understand that I have to use assertEquals to check if for example if 
RegionData.Key.DEV returns VZCRegion.Development. 
Any help would be appreciated.     </p>

<pre><code>fun fromCakeSliceRegion(cakeSliceIndex: RegionData.Key): VZCRegion {

    return when (cakeSliceIndex) {
        RegionData.Key.DEV -&gt; VZCRegion.Development
        RegionData.Key.EU_TEST -&gt; VZCRegion.EuropeTest
        RegionData.Key.US_TEST -&gt; VZCRegion.UnitedStatesTest
        RegionData.Key.US_STAGING -&gt; VZCRegion.UnitedStatesStage
        RegionData.Key.EU_STAGING -&gt; VZCRegion.EuropeStage
        RegionData.Key.LOCAL, RegionData.Key.EU_LIVE -&gt; VZCRegion.Europe
        RegionData.Key.AP_LIVE, RegionData.Key.US_LIVE -&gt; VZCRegion.UnitedStates
        RegionData.Key.PERFORMANCE, RegionData.Key.PERFORMANCE -&gt; VZCRegion.Performance
    }
</code></pre>
",https://stackoverflow.com/questions/58727442/how-would-i-go-about-unit-testing-this-function-in-kotlin,"['unit-testing', 'kotlin', 'junit4']",140,True,0,2
How to mock plain object&#39;s dependency when unit testing with jest?,"<p>I can't find the way to mock object import when testing my ReactJs helper. All examples out there showing how to mock imported functions and nobody speak about mocking imported objects. </p>

<p>This base helper object I want to mock: </p>

<p><code>filters-state.helper.ts</code>:</p>

<pre class=""lang-js prettyprint-override""><code>export const FiltersStateHelper = {
  toggleFilters: &lt;T extends FiltersState&gt;(state: T): T =&gt; ({
    ...state,
    isOpen: !state.isOpen
  })
};
</code></pre>

<p>I am using it in the state helper I'm testing:</p>

<p><code>search-view-state.helper.ts</code>:</p>

<pre class=""lang-js prettyprint-override""><code>import { FiltersStateHelper } from 'shared/filters/helpers/filters-state.helper';

export const SearchViewStateHelper = {
  toggleFilters: &lt;T extends SearchViewState&gt;(state: T): T =&gt; ({
    ...state,
    filters: FiltersStateHelper.toggleFilters(state.filters)
  })
  //... more methods
};
</code></pre>

<p>And in the test mocking dependency is failing, probably because my helper's dependencies already resolved before I said jest what to mock:</p>

<p><code>search-view-state.helper.spec.ts</code>:</p>

<pre class=""lang-js prettyprint-override""><code>import { SearchViewStateHelper as helper } from 'shared/search-view/helpers/search-view-state.helper';

describe('toggleFilters method', () =&gt; {
  const spy = jest.fn();
  jest.doMock('shared/filters/helpers/filters-state.helper', () =&gt; {
    return {
      toggleFilters: spy
    };
  });

  const state = {};

  it('should toggle filters', () =&gt; {
    helper.toggleFilters(state);
    expect(spy).toHaveBeenCalled();
  });
});
</code></pre>
",https://stackoverflow.com/questions/58746881/how-to-mock-plain-objects-dependency-when-unit-testing-with-jest,"['reactjs', 'unit-testing', 'jestjs']",515,True,0,1
How to mock a method inside another module during unit testing,"<p>In one of my test case the flow requires that a customer provision process wherein the call goes to the api.py file where in the response is saved from the function create_t_customer like following:</p>

<p>In api.py file it is using the method create_t_customer imported from file customer.py</p>

<pre><code>response = create_t_customer(**data)
</code></pre>

<p>In customer.py file the code for function is</p>

<pre><code>def create_t_customer(**kwargs):
    t_customer_response = Customer().create(**kwargs)
    return t_customer_response

</code></pre>

<p>I want to mock the function create_t_customer inside the unittest.
Current I have tried the following but it doesn't seem to be working</p>

<pre><code>class CustomerTest(APITestCase):
    @mock.patch(""apps.dine.customer.create_t_customer"")
    def setUp(self,mock_customer_id):
        mock_customer_id.return_value = {""customer"":1}
</code></pre>

<p>But this is not able to mock the function.</p>
",https://stackoverflow.com/questions/58928580/how-to-mock-a-method-inside-another-module-during-unit-testing,"['django', 'python-3.x', 'mocking', 'python-mock', 'django-unittest']",1120,True,0,1
unit testing an async method tests assertions before method has completed,"<pre><code>[TestMethod]
public void TestMethod1()
{
    TestClass testClass = new TestClass();
    testClass.Method();
    Assert.AreEqual(testClass.x, true);
}
</code></pre>

<p>And test class:</p>

<pre><code>public async void Method()
{
    if(cond)
        await InnerMethod();
}

private async Task InnerMethod()
{
    var data = await client.FetchData();
    x = data.res;
}
</code></pre>

<p>I am testing an sync method which is of this format. But when i run the test, it runs through the line
 var data = await client.FetchData();</p>

<p>and then instead of continuing the method execution, goes into the assert statement in the test method first (fails because obviously it didnt finish the method). and THEN carries on with the rest of the method.</p>

<p>I am really confused why its doing this but am guessing its soemthing to do with threading. any clues as to why this behavior would be really helpful! thanks</p>
",https://stackoverflow.com/questions/56341210/unit-testing-an-async-method-tests-assertions-before-method-has-completed,"['c#', '.net', 'unit-testing', 'asynchronous', 'vs-unit-testing-framework']",282,True,0,1
Need help calling a Repository from a Controller in Unit Testing,"<p>I am needing to set up a Unit Test for our project. In our Controllers we are using a Unit of Work which holds all the repositories and calling the repository in our <code>IHttpActionResult</code> to get the data. </p>

<p>So far I have set up a Mock of the Interfaces and this is calling the correct <code>IHttpActionResult</code> in the Controller but there is no data coming back. </p>

<pre><code>[TestMethod]
public void TestMethod1()
{
    var unitOfWork = new Mock&lt;IUnitOfWork&gt;();
    var repo = new Mock&lt;IAuditReleaseRepository&gt;();
    unitOfWork.Setup(e =&gt; e.AuditReleaseRepository).Returns(repo.Object);
    var auditReleaseController = new AuditReleaseController(unitOfWork.Object);
    var result = auditReleaseController.Get() as ViewResult;
    var model = result.ViewData.Model as IQueryable&lt;AuditReleas&gt;;
    Assert.AreEqual(12, model.Count());
}
</code></pre>

<pre><code>public class AuditReleaseController : BaseController
{
    private IAuditReleaseRepository _auditReleaseRepository;
    private IUnitOfWork _unitOfWork;
    public AuditReleaseController(IUnitOfWork unitOfWork)
    {
        this._unitOfWork = unitOfWork;
        this._auditReleaseRepository = unitOfWork.AuditReleaseRepository;
    }

    [HttpGet, Route(""audit-releases"")]
    public IHttpActionResult Get()
    {
        var query = this._auditReleaseRepository.GetAll();
        return Ok(query);
    }
}
</code></pre>

<pre><code>public class AuditReleaseRepository : RepositoryBase&lt;AuditReleas&gt;, IAuditReleaseRepository
{
    private readonly RetailAssignmentEntities _entities;

    public AuditReleaseRepository(RetailAssignmentEntities entities) : base(entities)
    {
        this._entities = entities;
    }

    IEnumerable&lt;AuditReleaseDto&gt; IDtoRepository&lt;AuditReleaseDto&gt;.GetAll()
    {
        return base.GetAll().Where(x=&gt;x.IsReleaseEnabled).Select(AuditReleaseMapping.All).OrderByDescending(x =&gt; x.Id);
    }
}
</code></pre>

<p>This is the Mapping that is taking place to get the data in the GetAll method:</p>

<pre><code>public class AuditReleaseMapping
    {
        public static Expression&lt;Func&lt;AuditReleas, AuditReleaseDto&gt;&gt; All = (auditRelease) =&gt; new AuditReleaseDto()
        {
           EndDate = auditRelease.AuditReleaseEndDate,
           Id = auditRelease.AuditReleaseId,
           Name = auditRelease.AuditReleaseName,
           StartDate = auditRelease.AuditReleaseStartDate,
           AuditPeriodId = auditRelease.AuditPeriod.AuditPeriodId,
           AuditYearId = auditRelease.AuditPeriod.AuditYear.AuditYearId,
           AuditEndDate = auditRelease.AuditPeriod.AuditEndDate,
           AuditStartDate = auditRelease.AuditPeriod.AuditStartDate
        };
    }
</code></pre>

<p>What would be ideal is to call the Controller, which would call the repository, which would then call the Mapping but so far it's not even calling the Repository to get the data. I need help getting that functionality set up.</p>
",https://stackoverflow.com/questions/57787227/need-help-calling-a-repository-from-a-controller-in-unit-testing,"['c#', 'asp.net-mvc', 'unit-testing', 'moq']",398,False,0,1
"HttpClient interceptor retry unit testing (Expected no open requests, found 1)","<p>I have a simple HttpClient interceptor that just retries failed requests a set amount of times. Now, I'm trying to write unit tests for it but somehow I end up with an unfinished request. I've tried wrapping the test in <code>fakeAsync</code> or using <code>done</code> but it does not seem to help. Right now I am out of ideas.</p>

<p>The error I get is:
<code>Error: Expected no open requests, found 1: GET mock/url</code></p>

<p>What am I missing?</p>

<p><code>server-error.interceptor.ts</code></p>

<pre class=""lang-js prettyprint-override""><code>import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { retry } from 'rxjs/operators';
import { ConfigService } from '@app/shared/services/config.service';

/**
 * Http error interceptor class
 */

@Injectable()
export class ServerErrorInterceptor implements HttpInterceptor {
  constructor(private configService: ConfigService) {}

  /**
   * Intercepts failed requests and retries set amount of times before throwing an error
   *
   * @param request  HTTP request
   * @param next  HTTP handler
   *
   * @returns Observable of Http event
   */
  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    return next.handle(request).pipe(retry(this.configService.config.httpRetryCount));
  }
}

</code></pre>

<p><code>server-error.interceptor.spec.ts</code></p>

<pre class=""lang-js prettyprint-override""><code>import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController, TestRequest } from '@angular/common/http/testing';
import { HTTP_INTERCEPTORS, HttpClient, HttpErrorResponse } from '@angular/common/http';

import { ServerErrorInterceptor } from '@core/interceptors/server-error.interceptor';
import { ConfigService } from '@shared/services/config.service';

const mockUrl = 'mock/url';
const mockHttpRetryCount = 5;
const mockErrorText = 'Mock error!';

const mockConfigService: object = {
  config: jest.fn().mockReturnValue({
    httpRetryCount: mockHttpRetryCount
  })
};

describe('ServerErrorInterceptor', () =&gt; {
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;
  let interceptor: ServerErrorInterceptor;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        ServerErrorInterceptor,
        { provide: ConfigService, useValue: mockConfigService },
        { provide: HTTP_INTERCEPTORS, useClass: ServerErrorInterceptor, multi: true }
      ]
    });

    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);
    interceptor = TestBed.get(ServerErrorInterceptor);
  });

  afterEach(() =&gt; {
    httpTestingController.verify();
  });

  it('should be created', () =&gt; {
    expect(interceptor).toBeTruthy();
  });

  it('should retry an errored request set amount of times', (): void =&gt; {
    httpClient.get(mockUrl).subscribe(
      null,
      (response: HttpErrorResponse): void =&gt; {
        expect(response.status).toEqual(500);
        expect(response.message).toEqual(`Http failure response for ${mockUrl}: 500 Server Error`);
      }
    );

    for (let i = 0; i &lt; mockHttpRetryCount; i += 1) {
      const request: TestRequest = httpTestingController.expectOne(mockUrl);
      request.flush(mockErrorText, { status: 500, statusText: 'Server Error' });
    }
  });
});

</code></pre>
",https://stackoverflow.com/questions/55473295/httpclient-interceptor-retry-unit-testing-expected-no-open-requests-found-1,"['angular', 'unit-testing', 'jestjs', 'angular-httpclient-interceptors']",2263,True,0,1
NullPointer during unit testing method responsible for retrieving data from file,"<p>I am trying to unit test method that is responsible for retreiving data from text file.</p>

<p>Here is how the class with that method looks like:</p>

<pre><code>package contentfile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ContentFileRetrieverService implements ContentFileRetriever {

    @Override
    public String[] getContentFile(String pathName) {

        Stream&lt;String&gt; contentFileStream;
        try {
            contentFileStream = Files.lines(Paths.get(pathName));
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }

        return contentFileStream.toArray(String[]::new);
    }
}
</code></pre>

<p>Here is how the test looks like:</p>

<pre><code>package contentfile;

import org.junit.Rule;
import org.junit.jupiter.api.Test;

import static org.junit.Assert.*;

class ContentFileRetrieverServiceTest {

    private ContentFileRetrieverService contentFileRetrieverService;

//    @Rule
//    TemporaryFiles temporaryFiles = new TemporaryFiles();

    @Test
    void getContentFile() {
        String pathFile = ""tekst.txt"";
        String[] testedContent = contentFileRetrieverService.getContentFile(pathFile);
        String[] expected = {""la"", ""la""};
        assertArrayEquals(expected, testedContent);
    }
}
</code></pre>

<p>Unfortunately, I got <code>NullPointer</code> while calling getContentFile method.
Here is stacktrace:</p>

<pre><code>java.lang.NullPointerException
    at contentfile.ContentFileRetrieverServiceTest.getContentFile(ContentFileRetrieverServiceTest.java:18)
    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)
</code></pre>

<p>Content file</p>

<pre><code>Line1 a
Line2 b c
Line 3
</code></pre>
",https://stackoverflow.com/questions/55735680/nullpointer-during-unit-testing-method-responsible-for-retrieving-data-from-file,"['java', 'file', 'unit-testing']",248,True,0,1
Need advice on unit testing method which is using &quot;dozer.map&quot; method,"<p>I have an empModel and empDto object. In an spring boot app, I am making a service call to get employee model by Id. In the method, empModel is obtained from database by making a service call. Dozermapper populates the DTO and returns the dto. DozerMapper is injected to the controller . </p>

<p>Facing difficulty in unit testing the method. 
I am able to mock the service using when/thenReturn. However, I am unable to mock the dozerMapper as its a method with void return. What would be the right approach to unit test the method? </p>

<pre><code>  @Inject
  public Controller(DozerBeanMapper dozerBeanMapper, EmployeeService service){
    this.dozerBeanMapper = dozerBeanMapper;
    this.service = service;
  }

  @GetMapping(""/{id}"")
  public EmpDto getEmployeeById(@PathVariable long id){
    EmpModel empModel = service.getEmployeeById(id);
    EmpDto empDto = new EmpDto();
    dozerBeanMapper.map(empModel,empDto);
    return empDto;
  }
</code></pre>
",https://stackoverflow.com/questions/54223042/need-advice-on-unit-testing-method-which-is-using-dozer-map-method,"['unit-testing', 'spring-boot', 'dozer']",616,True,0,1
How to unit test $uibModal in Jasmine? (unit testing injected library),"<p>So I am using $uibModal from bootstrap and I have the following code in my AngularJS controller:</p>

<pre><code>vm.openPopup = function() {
  $uibModal.open({
    templateUrl: 'popup.html',
    controller: function() {
       var modal = this;

       modal.hi = function() {
         // some code here
       }
    }
  });
};
</code></pre>

<p>How would I go about calling the modal.hi function in Jasmine and unit testing it to make sure it works correctly?</p>
",https://stackoverflow.com/questions/57319381/how-to-unit-test-uibmodal-in-jasmine-unit-testing-injected-library,"['angularjs', 'unit-testing', 'jasmine', 'karma-jasmine', 'angular-ui-bootstrap']",542,True,0,1
Code coverage concern on promise/asynchronous unit testing using nockjs and jest,"<p>I have written a simple unit test for API call using NockJS and Jest for a react application as bellow:</p>

<p>AjaxService.js</p>

<pre><code>export const AjaxService = {
    post: (url, data, headers) =&gt; {
        return axios({
            method: ""POST"",
            url: url,
            headers: headers || { ""content-type"": ""application/json"" },
            data: data
        });
    },
};
</code></pre>

<p>API Promise:</p>

<pre><code>export const getDashboard = (request) =&gt; {
  return AjaxService.post(API_DASHBOARD_URL + ""/getDashboard"", request
  ).then(
    response =&gt; {
      return response.data;
    },
    (error) =&gt; {
      return error.response.data;
    }
  )
};
</code></pre>

<p>Unit test using NockJS:</p>

<pre><code>nock(baseUrl)
    .post(subUrl, request)
    .reply(200, response);

getDashboard(request)
    .then(resp =&gt; {
        let compareVal = getNestedObject(resp, keyToCompare);
        let actualVal = getNestedObject(response, keyToCompare);
        expect(compareVal).to.equal(actualVal);
    })
    .then(() =&gt; {});
</code></pre>

<p>But when the code-coverage report is generated using Jest <code>--coverage</code> as below:</p>

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

<p>We can see that in promise, <strong>success callback</strong> and <strong>error callback</strong> is <strong>not</strong> called during unit test. How to cover this part of code as it affects code-coverage percentage when an application is having numerous API calls? Or am I not testing is properly? Please help as I am new to unit testing. Thanks in advance. </p>
",https://stackoverflow.com/questions/57656523/code-coverage-concern-on-promise-asynchronous-unit-testing-using-nockjs-and-jest,"['javascript', 'reactjs', 'jestjs', 'code-coverage', 'nock']",2427,True,4,1
How can I mock Javascript file imported in Svelte for unit testing?,"<p>I have the following svelte file</p>

<p><strong>Dashboard.svelte</strong></p>

<pre><code>&lt;script&gt;
  import Proxy from ""../Proxy.js"";

  import { onMount } from ""svelte"";

  export let data = [];

  onMount(async () =&gt; {
    spinner = true;
    let data = await Proxy.getData();
  });
&lt;/script&gt;
......
......
......
</code></pre>

<p><strong>Dashboard.test.js</strong></p>

<pre><code>import Dashboard from ""../src/Dashboard.svelte""
jest.mock(""../src/Proxy.js"");

describe('Dashboard Component', (next) =&gt; {
  it('should update data on mount', () =&gt; {
    const target = document.createElement('div');
    const dashboard = new Dashboard({ target });

    Proxy.getData.mockResolvedValue([{
        ""id"": ""sdadasdas""
    }]);

    setTimeout(() =&gt; {
      expect(dashboard.data.length).toBe(1);
      next();
    }, 10);
  })
})
</code></pre>

<p>Now, it is not mocking the Proxy.js that I am trying to mock and always going into the inside code. </p>

<p>Any idea what is going wrong here?</p>

<p>Thanks for the help.</p>
",https://stackoverflow.com/questions/57863015/how-can-i-mock-javascript-file-imported-in-svelte-for-unit-testing,"['javascript', 'jestjs', 'svelte']",981,True,3,2
How to pass mock date event value on unit testing in angular,"<p>I have a function which needs date from datepicker event. I used matdatepicker to select date from UI.</p>

<p><strong>i want to pass date event value on onDateSelected() function.</strong></p>

<p>can anybody help me to pass date event value to pass my unit test case.</p>

<p>i tried below code but it wont works</p>

<p><strong>my function</strong></p>

<pre><code> onDateSelected(event: MatDatepickerInputEvent&lt;Date&gt;) {
    const dts = event.value;
    const startDate = moment(dts).format('MM/DD/YYYY');
    this.details.controls.contractStartDate.setValue(startDate);
    this.selectedDate = this.details.get('contractStartDate').value;
    this.selectedDate = event.value;
  }
</code></pre>

<p><strong>Unit testing code</strong></p>

<pre><code>  it('should check ondate selected event', () =&gt; {
    const date = new Date(10/03/2019);
    component.onDateSelected(date);
    fixture.detectChanges();
    expect(component.details.get('contractStartDate').value.toString()).toEqual(date);
  });
</code></pre>
",https://stackoverflow.com/questions/58231457/how-to-pass-mock-date-event-value-on-unit-testing-in-angular,"['angular', 'jasmine', 'karma-jasmine']",5103,True,3,1
How to do unit testing in the case of access log middleware,"<p>I have a middleware to log this service access. But I'm confused to do the unit testing several times I surfed googling. I have not found the right way to solve this</p>

<pre><code>package accesslog

import (
    ""net/http""
    ""time""

    ""github.com/go-chi/chi/middleware""

    ""transactionService/pkg/log""
)

func Handler(logger log.Logger) func(next http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        fn := func(w http.ResponseWriter, r *http.Request) {
            ctx := r.Context()
            ctx = log.WithRequest(ctx, r)
            ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)

            start := time.Now()
            defer func() {
                logger.With(ctx, ""duration"", time.Since(start), ""status"", ww.Status()).
                    Infof(""%s %s %s %d %d"", r.Method, r.URL.Path, r.Proto, ww.Status(), ww.BytesWritten())
            }()

            next.ServeHTTP(ww, r.WithContext(ctx))
        }

        return http.HandlerFunc(fn)
    }
}


</code></pre>
",https://stackoverflow.com/questions/59495537/how-to-do-unit-testing-in-the-case-of-access-log-middleware,"['unit-testing', 'go', 'middleware', 'go-chi']",1603,True,3,1
How to trigger a window event during unit testing using vue-test-utils,"<p>I've added 'attachToDocument', but I still can't trigger a keyup event on window.</p>

<p>my dependencies' version:</p>

<p>""@vue/test-utils"": ""^1.0.0-beta.29""</p>

<p>""vue"": ""2.5.18""</p>

<pre><code>&lt;template lang=""pug""&gt;
div
  h1 123
&lt;/template&gt;
&lt;script&gt;
export default {
  mounted() {
    window.addEventListener('keyup', this.handleKeyup)
  },
  beforeDestroy() {
    window.removeEventListener('keyup', this.handleKeyup)
  },
  methods: {
    handleKeyup() {}
  }
}
&lt;/script&gt;
</code></pre>

<pre><code>import { mount } from '@vue/test-utils'
import test from '@/views/test.vue'

describe('just test', () =&gt; {
  it('handle keyup', () =&gt; {
    const wrapper = mount(test, {
      attachToDocument: true
    })
    const handleKeyup = jest.fn()
    wrapper.setMethods({ handleKeyup })
    wrapper.trigger('keyup')
    expect(handleKeyup).toHaveBeenCalled()
  })
})
</code></pre>

<p>'handleKeyup' should have been called.</p>

<p>I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.</p>
",https://stackoverflow.com/questions/55738445/how-to-trigger-a-window-event-during-unit-testing-using-vue-test-utils,"['vue.js', 'jestjs', 'vue-test-utils']",12007,True,8,2
Error Unit testing Angular 8 / Jasmine / Karma : RangeError: Maximum call stack size exceeded,"<p>I'm using Jasmine to unit test my angular app and sometimes this error below occurs in the Karma window. I can't find where it could come from since it happens about 1/5 times on reloading. It happens when in watch mode. Any clue? </p>

<pre><code>zone.js:202 Uncaught RangeError: Maximum call stack size exceeded
      at RegExp.exec (&lt;anonymous&gt;)
      at Array.&lt;anonymous&gt; (VM2578 browser-source-map-support.js:110)
      at VM2578 browser-source-map-support.js:102
      at d (VM2578 browser-source-map-support.js:103)
      at q (VM2578 browser-source-map-support.js:106)
      at VM2578 browser-source-map-support.js:107
      at Array.map (&lt;anonymous&gt;)
      at Function.w [as prepareStackTrace] (VM2578 browser-source-map-support.js:107)
      at VM2580 jasmine.js:897
      at onerror (VM2580 jasmine.js:3199)
</code></pre>

<p>Most of the time, after reloading the karma window once, the test sets run again and it works. </p>
",https://stackoverflow.com/questions/58302285/error-unit-testing-angular-8-jasmine-karma-rangeerror-maximum-call-stack,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1962,False,8,2
Where is the Red/Green Bar for unit-testing in IntelliJ 2018?,"<p>The <a href=""https://www.jetbrains.com/help/idea/tdd-with-intellij-idea.html"" rel=""nofollow noreferrer"">manual for IntelliJ 2018</a> shows the usual Red/Green bar in the <code>Run</code> panel, as seen in this shot:</p>

<p><img src=""https://www.jetbrains.com/help/img/idea/2018.3/ij_tdd_run_failing_tests.png"" alt=""screenshot of Run panel in IntelliJ with a Red bar for failed tests""/></p>

<p>But in my IntelliJ Ultimate Edition version 2018.3.4, I see no such green or red bar, as seen in this screenshot from my computer:</p>

<p><a href=""https://i.stack.imgur.com/cvirf.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/cvirf.jpg"" alt=""screenshot of Run panel in IntelliJ failing to show the expected red or green bar for unit-testing""></a></p>
",https://stackoverflow.com/questions/54374103/where-is-the-red-green-bar-for-unit-testing-in-intellij-2018,"['unit-testing', 'intellij-idea']",1214,True,2,1
Swift Unit Testing in Xcode is not finding any Objective-C types,"<p>I'm trying to write some unit tests in Swift in Xcode. I'm needing to make use of two Swift files because they have the classes I need to utilize in this unit test.</p>

<p>These two Swift files build and run properly when I normally build/run my project.</p>

<p>However, when I attempt to use them in my unit test, I get errors for any types that are referenced in these two Swift files that are coming from any Objective-C file.</p>

<p>See this image:</p>

<p><a href=""https://i.stack.imgur.com/bWect.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/bWect.png"" alt=""missing types""></a></p>

<p>These missing types are coming from an Objective-C file. Now, these Objective-C files ARE included in my bridging header file so that's not the problem.</p>

<p>I have no other info to work off.</p>
",https://stackoverflow.com/questions/56859854/swift-unit-testing-in-xcode-is-not-finding-any-objective-c-types,"['ios', 'objective-c', 'swift', 'unit-testing']",127,False,2,1
How to set port in KafkaEmbedded when unit testing spring-kafka consumer,"<p>I am using <code>spring-boot-starter-parent</code> version <code>1.5.0.RELEASE</code>, <code>spring-kafka</code> version <code>1.0.0.RELEASE</code> and <code>spring-kafka-test</code> version <code>1.0.0.RELEASE</code> in an application which consumes messages from a <code>Kakfa 0.9</code> cluster. I have a unit test for my consumer which used <code>KafkaEmbedded</code> but it fails since the broker port is picked up randomly. Is there a way I can set this broker property without changing versions? Or which versions should I use so as to not break anything?</p>
<p>Here is the code for the <code>KafkaListener</code> and <code>KafkaConsumerTest</code>.</p>
<h3><strong>Listener.java</strong></h3>
<pre><code>@Service
public class Listener {

    private static final Logger logger = LoggerFactory.getLogger(Listener.class);
    private CountDownLatch latch = new CountDownLatch(1);

    @KafkaListener(topics = &quot;topic&quot;, group = &quot;group&quot;, containerFactory = &quot;kafkaListenerContainerFactory&quot;)
    public void consumeClicks(@Payload String msg, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) Integer partition, @Header(KafkaHeaders.OFFSET) Integer offset, Acknowledgment ack) throws Exception {
        logger.info(msg);
        latch.countDown();
        ack.acknowledge();
    }

    public CountDownLatch getLatch() {
        return latch;
    }
}

</code></pre>
<h3><strong>KafkaConsumerTest.java</strong> (<em>EDIT</em>)</h3>
<pre><code>@DirtiesContext
@SpringBootTest(classes = {SpringApplication.class})
@RunWith(SpringRunner.class)
public class KafkaConsumerTest {
    private static final Logger logger = LoggerFactory.getLogger(KafkaConsumerTest.class);
    private static String TEST_TOPIC = &quot;topic&quot;;

    @ClassRule
    public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, TEST_TOPIC);

    public KafkaTemplate&lt;String, String&gt; template;

    @Autowired
    private KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;

    @Autowired
    private Listener listener;

    @Before
    public void init(){
        System.setProperty(&quot;spring.kafka.bootstrap-servers&quot;, embeddedKafka.getBrokersAsString());
        Map&lt;String, Object&gt; senderProps = KafkaTestUtils.senderProps(embeddedKafka.getBrokersAsString());
        senderProps.put(&quot;key.serializer&quot;, StringSerializer.class);
        ProducerFactory&lt;String, String&gt; producerFactory = new DefaultKafkaProducerFactory&lt;String, String&gt;(senderProps);
        template = new KafkaTemplate&lt;&gt;(producerFactory);
        template.setDefaultTopic(TEST_TOPIC);
    }

    @Test
    public void testConsume() throws Exception {
        String record = &quot;message&quot;;
        template.sendDefault(TEST_TOPIC, record);
        logger.debug(&quot;test-consume sent record {}&quot;, record);
        listener.getLatch().await(1000, TimeUnit.MILLISECONDS);
        Assert.assertEquals(listener.getLatch().getCount(), 0);
    }
}

</code></pre>
",https://stackoverflow.com/questions/56225440/how-to-set-port-in-kafkaembedded-when-unit-testing-spring-kafka-consumer,"['java', 'spring-kafka', 'spring-kafka-test']",8910,False,2,2
"EF Core in memory, delete unit testing giving error: entity already tracked","<p>I am working with entity framework core in memory to test my code.I created in memory context and added data. I have delete method which is going to delete record with id=1. Test method is throwing error following error:</p>

<blockquote>
  <p>The instance of entity type 'cats' cannot be tracked because another instance with the key value '{Id: 204}' is already being tracked When attaching existing entities, ensure that only one entity instance with a given key value is attached.</p>
</blockquote>

<p>Could any one help me , how to resolve this issue. I tried different scenarios on internet, but nothing did not work.</p>

<p><strong>Test.cs:</strong></p>

<pre><code>   [Fact(DisplayName =""Delete Service Must Return Result"")]
    public void DeleteService()
    {
        var serviceId = _collectionFixture.context.cat.Where(x =&gt; x.Id == 201).AsNoTracking();

       var okObject = _collectionFixture.CatController.DeleteService(serviceId) as OkObjectResult;

          var baseResponse = okObject.Value as BaseResponse;
           Assert.True(baseResponse.Success);
    }
</code></pre>

<p>my service class: </p>

<p>public catResponse DeleteService(int serviceId)
          {
               try{</p>

<pre><code>               var serviceDto = _Context.catserviceTreatment.Where(x =&gt; x.Id 
                           ==serviceId).AsNoTracking().firstordefault();

            if(serviceDto!=null)
            {


                    this._Context.catserviceTreatment.Remove(serviceDto);
                    this._Context.SaveChanges();

                   return new catResponse { Success = true, Error = ""service 
                              deleted successfully"" };
            }

           }catch(exception e)
           {
           } 
      }
</code></pre>

<p>my collection fixture:</p>

<pre><code>      public catContext GetDbContext()
              {
                  var options = new DbContextOptionsBuilder&lt;catContext&gt;()
                 .UseInMemoryDatabase(Guid.NewGuid().ToString())

               .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)

                  .ConfigureWarnings(x =&gt; 
                 x.Ignore(InMemoryEventId.TransactionIgnoredWarning))
               //  .ConfigureWarnings(x=&gt;x.Ignore(InMemoryEventId.))
                .EnableSensitiveDataLogging()
                   .Options;

                var context = new CatDirectoryContext(options);

            var catCategory = new List&lt;catcategory&gt;()
               {
                   new catCategory{Id=100,CategoryName=""Youth 
                teereafjkd"",UpdatedBy=""Test"",UpdatedWhen=DateTime.Now},
                 new catCategory{Id=101,CategoryName=""Adult 
                fdsafd"",UpdatedWhen=DateTime.Now},     
        };

        context.catcategory.AddRange(catCategory);
        context.SaveChanges();


        var catService = new List&lt;catserviceTreatment&gt;()
        {
            new catserviceTreatment{Id=200,Name=""House of 
          Hope"",Company="""",
                Address =""2001 st street"",City=""alone 
           city"",State=""UT"",ZipCode=8404,Category=null,
                CategoryId =100,Description=""this is 
           description"",UpdatedBy=""test"",UpdatedWhen=DateTime.Now},

            new catserviceTreatment{Id=201,Name=""Odyssey 
             House"",Company="""",
                Address =""2001 st"",City=""bare 
               city"",State=""UT"",ZipCode=84dfd,Category=null,
                CategoryId =101,Description=""this is d 
                 description"",UpdatedBy=""test"",UpdatedWhen=DateTime.Now},

        }
        context.catserviceTreatment.AddRange(catService);

        context.SaveChanges();

        return context;

   }
</code></pre>
",https://stackoverflow.com/questions/56083683/ef-core-in-memory-delete-unit-testing-giving-error-entity-already-tracked,"['entity-framework-core', 'in-memory-database']",3596,False,2,2
How to use Conversation state for unit testing a bot builder dialog?,"<p>I am developing a multi lingual bot that uses LUIS for NLU conversation state to store the language preference.</p>

<pre class=""lang-js prettyprint-override""><code>const { ComponentDialog, WaterfallDialog } = require(""botbuilder-dialogs"");
const { t } = require(""../../utils/translations"");

class HowAreYou extends ComponentDialog {
  constructor(id, localeProp) {
    super(id);
    this.localeProp = localeProp;
    this.initialDialogId = ""mainDialog"";

    this.addDialog(
      new WaterfallDialog(this.initialDialogId, [this.showHowAreYou.bind(this)])
    );
  }

  async showHowAreYou(step) {
    const locale = await this.localeProp.get(step.context);
    await step.context.sendActivity(t(locale, ""how_are_you_response""));
    return await step.endDialog();
  }
}

exports.HowAreYou = HowAreYou;
</code></pre>

<p>This is the code for the unit test.</p>

<pre class=""lang-js prettyprint-override""><code>const { DialogTestClient, DialogTestLogger } = require(""botbuilder-testing"");
const assert = require(""assert"");
const { HowAreYou } = require(""../../../app/dialogs/small-talk/how-are-you"");
const { SMALL_TALK } = require(""../../../app/data/dialog-ids"");

describe(""How are you dialog"", () =&gt; {
  it(""Should respond with its status"", async () =&gt; {
    const howAreYouClient = new DialogTestClient(
      SMALL_TALK.HOW_ARE_YOU,
      HowAreYou,
      undefined,
      [new DialogTestLogger()]
    );
    let reply = await howAreYouClient.sendActivity(""How are you doing?"");
    assert.strictEqual(reply.text, ""Wonderful as always! Thanks for asking"");
  });
});

</code></pre>

<p>When running the test with <code>npm test</code>, the test failed and throws this error:</p>

<pre><code>&gt; mocha test/**/*



  How are you dialog
    - User: Text = How are you doing?
    - -&gt; ts: 11:40:28
    1) Should respond with its status


  0 passing (14ms)
  1 failing

  1) How are you dialog
       Should respond with its status:
     Error: DialogSet.add(): Invalid dialog being added.
      at DialogSet.add (node_modules/botbuilder-dialogs/lib/dialogSet.js:87:19)
</code></pre>

<p>In the main bot file constructor, I <strong>added</strong> the logic for <strong>loading</strong> all the bot dialogues and adding them to the <strong>dialogSet</strong>. How can I fix the issue in order simulate a test data.</p>
",https://stackoverflow.com/questions/59287394/how-to-use-conversation-state-for-unit-testing-a-bot-builder-dialog,"['node.js', 'unit-testing', 'botframework']",278,False,2,0
How to cause SpringBoot/Hibernate to create a schema for unit testing?,"<p><strong>Environment</strong></p>

<p>SpringBoot 2 with H2 as test dependency.</p>

<p><strong>Production works</strong></p>

<p>Jar is deployed to cloud. A DB2 service is configured with driver and connection details, and automatically bound to the java application. There's no configuration in the jar itself. There is the application.properties file but it's empty. This part works fine and I'm hoping that a solution exists which will not require me to create property files and profiles.</p>

<p><strong>Local Unit Test crashes on 'schema xxx not found'</strong></p>

<pre><code>@Entity(table=""Employee"", schema=""acme"")
class Employee {
...
}

@RunWith(SpringRunner.class)
@DataJpaTest
public class EmployeeTest {
...
}
</code></pre>

<ol>
<li>No data source configuration exists. </li>
<li>SpringBoot sees H2 dependency and selects Hibernate by default. </li>
<li>Hibernate sees the Entity definition and attempts to drop the table first. </li>
<li>The drop uses the schema name <code>drop table acme.employee if exists</code>. No schema has been created so process fails with <code>JdbcSQLSyntaxErrorException: Schema ""acme"" not found</code>.</li>
<li>I tried <code>@TestPropertySource(properties =""jdbc:h2:testb;INIT=CREATE SCHEMA IF NOT EXISTS acme;"")</code> with no luck.</li>
</ol>

<p>I've found issues like this on the web and potential solutions. But they go very far into Hibernate and/or Spring configuration files. I would really want to avoid this. It's only local unit test that fails so I'm hoping to find a solution that is contained within the test.</p>
",https://stackoverflow.com/questions/57318288/how-to-cause-springboot-hibernate-to-create-a-schema-for-unit-testing,"['java', 'spring', 'hibernate', 'spring-boot', 'h2']",1222,True,1,2
How can I solve error when unit testing with mocha on vue?,"<p>I using <code>mocha</code> to do unit testing to my vuetify project</p>

<p>I had install it. So I run <code>npm run test:unit</code>, there exist error like this :</p>

<pre><code>npm ERR! Failed at the test-vuetify@0.1.0 test:unit script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code></pre>

<p>The full error like this :</p>

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

<p>How can I solve this error?</p>

<p><strong>Note</strong> :</p>

<p>When I first installed vuetify and tried unit testing, it worked. No error</p>

<p>After I edited some parts and ran the unit test, the above error appeared</p>

<p>How do I resolve this error?</p>

<p><strong>Update</strong> :</p>

<p>I have updated the version of vuetify. Is that what caused this error?</p>

<p>I am confused to solve this error. Because all errors are located in the node-modules folder. Not in the component that I made</p>
",https://stackoverflow.com/questions/59127109/how-can-i-solve-error-when-unit-testing-with-mocha-on-vue,"['unit-testing', 'vue.js', 'mocha.js', 'vue-component', 'vuetify.js']",226,False,1,1
How to mock the window navigator object while unit testing angular code,"<p>I am using jasmine to write a unit test in angular. The method uses the the window.navigator property. The property is defined outside the method like below </p>

<pre><code>declare var navigator: any;
navigator = window.navigator;
</code></pre>

<p>In the method to be tested the below code is present which is to be tested</p>

<pre><code>let locale = navigator.language || navigator.userLanguage || navigator.browserLanguage; 
</code></pre>

<p>The first condition <code>navigator.language</code> gets covered automatically while running the unit test. 
I want to cover all branches of this code ie, I want to cover all OR conditions while testing. How do I mock the navigator in unit test?</p>
",https://stackoverflow.com/questions/54558211/how-to-mock-the-window-navigator-object-while-unit-testing-angular-code,"['angular', 'unit-testing', 'jasmine']",3453,True,1,2
How to configure a maven project for unit testing Spring Cloud functions,"<p>What's the right way to set up the Spring Cloud project with the functions and unit testing?</p>

<p>I want to create a standalone web application with Spring Cloud Function and have a possibility to cover it by the unit tests. I've set it up according to the <a href=""https://cloud.spring.io/spring-cloud-function/reference/html/spring-cloud-function.html"" rel=""nofollow noreferrer"">reference guide</a>:</p>

<ol>
<li>I created the maven project with the <code>spring-boot-starter-parent</code>.</li>
<li>Added <code>spring-cloud-dependencies</code> to a dependencyManagement.</li>
<li>Added <code>spring-cloud-starter-function-web</code> starter.</li>
<li>Added testing dependencies:

<ul>
<li>Added <code>junit-bom</code> for the 5th version to a dependencyManagement.</li>
<li>Added <code>spring-boot-starter-test</code> starter and excluded <code>junit</code> from it.</li>
<li>Added <code>junit-jupiter</code> and <code>mockito-junit-jupiter</code> dependencies.</li>
</ul></li>
</ol>

<p>My <code>FunctionapApplication</code> contains the bean <code>uppercase</code> as function, the exmaple from docs. I'm trying to make a test for it.</p>

<pre class=""lang-java prettyprint-override""><code>@ExtendWith(SpringExtension.class)
@FunctionalSpringBootTest
@AutoConfigureWebTestClient
class FunctionsApplicationTest {

  @Autowired
  WebTestClient client;

  @BeforeEach
  void setUp() {
    // set up
  }

  @Test
  void shouldCallFunctionViaWeb() {
    client.post().uri(""/"").body(""foo"", String.class).exchange()
      .expectStatus().isOk().expectBody(String.class).isEqualTo(""FOO"");
  }

}
</code></pre>

<p>But it fails to start a context and finds <code>WebTestClient</code>:</p>

<pre><code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.example.file.FunctionsApplicationTest': Unsatisfied dependency expressed through field 'client'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.test.web.reactive.server.WebTestClient' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:98)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassBasedTestDescriptor.java:337)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:342)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:337)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:313)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:743)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:742)
    at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:647)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:336)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:259)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:252)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$3(ClassBasedTestDescriptor.java:251)
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:29)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:106)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:105)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:69)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:107)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:107)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:75)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    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:1257)
    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:128)
    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)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.test.web.reactive.server.WebTestClient' 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:1695)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
    ... 67 more

</code></pre>

<p>and a small piece from a conditions evaluation report:</p>

<pre><code>Unconditional classes:
----------------------

    org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration

    org.springframework.cloud.client.ReactiveCommonsClientAutoConfiguration

    org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClientAutoConfiguration

    org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration

    org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration

    org.springframework.cloud.client.serviceregistry.ServiceRegistryAutoConfiguration

    org.springframework.cloud.autoconfigure.LifecycleMvcEndpointAutoConfiguration

    org.springframework.cloud.client.CommonsClientAutoConfiguration

    org.springframework.cloud.commons.httpclient.HttpClientConfiguration

    org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
</code></pre>

<p>What am I doing wrong?</p>

<p><strong>UPDATE</strong><br>
I guess the issue with <code>@AutoConfigureWebTestClient</code> and injecting <code>WebTestClient</code>.</p>
",https://stackoverflow.com/questions/59388822/how-to-configure-a-maven-project-for-unit-testing-spring-cloud-functions,"['java', 'spring', 'maven', 'spring-cloud', 'spring-cloud-function']",1308,True,1,1
Exclude a line of Code from coverage during Unit Testing with NUnit,"<p>When trying to perform a Unit test on a Unit of code, I am running into an issue, where an Object has not been instantiated (this is a Controller in an API) , and I'm receiving a null reference exception that I cannot bypass to properly test the method. The suspect line is something along: </p>

<pre><code>Class.List.Add(Object)
</code></pre>

<p>where the Class.List is null. </p>

<p>I understand I can write a Null reference check in the controller by doing </p>

<pre><code>  if(Class.List != null) 
          {
          Class.List.Add(Object)
          }
</code></pre>

<p>But I know there must be a cleaner way to do this, that adheres more closely to Unit test best practices.</p>

<p>I am using NUnit with C#.</p>

<p>Thank you for your time and explanations</p>

<p>Edit: To add more context, the Class is  the Program.cs class.</p>
",https://stackoverflow.com/questions/57365487/exclude-a-line-of-code-from-coverage-during-unit-testing-with-nunit,"['c#', 'wpf', 'unit-testing', 'nunit']",766,False,1,0
Entity Framework Core 2.2 not reseting after tear down while unit testing,"<p>I'm attempting to write some unit tests to cover as much of my api as possible, but instead of using a database I've decided to use the InMemory provider, not to test that EF works, rather that my implantation is correct, but what I'm running into is a strange side effect.</p>

<p>Essentially what is happening is the id values for objects that are seeded, are not resetting after each test.</p>

<p>In MSTest I've implemented a setup to create a new database context for each test, providing a new name for each test run and am making sure to call <code>EnsureCreated()</code>  before seeding my database. In addition I'm also implementing a TearDown to ensure that the database is correctly disposed.</p>

<pre><code>[TestClass]
public class CountryTests
{
    private CdiContext Context { get; set; }

    [TestInitialize]
    public void Setup()
    {
        DbContextOptions&lt;CdiContext&gt; options = new DbContextOptionsBuilder&lt;CdiContext&gt;()
            .UseInMemoryDatabase(databaseName: $""{Guid.NewGuid()}"")
            .Options;

        Context = new CdiContext(options);
        Context.Database.EnsureCreated();
        Seed();
    }

    [TestCleanup]
    public void TearDown()
    {
        Context.Database.EnsureDeleted();
    }

    private void Seed()
    {
        var service = new CoreDataService(Context);

        var regions = new List&lt;Region&gt;
        {
            new Region
            {
                Name = ""Asia"",
                State = RecordState.Active,
                Created = DateTime.Now,
                UserId = Guid.NewGuid().ToString()
            },

            new Region
            {
                Name = ""Africa"",
                State = RecordState.Active,
                Created = DateTime.Now,
                UserId = Guid.NewGuid().ToString()
            },

            new Region
            {
                Name = ""South America"",
                State = RecordState.Active,
                Created = DateTime.Now,
                UserId = Guid.NewGuid().ToString()
            }
        };

        Context.Regions.AddRange(regions);
        Context.SaveChanges();
    }

    [TestMethod]
    public async Task CanAddCountry()
    {
        //-- arrange
        var service = new CoreDataService(Context);

        var userId = ""133BC82D-FDE2-4124-9207-CD3465511AEB"";
        var region = await service.GetRegionById(1);

        var country = new Country
        {
            Name = ""Canada"",
            State = RecordState.Active,
            UserId = userId,
            Created = DateTime.Now,
            RegionId = region.Id
        };

        //-- act
        var results = await service.AddCountry(country);

        //-- assert
        Assert.IsTrue(results.Name == ""Canada"");
        Assert.IsTrue(results.UserId == ""133BC82D-FDE2-4124-9207-CD3465511AEB"");
        Assert.IsNotNull(results.Region);
    }

    [TestMethod]
    public async Task CanGetCountries()
    {
        //-- arrange
        var service = new CoreDataService(Context);

        var userId = ""133BC82D-FDE2-4124-9207-CD3465511AEB"";
        var region = service.GetRegionById(1);
        var names = new[] {""Canada"", ""Wales"", ""Japan"", ""Australia"", ""Hawaii"", ""Germany""};

        for (var x = 0; x &lt; 5; x++)
        {
            await service.AddCountry(new Country
            {
                Name = names[x],
                State = RecordState.Active,
                UserId = userId,
                Created = DateTime.Now,
                RegionId = region.Id
            });
        }

        //-- act
        var results = await service.GetCountries();

        //-- assert
        Assert.IsNotNull(results);
        Assert.IsTrue(results.Count == 5);
    }

    [TestMethod]
    public async Task CanDeleteCountry()
    {
        //-- arrange
        var service = new CoreDataService(Context);

        var userId = ""133BC82D-FDE2-4124-9207-CD3465511AEB"";
        var region = service.GetRegionById(1);
        var names = new[] { ""Canada"", ""Wales"", ""Japan"", ""Australia"", ""Hawaii"", ""Germany"" };

        for (var x = 0; x &lt; 5; x++)
        {
            await service.AddCountry(new Country
            {
                Name = names[x],
                State = RecordState.Active,
                UserId = userId,
                Created = DateTime.Now,
                RegionId = region.Id
            });
        }

        //-- act
        await service.DeleteCountry(id: 2, userId: Guid.NewGuid().ToString());

        var countries = await service.GetCountries();
        var country = await service.GetCountryById(2);

        //-- assert
        Assert.IsTrue(countries.Count != 5);
        Assert.IsNull(country);
    }
}
</code></pre>

<p>Now when I run this, the third test fails, because it can't find the correct id, and this to me is a bit weird.</p>

<p>I initially thought this was a problem with MSTest, but noticed the same behaviour in xUnit as well.</p>

<pre><code>public class CdiTestBase : IDisposable
{
    protected readonly CdiContext _context;

    public CdiTestBase()
    {
        var options = new DbContextOptionsBuilder&lt;CdiContext&gt;()
            .UseInMemoryDatabase(databaseName: $""{Guid.NewGuid()}"")
            .Options;

        _context = new CdiContext(options);

        _context.Database.EnsureCreated();

        SeedRegions(_context);
    }

    public void Dispose()
    {
        _context.Database.EnsureDeleted();

        _context.Dispose();
    }

    private void SeedRegions(CdiContext context)
    {
        var regions = new List&lt;Region&gt;
        {
            new Region
            {
                Name = ""Asia"",
                State = RecordState.Active,
                Created = DateTime.Now,
                UserId = Guid.NewGuid().ToString()
            },

            new Region
            {
                Name = ""Africa"",
                State = RecordState.Active,
                Created = DateTime.Now,
                UserId = Guid.NewGuid().ToString()
            },

            new Region
            {
                Name = ""South America"",
                State = RecordState.Active,
                Created = DateTime.Now,
                UserId = Guid.NewGuid().ToString()
            }
        };

        context.Regions.AddRange(regions);
        context.SaveChanges();
    }
}

public class CountryTests : CdiTestBase
{
    [Fact]
    public async Task CanAddCountry()
    {
        //-- arrange
        var service = new CoreDataService(_context);

        var userId = ""133BC82D-FDE2-4124-9207-CD3465511AEB"";
        var region = await service.GetRegionById(1);

        var country = new Country
        {
            Name = ""Canada"",
            State = RecordState.Active,
            UserId = userId,
            Created = DateTime.Now,
            RegionId = region.Id
        };

        //-- act
        var results = await service.AddCountry(country);

        //-- assert
        Assert.True(results.Name == ""Canada"");
        Assert.True(results.UserId == ""133BC82D-FDE2-4124-9207-CD3465511AEB"");
        Assert.NotNull(results.Region);
    }

    [Fact]
    public async Task CanGetCountries()
    {
        //-- arrange
        var service = new CoreDataService(_context);

        var userId = ""133BC82D-FDE2-4124-9207-CD3465511AEB"";
        var region = service.GetRegionById(1);
        var names = new[] { ""Canada"", ""Wales"", ""Japan"", ""Australia"", ""Hawaii"", ""Germany"" };

        for (var x = 0; x &lt; 5; x++)
        {
            await service.AddCountry(new Country
            {
                Name = names[x],
                State = RecordState.Active,
                UserId = userId,
                Created = DateTime.Now,
                RegionId = region.Id
            });
        }

        //-- act
        var results = await service.GetCountries();

        //-- assert
        Assert.NotNull(results);
        Assert.True(results.Count == 5);
    }

    [Fact]
    public async Task CanDeleteCountry()
    {
        //-- arrange
        var service = new CoreDataService(_context);

        var userId = ""133BC82D-FDE2-4124-9207-CD3465511AEB"";
        var region = service.GetRegionById(1);
        var names = new[] { ""Canada"", ""Wales"", ""Japan"", ""Australia"", ""Hawaii"", ""Germany"" };

        for (var x = 0; x &lt; 5; x++)
        {
            await service.AddCountry(new Country
            {
                Name = names[x],
                State = RecordState.Active,
                UserId = userId,
                Created = DateTime.Now,
                RegionId = region.Id
            });
        }

        //-- act
        await service.DeleteCountry(id: 2, userId: Guid.NewGuid().ToString());

        var countries = await service.GetCountries();
        var country = await service.GetCountryById(2);

        //-- assert
        Assert.True(countries.Count != 5);
        Assert.Null(country);
    }
}
</code></pre>

<p>If I run all the tests at the same time, I consistently get test failures, but if I run each test individually they all pass, and this bothers me.</p>
",https://stackoverflow.com/questions/55952419/entity-framework-core-2-2-not-reseting-after-tear-down-while-unit-testing,"['c#', 'entity-framework-core', 'mstest', 'xunit']",587,True,1,1
How can I clear all test data between two unit testing method?,"<p>I want to write some unit tests for Flowable, but different methods may have data conflicts. What should I do to clear the test data between two test methods?</p>

<p>I tried the annotation <code>@DirtiesContext</code> but it didn't work.</p>

<pre class=""lang-java prettyprint-override""><code>@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles(""test"")
@Import(TestConfig.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class FlowableTest {
    @Autowired
    private ProcessEngine processEngine;

    @Test
    public void test() {
        IdentityService identityService = processEngine.getIdentityService();
        Group defaultGroup = identityService.newGroup(""default"");
        defaultGroup.setName(""233333"");
        identityService.saveGroup(defaultGroup);
    }

    @Test
    public void test2() {
        IdentityService identityService = processEngine.getIdentityService();
        Group defaultGroup = identityService.newGroup(""default"");
        defaultGroup.setName(""233333"");
        identityService.saveGroup(defaultGroup);
        // do some thing
    }
}

</code></pre>

<p>This is the error message.</p>

<pre><code>Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation: ""PUBLIC.PRIMARY_KEY_6B ON PUBLIC.ACT_ID_GROUP(ID_) VALUES 1""; SQL statement:
insert into ACT_ID_GROUP (ID_, REV_, NAME_, TYPE_)
    values (
      ?,
      1, 
      ?,
      ?
    ) [23505-199]
</code></pre>

<p>And then I want to create tables manually before each method, I found the ""flowable.h2.create.history.sql"" and ""flowable.h2.create.engine.sql"" 
in ""flowable-engine-6.4.1.jar"" ,but when I rerun these unit tests, I found there are lots of columns missing.</p>

<p>Is there any easy way to clear all test data?</p>
",https://stackoverflow.com/questions/56867121/how-can-i-clear-all-test-data-between-two-unit-testing-method,"['java', 'spring-boot', 'flowable']",441,False,1,1
Django unit testing: Separating unit tests without querying the database multiple times,"<p>I have a pair of tests like this: </p>

<h1>Make sure a task's deletion status initializes as None</h1>

<pre><code>def test_initial_task_deletion_status_is_none(self):
    unfinished_task = Task.objects.get(tasked_with=""Unfinished Test"")
    self.assertIsNone(unfinished_task.delete_status)

# Make sure a task's deletion status changes appropriately
def test_unfinished_task_deletion_status_updates_appropriately(self):
    unfinished_task = Task.objects.get(tasked_with=""Unfinished Test"")
    unfinished_task.timed_delete(delta=.1)
    self.assertIs(unfinished_task.delete_status, ""Marked for Deletion"")
</code></pre>

<p>This will go on, but I'll have <code>unfinished_task = Task.objects.get(tasked_with=""Unfinished Test"")</code> at the beginning of every one. Is there a way to split these types of things into separate tests, but use the same query result?</p>
",https://stackoverflow.com/questions/54242511/django-unit-testing-separating-unit-tests-without-querying-the-database-multipl,"['django', 'unit-testing']",36,True,1,2
How to override the H2 with embedded postgreSQl lib in unit testing?,"<p>In unit testing for Corda, it runs a H2 DB. Given that I run a postgreSQL in production, I would like to run using PostgreSQL during unit testing to close this gap (rather than leave it to integrating testing) as well. There are embedded postgreSQL lib to ""mock"" postgreSQL"". </p>

<p>How can i override the default H2 DB in Corda to run a embedded postgreSQL instead during unit testing?</p>
",https://stackoverflow.com/questions/57917481/how-to-override-the-h2-with-embedded-postgresql-lib-in-unit-testing,['corda'],110,True,1,1
Unit testing NgRx effect to ensure the service method was called - ain&#39;t working,"<p>I am using NgRx ^7.0.0 version.
This is my NgRx effect class:</p>

<pre><code>import { Injectable } from '@angular/core';
import { ApisService } from '../apis.service';
import { Effect, Actions, ofType } from '@ngrx/effects';
import { Observable } from 'rxjs';
import { ApisActionTypes, ApisFetched } from './apis.actions';
import { mergeMap, map } from 'rxjs/operators';

@Injectable()
export class ApisEffects {

  constructor(private apisS: ApisService, private actions$: Actions) { }

  @Effect()
  $fetchApisPaths: Observable&lt;any&gt; = this.actions$.pipe(
    ofType(ApisActionTypes.FetchApisPaths),
    mergeMap(() =&gt;
      this.apisS.fetchHardCodedAPIPaths().pipe(
        map(res =&gt; new ApisFetched(res))
      )
    )
  );
}
</code></pre>

<p>And that's a simple test. As you can see it should fail, but is always passing.
I followed similar question here on StackOverflow <a href=""https://stackoverflow.com/questions/48318095/how-to-unit-test-this-effect-with-dispatch-false"">How to unit test this effect (with {dispatch: false})?</a> but it doesn't work for me, as if the code execution never enters the effects.$fetchApisPaths.subscribe block</p>

<pre><code>import { TestBed } from '@angular/core/testing';
import { provideMockActions } from '@ngrx/effects/testing';
import { hot, cold } from 'jasmine-marbles';
import { Observable, ReplaySubject } from 'rxjs';
import { ApisEffects } from '../state/apis.effects';
import { ApisFetch, ApisFetched } from '../state/apis.actions';
import { IApiPath } from '../models';
import { convertPaths, getAPIPathsAsJson, ApisService } from '../apis.service';
import { ApisServiceMock } from './mocks';

describe('Apis Effects', () =&gt; {
  let effects: ApisEffects;
  let actions: Observable&lt;any&gt;;
  let apisS: ApisService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        ApisEffects,
        provideMockActions(() =&gt; actions),
        {
          provide: ApisService,
          useClass: ApisServiceMock
        }
      ]
    });

    effects = TestBed.get(ApisEffects);
    apisS = TestBed.get(ApisService);
  });

  it('should call ApisService method() to get Api Paths', () =&gt; {
    const spy = spyOn(apisS, 'fetchHardCodedAPIPaths');

    const action = new ApisFetch();
    actions = hot('--a-', {a: action});

    effects.$fetchApisPaths.subscribe(() =&gt; {
      console.log('%c effect trigerred', 'color: orange; border: 1px solid red;');
      // expect(spy).toHaveBeenCalled();
      expect(true).toBe(false); // never fails
    });
  });
});
</code></pre>

<p>Just in case I am doing smthg stupid with actions, here is the actions file:
Most likely I am not, since it's working in the app as expected.</p>

<pre><code>import { Action } from '@ngrx/store';
import { IApiPath } from '../models';

export enum ApisActionTypes {
    FetchApisPaths = '[Apis] Fetch Paths',
    FetchedApisPaths = '[Apis] Fetched Paths'
}

export class ApisFetch implements Action {
    readonly type = ApisActionTypes.FetchApisPaths;
}

export class ApisFetched implements Action {
    readonly type = ApisActionTypes.FetchedApisPaths;
    constructor(public payload: IApiPath[]) {}
}

export type ApisActions = ApisFetch | ApisFetched;
</code></pre>

<p>=======================EDIT==============================</p>

<p>I have used an example from official ngrx docs <a href=""https://ngrx.io/guide/effects/testing"" rel=""noreferrer"">https://ngrx.io/guide/effects/testing</a> and now I can successfully enter the subscribe block below, I get both console logs logged, but the test succeeds. This is bizarre! I have tried throwing errors from the subscribe block and the test still succeeds.</p>

<pre><code>it('should work also', () =&gt; {
    actions$ = new ReplaySubject(1);

    actions$.next(new ApisFetch());

    effects.$fetchApisPaths.subscribe(result =&gt; {
      console.log('will be logged');
      expect(true).toBe(false); // should fail but nothing happens - test succeeds
      console.log(' --------- after '); // doesn't get called, so the code
      // execution stops on expect above
    });
  });
</code></pre>
",https://stackoverflow.com/questions/54292921/unit-testing-ngrx-effect-to-ensure-the-service-method-was-called-aint-working,"['angular', 'unit-testing', 'jestjs', 'ngrx', 'ngrx-effects']",5203,True,6,1
How can I access Objects within a void method while unit testing?,"<p>I am unit testing a Spring Boot service method. I have a void method with no args. It queries a db and gets a List. I can mock and assert on that. Then it runs through the list and changes object fields according to some condition. How can I check the contents of that list so I can assert on them?</p>

<pre><code>@Transactional
public void someMethod() {
    List&lt;Person&gt; myList = repository.findAllByAge(0);
    myList.forEach(person -&gt; person.setAge(18));
}
</code></pre>

<p>How can I assert on myList to check that each Person in myList with age 0 is getting set to age 18? I currently have this in my test class...</p>

<pre><code>@Test
public void someMethod_withSuccess() {
    List&lt;Person&gt; testList = new ArrayList&lt;&gt;();
    testList.add(toPersonEntity(createPersonDto().setAge(0)));
    when(mockRepo.findAllByAge(0)).thenReturn(testList);

    mockService.someMethod();
}
</code></pre>
",https://stackoverflow.com/questions/59204979/how-can-i-access-objects-within-a-void-method-while-unit-testing,"['java', 'unit-testing', 'mockito', 'void']",345,False,1,2
I am trying to write unit testing of QuerydslRepositorySupport in spring boot,"<p>I am developing a spring boot 2.2.0 application using QuerydslRepositorySupport as a Data Access Object (DAO aka Repository).  I would very much like to write a unit test for it but haven't been successful so far. Has anyone come across this problem before and how do you solve it?  below is my code </p>

<p>BankAccountRepository.java</p>

<pre><code>@Repository
public class BankAccountRepository extends QuerydslRepositorySupport {

    private QBankAccountDO qBankAccount = QBankAccountDO.bankAccountDO;

    public BankAccountRepository() {
        super(BankAccountDO.class);
    }

    public Page&lt;BankAccountDO&gt; searchBankAccountDOByShopId(SearchBankAccountRequest request, Pageable pageable) {
        if(request == null || request.getShopId() == null) {
            return new PageImpl&lt;&gt;(new ArrayList&lt;BankAccountDO&gt;(), pageable, 0L);
        }

        JPQLQuery&lt;BankAccountDO&gt; query = from(qBankAccount).where( qBankAccount.shop.id.eq(request.getShopId()) );

        return new PageImpl&lt;&gt;(getQuerydsl().applyPagination(pageable, query).fetch(), pageable, query.fetchCount());
    }
}

</code></pre>

<p>BankAccountRepositoryTest.java</p>

<pre><code>@ExtendWith(SpringExtension.class)
@DataJpaTest
public class BankAccountRepositoryTest {

    @Autowired
    private BankAccountRepository bankAccountRepository;

    @Test
    public void testtest() {
        assertThat(bankAccountRepository).isNotNull();
    }

}
</code></pre>

<p>src/test/resources/application.properties</p>

<pre><code>spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

spring.liquibase.enabled=true
spring.liquibase.contexts=development
spring.liquibase.change-log=classpath:liquibase/liquibase.xml
spring.liquibase.drop-first=false
</code></pre>

<p>test result</p>

<pre><code>2019-11-01 20:35:07.235  INFO 6964 --- [           main] l.lockservice.StandardLockService        : Successfully released change log lock
2019-11-01 20:35:07.438  INFO 6964 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2019-11-01 20:35:07.594  INFO 6964 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.4.6.Final}
2019-11-01 20:35:07.828  INFO 6964 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2019-11-01 20:35:08.000  INFO 6964 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-11-01 20:35:08.889  INFO 6964 --- [           main] org.hibernate.tuple.PojoInstantiator     : HHH000182: No default (no-argument) constructor for class: com.smehelper.product.entity.SubProductDO (class must be instantiated by Interceptor)
2019-11-01 20:35:09.249  INFO 6964 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2019-11-01 20:35:09.264  INFO 6964 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'



============================
CONDITIONS EVALUATION REPORT
============================


Positive matches:
-----------------

   DataSourceAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'javax.sql.DataSource', 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType' (OnClassCondition)

   DataSourceAutoConfiguration.PooledDataSourceConfiguration matched:
      - AnyNestedCondition 1 matched 1 did not; NestedCondition on DataSourceAutoConfiguration.PooledDataSourceCondition.PooledDataSourceAvailable PooledDataSource found supported DataSource; NestedCondition on DataSourceAutoConfiguration.PooledDataSourceCondition.ExplicitType @ConditionalOnProperty (spring.datasource.type) did not find property 'type' (DataSourceAutoConfiguration.PooledDataSourceCondition)
      - @ConditionalOnBean (types: javax.sql.DataSource,javax.sql.XADataSource; SearchStrategy: all) did not find any beans (OnBeanCondition)

   DataSourceConfiguration.Hikari matched:
      - @ConditionalOnClass found required class 'com.zaxxer.hikari.HikariDataSource' (OnClassCondition)
      - @ConditionalOnProperty (spring.datasource.type=com.zaxxer.hikari.HikariDataSource) matched (OnPropertyCondition)
      - @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) did not find any beans (OnBeanCondition)

   DataSourcePoolMetadataProvidersConfiguration.HikariPoolDataSourceMetadataProviderConfiguration matched:
      - @ConditionalOnClass found required class 'com.zaxxer.hikari.HikariDataSource' (OnClassCondition)

   DataSourceTransactionManagerAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'org.springframework.jdbc.core.JdbcTemplate', 'org.springframework.transaction.PlatformTransactionManager' (OnClassCondition)

   DataSourceTransactionManagerAutoConfiguration.DataSourceTransactionManagerConfiguration matched:
      - @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found a primary bean from beans 'dataSource' (OnBeanCondition)

   HibernateJpaAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean', 'javax.persistence.EntityManager', 'org.hibernate.engine.spi.SessionImplementor' (OnClassCondition)

   HibernateJpaConfiguration matched:
      - @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found a primary bean from beans 'dataSource' (OnBeanCondition)

   JdbcTemplateAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'javax.sql.DataSource', 'org.springframework.jdbc.core.JdbcTemplate' (OnClassCondition)
      - @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found a primary bean from beans 'dataSource' (OnBeanCondition)

   JdbcTemplateConfiguration matched:
      - @ConditionalOnBean (types: org.springframework.jdbc.core.JdbcOperations; SearchStrategy: all) did not find any beans (OnBeanCondition)

   JpaBaseConfiguration#entityManagerFactory matched:
      - @ConditionalOnBean (types: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,javax.persistence.EntityManagerFactory; SearchStrategy: all) did not find any beans (OnBeanCondition)

   JpaBaseConfiguration#entityManagerFactoryBuilder matched:
      - @ConditionalOnBean (types: org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; SearchStrategy: all) did not find any beans (OnBeanCondition)

   JpaBaseConfiguration#jpaVendorAdapter matched:
      - @ConditionalOnBean (types: org.springframework.orm.jpa.JpaVendorAdapter; SearchStrategy: all) did not find any beans (OnBeanCondition)

   JpaBaseConfiguration#transactionManager matched:
      - @ConditionalOnBean (types: org.springframework.transaction.PlatformTransactionManager; SearchStrategy: all) did not find any beans (OnBeanCondition)

   JpaRepositoriesAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.data.jpa.repository.JpaRepository' (OnClassCondition)
      - @ConditionalOnProperty (spring.data.jpa.repositories.enabled=true) matched (OnPropertyCondition)
      - @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found bean 'dataSource'; @ConditionalOnBean (types: org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean,org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension; SearchStrategy: all) did not find any beans (OnBeanCondition)

   LiquibaseAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'liquibase.integration.spring.SpringLiquibase', 'liquibase.change.DatabaseChange' (OnClassCondition)
      - @ConditionalOnProperty (spring.liquibase.enabled) matched (OnPropertyCondition)
      - AnyNestedCondition 1 matched 1 did not; NestedCondition on LiquibaseAutoConfiguration.LiquibaseDataSourceCondition.LiquibaseUrlCondition @ConditionalOnProperty (spring.liquibase.url) did not find property 'url'; NestedCondition on LiquibaseAutoConfiguration.LiquibaseDataSourceCondition.DataSourceBeanCondition @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found bean 'dataSource' (LiquibaseAutoConfiguration.LiquibaseDataSourceCondition)

   LiquibaseAutoConfiguration.LiquibaseConfiguration matched:
      - @ConditionalOnBean (types: liquibase.integration.spring.SpringLiquibase; SearchStrategy: all) did not find any beans (OnBeanCondition)

   LiquibaseAutoConfiguration.LiquibaseEntityManagerFactoryDependsOnPostProcessor matched:
      - @ConditionalOnClass found required class 'org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean' (OnClassCondition)
      - @ConditionalOnBean (types: org.springframework.orm.jpa.AbstractEntityManagerFactoryBean; SearchStrategy: all) found bean '&amp;entityManagerFactory' (OnBeanCondition)

   LiquibaseAutoConfiguration.LiquibaseJdbcOperationsDependsOnPostProcessor matched:
      - @ConditionalOnClass found required class 'org.springframework.jdbc.core.JdbcOperations' (OnClassCondition)
      - @ConditionalOnBean (types: org.springframework.jdbc.core.JdbcOperations; SearchStrategy: all) found bean 'jdbcTemplate' (OnBeanCondition)

   LiquibaseAutoConfiguration.LiquibaseNamedParameterJdbcOperationsDependsOnPostProcessor matched:
      - @ConditionalOnClass found required class 'org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations' (OnClassCondition)
      - @ConditionalOnBean (types: org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; SearchStrategy: all) found bean 'namedParameterJdbcTemplate' (OnBeanCondition)

   NamedParameterJdbcTemplateConfiguration matched:
      - @ConditionalOnBean (types: org.springframework.jdbc.core.JdbcTemplate; SearchStrategy: all) found a primary bean from beans 'jdbcTemplate'; @ConditionalOnBean (types: org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; SearchStrategy: all) did not find any beans (OnBeanCondition)

   NoOpCacheConfiguration matched:
      - Cache org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration NONE cache type (CacheCondition)

   TestDatabaseAutoConfiguration#embeddedDataSourceBeanFactoryPostProcessor matched:
      - @ConditionalOnProperty (spring.test.database.replace=ANY) matched (OnPropertyCondition)

   TestEntityManagerAutoConfiguration matched:
      - @ConditionalOnClass found required class 'javax.persistence.EntityManagerFactory' (OnClassCondition)

   TestEntityManagerAutoConfiguration#testEntityManager matched:
      - @ConditionalOnBean (types: org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; SearchStrategy: all) did not find any beans (OnBeanCondition)

   TransactionAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.transaction.PlatformTransactionManager' (OnClassCondition)

   TransactionAutoConfiguration#platformTransactionManagerCustomizers matched:
      - @ConditionalOnBean (types: org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers; SearchStrategy: all) did2019-11-01 20:35:10.294  INFO 6964 --- [           main] c.s.s.r.BankAccountRepositoryTest        : Started BankAccountRepositoryTest in 13.123 seconds (JVM running for 16.445)
 not find any beans (OnBeanCondition)

   TransactionAutoConfiguration.EnableTransactionManagementConfiguration matched:
      - @ConditionalOnBean (types: org.springframework.transaction.TransactionManager; SearchStrategy: all) found bean 'transactionManager'; @ConditionalOnBean (types: org.springframework.transaction.annotation.AbstractTransactionManagementConfiguration; SearchStrategy: all) did not find any beans (OnBeanCondition)

   TransactionAutoConfiguration.EnableTransactionManagementConfiguration.CglibAutoProxyConfiguration matched:
      - @ConditionalOnProperty (spring.aop.proxy-target-class=true) matched (OnPropertyCondition)

   TransactionAutoConfiguration.TransactionTemplateConfiguration matched:
      - @ConditionalOnBean (types: org.springframework.transaction.PlatformTransactionManager; SearchStrategy: all) found a primary bean from beans 'transactionManager' (OnBeanCondition)

   TransactionAutoConfiguration.TransactionTemplateConfiguration#transactionTemplate matched:
      - @ConditionalOnBean (types: org.springframework.transaction.support.TransactionOperations; SearchStrategy: all) did not find any beans (OnBeanCondition)


Negative matches:
-----------------

   CacheAutoConfiguration:
      Did not match:
         - @ConditionalOnBean (types: org.springframework.cache.interceptor.CacheAspectSupport; SearchStrategy: all) did not find any beans of type org.springframework.cache.interceptor.CacheAspectSupport (OnBeanCondition)
      Matched:
         - @ConditionalOnClass found required class 'org.springframework.cache.CacheManager' (OnClassCondition)

   CacheAutoConfiguration.CacheManagerEntityManagerFactoryDependsOnPostProcessor:
      Did not match:
         - Ancestor org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration did not match (ConditionEvaluationReport.AncestorsMatchedCondition)
      Matched:
         - @ConditionalOnClass found required class 'org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean' (OnClassCondition)

   CaffeineCacheConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'com.github.benmanes.caffeine.cache.Caffeine', 'org.springframework.cache.caffeine.CaffeineCacheManager' (OnClassCondition)

   CouchbaseCacheConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'com.couchbase.client.java.Bucket', 'com.couchbase.client.spring.cache.CouchbaseCacheManager' (OnClassCondition)

   DataSourceAutoConfiguration.EmbeddedDatabaseConfiguration:
      Did not match:
         - EmbeddedDataSource found supported pooled data source (DataSourceAutoConfiguration.EmbeddedDatabaseCondition)

   DataSourceConfiguration.Dbcp2:
      Did not match:
         - @ConditionalOnClass did not find required class 'org.apache.commons.dbcp2.BasicDataSource' (OnClassCondition)

   DataSourceConfiguration.Generic:
      Did not match:
         - @ConditionalOnProperty (spring.datasource.type) did not find property 'spring.datasource.type' (OnPropertyCondition)

   DataSourceConfiguration.Tomcat:
      Did not match:
         - @ConditionalOnClass did not find required class 'org.apache.tomcat.jdbc.pool.DataSource' (OnClassCondition)

   DataSourceJmxConfiguration:
      Did not match:
         - @ConditionalOnProperty (spring.jmx.enabled=true) found different value in property 'enabled' (OnPropertyCondition)

   DataSourcePoolMetadataProvidersConfiguration.CommonsDbcp2PoolDataSourceMetadataProviderConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'org.apache.commons.dbcp2.BasicDataSource' (OnClassCondition)

   DataSourcePoolMetadataProvidersConfiguration.TomcatDataSourcePoolMetadataProviderConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'org.apache.tomcat.jdbc.pool.DataSource' (OnClassCondition)

   DataSourceTransactionManagerAutoConfiguration.DataSourceTransactionManagerConfiguration#transactionManager:
      Did not match:
         - @ConditionalOnBean (types: org.springframework.transaction.PlatformTransactionManager; SearchStrategy: all) found beans of type 'org.springframework.transaction.PlatformTransactionManager' transactionManager (OnBeanCondition)

   EhCacheCacheConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'net.sf.ehcache.Cache', 'org.springframework.cache.ehcache.EhCacheCacheManager' (OnClassCondition)

   FlywayAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'org.flywaydb.core.Flyway' (OnClassCondition)

   GenericCacheConfiguration:
      Did not match:
         - Cache org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration unknown cache type (CacheCondition)

   HazelcastCacheConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'com.hazelcast.core.HazelcastInstance', 'com.hazelcast.spring.cache.HazelcastCacheManager' (OnClassCondition)

   InfinispanCacheConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManager' (OnClassCondition)

   JCacheCacheConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required classes 'javax.cache.Caching', 'org.springframework.cache.jcache.JCacheCacheManager' (OnClassCondition)

   JpaBaseConfiguration.JpaWebConfiguration:
      Did not match:
         - not a servlet web application (OnWebApplicationCondition)
      Matched:
         - @ConditionalOnClass found required class 'org.springframework.web.servlet.config.annotation.WebMvcConfigurer' (OnClassCondition)

   JpaRepositoriesAutoConfiguration#entityManagerFactoryBootstrapExecutorCustomizer:
      Did not match:
         - AnyNestedCondition 0 matched 2 did not; NestedCondition on JpaRepositoriesAutoConfiguration.BootstrapExecutorCondition.LazyBootstrapMode @ConditionalOnProperty (spring.data.jpa.repositories.bootstrap-mode=lazy) did not find property 'bootstrap-mode'; NestedCondition on JpaRepositoriesAutoConfiguration.BootstrapExecutorCondition.DeferredBootstrapMode @ConditionalOnProperty (spring.data.jpa.repositories.bootstrap-mode=deferred) did not find property 'bootstrap-mode' (JpaRepositoriesAutoConfiguration.BootstrapExecutorCondition)

   RedisCacheConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'org.springframework.data.redis.connection.RedisConnectionFactory' (OnClassCondition)

   SimpleCacheConfiguration:
      Did not match:
         - Cache org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration unknown cache type (CacheCondition)

   TestDatabaseAutoConfiguration#dataSource:
      Did not match:
         - @ConditionalOnProperty (spring.test.database.replace=AUTO_CONFIGURED) did not find property 'replace' (OnPropertyCondition)

   TransactionAutoConfiguration#transactionalOperator:
      Did not match:
         - @ConditionalOnBean (types: org.springframework.transaction.ReactiveTransactionManager; SearchStrategy: all) did not find any beans (OnBeanCondition)

   TransactionAutoConfiguration.EnableTransactionManagementConfiguration.JdkDynamicAutoProxyConfiguration:
      Did not match:
         - @ConditionalOnProperty (spring.aop.proxy-target-class=false) did not find property 'proxy-target-class' (OnPropertyCondition)


Exclusions:
-----------

    None


Unconditional classes:
----------------------

    org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration



2019-11-01 20:35:10.341 ERROR 6964 --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@68e5eea7] to prepare test instance [com.smehelper.shop.repository.BankAccountRepositoryTest@6497b078]

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.smehelper.shop.repository.BankAccountRepositoryTest': Unsatisfied dependency expressed through field 'bankAccountRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.smehelper.shop.repository.BankAccountRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:397) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1429) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119) ~[spring-test-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43) ~[spring-boot-test-autoconfigure-2.2.0.RELEASE.jar:2.2.0.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244) ~[spring-test-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:98) [spring-test-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassBasedTestDescriptor.java:337) [junit-jupiter-engine-5.5.2.jar:5.5.2]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor$$Lambda$285/195381554.execute(Unknown Source) [junit-jupiter-engine-5.5.2.jar:5.5.2]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:342) [junit-jupiter-engine-5.5.2.jar:5.5.2]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:337) [junit-jupiter-engine-5.5.2.jar:5.5.2]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor$$Lambda$284/298430307.accept(Unknown Source) [junit-jupiter-engine-5.5.2.jar:5.5.2]
    at java.util.stream.StreamSpliterators$WrappingSpliterator$$Lambda$89/1413653265.accept(Unknown Source) [na:1.8.0_40]
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) [na:1.8.0_40]
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) [na:1.8.0_40]
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374) [na:1.8.0_40]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512) [na:1.8.0_40]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502) [na:1.8.0_40]
    at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312) [na:1.8.0_40]
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:743) [na:1.8.0_40]
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:742) [na:1.8.0_40]
    at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580) [na:1.8.0_40]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:336) [junit-jupiter-engine-5.5.2.jar:5.5.2]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:259) [junit-jupiter-engine-5.5.2.jar:5.5.2]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:252) [junit-jupiter-engine-5.5.2.jar:5.5.2]
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor$$Lambda$278/896644936.get(Unknown Source) [junit-jupiter-engine-5.5.2.jar:5.5.2]
    at java.util.ArrayList.forEach(ArrayList.java:1249) [na:1.8.0_40]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask$$Lambda$174/1166151249.execute(Unknown Source) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask$$Lambda$173/1897115967.invoke(Unknown Source) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask$$Lambda$172/2095490653.execute(Unknown Source) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51) [junit-platform-engine-1.5.2.jar:1.5.2]
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229) [.cp/:na]
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197) [.cp/:na]
    at org.junit.platform.launcher.core.DefaultLauncher$$Lambda$141/120694604.accept(Unknown Source) [.cp/:na]
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211) [.cp/:na]
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191) [.cp/:na]
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137) [.cp/:na]
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463) [.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209) [.cp/:na]
</code></pre>
",https://stackoverflow.com/questions/58660690/i-am-trying-to-write-unit-testing-of-querydslrepositorysupport-in-spring-boot,"['spring-boot', 'spring-data-jpa', 'querydsl', 'junit5']",1195,False,1,1
Unit testing EF Core using in-memory database with an eager-loaded function,"<p>I am writing unit tests for my my Web API and cannot get the test to pass except by  removing the include (eager-loading from the method). I am using the in-memory database to provide the <code>dbcontext</code> and can't figure out why it is returning no data. Thanks in advance for any help or constructive criticism</p>

<p>This is the method I am trying to test.<br>
<strong>Note</strong>: it passes the test if I comment out the <code>.include</code> statements.</p>

<pre><code>    public async Task&lt;LibraryAsset&gt; GetAsset(int assetId)
    {
        var asset = await _context.LibraryAssets
            .Include(p =&gt; p.Photo)
            .Include(p =&gt; p.Category)
            .Include(a =&gt; a.AssetType)
            .Include(s =&gt; s.Status)
            .Include(s =&gt; s.Author)
            .FirstOrDefaultAsync(x =&gt; x.Id == assetId);

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

<p>This is the base <code>DbContext</code> using the inMemory DB:</p>

<pre><code>    public DataContext GetDbContext()
    {
        var builder = new DbContextOptionsBuilder&lt;DataContext&gt;();

        if (useSqlite)
        {
            // Use Sqlite DB.
            builder.UseSqlite(""DataSource=:memory:"", x =&gt; { });
        }
        else
        {
            // Use In-Memory DB.
            builder.UseInMemoryDatabase(Guid.NewGuid().ToString());
        }

        var DataContext = new DataContext(builder.Options);

        if (useSqlite)
        {
            // SQLite needs to open connection to the DB.
            // Not required for in-memory-database and MS SQL.
            DataContext.Database.OpenConnection();
        }

        DataContext.Database.EnsureCreated();

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

<p>This is the test:</p>

<pre><code>    [Fact]
    public async void GetAssetById_ExistingAsset_ReturnAsset()
    {
        using (var context = GetDbContext())
        {
            ILogger&lt;LibraryAssetService&gt; logger = new 
            NullLogger&lt;LibraryAssetService&gt;();

            var service = new LibraryAssetService(context, _logger);

            var asset = new LibraryAsset
            {
                Id = 40,
                NumberOfCopies = 20,
                Title = """",
                Year = 1992,
                Status = new Status { Id = 1 },
                AssetType = new AssetType { Id = 1 },
                Author = new Author { Id = 1 },
                Category = new Category { Id = 2 },
                Photo = new AssetPhoto { Id = 1 }
            };

            context.LibraryAssets.Attach(asset);

            context.Add(asset);
            context.SaveChanges();

            var actual = await service.GetAsset(40);
            Assert.Equal(40, actual.Id);
        }
    }
</code></pre>

<p>This is my first time writing unit tests and I am basically learning as I go. Please feel free to point out any other mistakes that you may have noticed as well.</p>
",https://stackoverflow.com/questions/57469212/unit-testing-ef-core-using-in-memory-database-with-an-eager-loaded-function,"['c#', 'unit-testing', 'asp.net-core', 'entity-framework-core', 'xunit']",9227,True,6,1
this.app.database is not a function when using firebase-server for unit testing,"<p>I'm trying to use firebase-server (<a href=""https://github.com/urish/firebase-server"" rel=""nofollow noreferrer"">https://github.com/urish/firebase-server</a>) for unit testing an express app that uses firebase. However, I'm starting out by just running the firebase-server on my own machine.</p>

<p>I've installed the library locally: <code>npm install --save-dev firebase-server</code></p>

<p>Then using the documentation for firebase-server, it says</p>

<blockquote>
  <p>If installed locally, use the following path to start the server: ./node_modules/.bin/firebase-server</p>
  
  <p>The following command will start a firebase server on port 5555:</p>
  
  <p><code>firebase-server -p 5555</code></p>
</blockquote>

<p>From the root of my project, I run <code>./node_modules/.bin/firebase-server -p 5555</code></p>

<p>The result is:</p>

<pre><code>/Users/user/Work/myproject/node_modules/firebase-server/dist/index.js:78
        this.app.database().goOffline();
                 ^

TypeError: this.app.database is not a function
    at new FirebaseServer (/Users/user/Work/myproject/node_modules/firebase-server/dist/index.js:78:18)
    at Object.&lt;anonymous&gt; (/Users/user/Work/myproject/node_modules/firebase-server/bin/firebase-server.js:85:17)
    at Object.cli.main (/Users/user/Work/myproject/node_modules/cli/cli.js:957:14)
    at Object.&lt;anonymous&gt; (/Users/user/Work/myproject/node_modules/firebase-server/bin/firebase-server.js:30:5)
    at Module._compile (module.js:649:30)
    at Object.Module._extensions..js (module.js:660:10)
    at Module.load (module.js:561:32)
    at tryModuleLoad (module.js:501:12)
    at Function.Module._load (module.js:493:3)
    at Function.Module.runMain (module.js:690:10)
</code></pre>

<p>Do I need to do some other configuration to get firebase-server to work via the cli?</p>

<p>Extra info:
I was able to get the server running if I install firebase-server globally, but still can't run it from my repo directory in <code>node_modules</code></p>

<p>package.json</p>

<pre><code>{
""name"": ""endpoints"",
""description"": ""my description"",
""version"": ""0.0.1"",
""private"": true,
""license"": ""Apache-2.0"",
""author"": ""JL"",
""repository"": {
    ""type"": ""git"",
    ""url"": ""https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git""
},
""engines"": {
    ""node"": ""&gt;=8.0.0""
},
""scripts"": {
    ""start"": ""node app.js"",
    ""test"": ""repo-tools test run --cmd ava -- -T 20s --verbose test/*.test.js""
},
""dependencies"": {
    ""@google-cloud/logging"": ""^4.2.0"",
    ""body-parser"": ""1.18.3"",
    ""express"": ""4.16.4"",
    ""firebase-admin"": ""~4.2.1"",
    ""safe-buffer"": ""5.1.2"",
    ""firebase"": ""5.8.3"",
    ""@firebase/app"": ""0.3.8"",
    ""@firebase/auth"": ""0.9.2"",
    ""@firebase/database"": ""0.3.12"",
    ""request-promise"": ""4.2.2""
},
""devDependencies"": {
    ""@google-cloud/nodejs-repo-tools"": ""^3.0.0"",
    ""ava"": ""0.25.0"",
    ""firebase-server"": ""^1.0.1"",
    ""husky"": ""^1.3.1"",
    ""proxyquire"": ""2.1.0"",
    ""sinon"": ""7.2.2"",
    ""supertest"": ""3.3.0""
},
""husky"": {
    ""hooks"": {
        ""pre-push"": ""npm test""
    }
}
}
</code></pre>
",https://stackoverflow.com/questions/54717381/this-app-database-is-not-a-function-when-using-firebase-server-for-unit-testing,"['firebase', 'unit-testing', 'firebase-realtime-database']",120,True,0,1
"Unit Testing of Remote API calls, How it works with JSON Objects","<p>In my web api, I have a method that call a service that return a deserialized  JSON object. I can't find a way for unit testing that is working for me.
the following is the code from the controller:</p>

<pre><code>     [RequireHttps]
     [Route(""api/GetItem/{id}"")]
     public class GetItemController : ControllerBase
    {
     private static HttpClient client = new HttpClient();
     private Item item = new Item();

     [RequireHttps]
     [Route(""api/GetItem/{id}"")]
     public Item GetItem(string name, string password)
     {
        string url = ""https://localhost:5001/"";


       string uri = url + ""api/item/"" + name+ ""/"" +  password ""/""  ;
       client.DefaultRequestHeaders.Accept.Add(new 
       MediaTypeWithQualityHeaderValue(""application/json""));
       HttpResponseMessage Res = client.GetAsync(uri).Result;              

            if (Res.IsSuccessStatusCode)
            {

                var MemResponse = Res.Content.ReadAsStringAsync().Result;

                member = JsonConvert.DeserializeObject&lt;Item&gt; 
                (MemResponse);

            }

            return Ok(item);
        }
    }
</code></pre>

<p>The unit test I wrote suppose to check the wrong user name and password, but when running the test it just gray out and never runs </p>

<pre><code>  [TestMethod]
   public void GetItemWithWrongPassword()
   {      
    var username = ""Hellow"";
    var pass = ""There"";
    var controller = new GetItemController();
    var response = controller.GetItem(username, pass);
    var s = response.ToString();
    Assert.AreEqual(s, ""System.Web.Http.Results.NotFoundResult"");
}
</code></pre>

<p>what I'm doing wrong?
Later on I want to test if the connection to the remote API.</p>
",https://stackoverflow.com/questions/54750391/unit-testing-of-remote-api-calls-how-it-works-with-json-objects,"['json', 'unit-testing', 'asp.net-web-api', 'controller', 'nunit']",141,False,0,1
"Angular, unit testing a component that creates a service via an interface","<p>Given this component that creates a service locally</p>

<pre><code>@Component({
    &lt;removed for clarity&gt;
    providers: [
        { provide: 'IMyService', useClass: MyService },
    ]
})
export class MyComponent implements OnInit, OnDestroy, AfterViewInit
{
    constructor(private data: IMyService){}
}
</code></pre>

<p>I've been trying to supply the service in the unit test, something like this</p>

<pre><code>beforeEach(async(() =&gt;
{
    TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [
            { provide: 'IMyService', useClass: MockMyService },
        ]
    })
    /*
        .overrideProvider('IMyService', { useValue: MockMyService })
        .overrideComponent(MyComponent, {
        set: {
            providers: [
                { provide: 'IMyService', useClass: MockMyService }
            ]
        }
    })
   */
.compileComponents();
</code></pre>

<p>The commented out bits being things I've tried.</p>

<p>But I constantly get this message</p>

<pre><code>Failed: Can't resolve all parameters for MyComponent: (?)
</code></pre>

<p>What am I missing here?</p>
",https://stackoverflow.com/questions/57817610/angular-unit-testing-a-component-that-creates-a-service-via-an-interface,"['angular', 'angular-unit-test']",1036,True,0,1
Spring Boot Unit testing endpoint NullPointerException - and how to reach 100% coverage,"<p>I'm new to Spring Boot testing and I'm trying to test and endpoint. Following tutorials, I did this:</p>

<pre><code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = SpringMiddlewareApplication.class)
@ComponentScan(""com.springmiddleware"")
@SpringBootTest
public class SpringMiddlewareApplicationTests {

private MockMvc mvc;

@Test
public void returnsString() {
    try {
        this.mvc.perform(get(""/home"")).andExpect(status().isOk())
        .andExpect(content().string(containsString(""You are in the home page"")));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code></pre>

<p>If I run the test it is passed, but the following error shows in the console:</p>

<pre><code>java.lang.NullPointerException
at com.example.demo.SpringMiddlewareApplicationTests.returnsString
</code></pre>

<p>The RestController class is the following:</p>

<pre><code>@RestController
public class FirstController {


    /**
     * Welcome page
     * 
     * @return String
     */
    @GetMapping(""/home"")
    public String homePage() {
        return ""You are in the home page"";
    }
</code></pre>

<p>What causes the error?<br>
Also, even if this test passes, running Jacoco I do not have coverage for the method ""homePage"". How do I achieve this?</p>
",https://stackoverflow.com/questions/55281169/spring-boot-unit-testing-endpoint-nullpointerexception-and-how-to-reach-100-c,"['spring-boot', 'testing', 'junit', 'jacoco', 'jacoco-maven-plugin']",425,True,0,1
How to mock fake file size in bytes array in unit testing,"<p>Here I have code which copies the document to specific loacation for that I have code which creates fake file as below.</p>

<pre><code>private static Mock&lt;IFormFile&gt; GetMockFormFile()
{
      var fileMock = new Mock&lt;IFormFile&gt;();
      var fileStreamProviderMock = new Mock&lt;IFileStreamProvider&gt;();
      var contentTypes = ""text/plain"";
      var content = ""Fake File"";
      var fileName = ""Test.txt"";
      var disk = new MemoryStream();
      var writers = new StreamWriter(disk);
      writers.Write(content);
      writers.Flush();
      disk.Position = 0;
      fileMock.Setup(_ =&gt; _.OpenReadStream()).Returns(disk);
      fileMock.Setup(_ =&gt; _.FileName).Returns(fileName);
      fileMock.Setup(_ =&gt; _.Length).Returns(disk.Length);
      fileMock.Setup(_ =&gt; _.ContentType).Returns(contentTypes);
      fileMock.Setup(_ =&gt; _.ContentDisposition).Returns($""form-data;name='file';filename ='{fileName}'"");
      fileStreamProviderMock.Setup(_ =&gt; _.Create(It.IsAny&lt;string&gt;())).Returns(disk);
      fileStreamProviderMock.Setup(_ =&gt; _.Open(It.IsAny&lt;string&gt;())).Returns(disk);
      fileMock.Setup(_ =&gt; _.CopyToAsync(disk, It.IsAny&lt;CancellationToken&gt;())).Returns(Task.CompletedTask);
      fileMock.Verify();
      return fileMock;
}
</code></pre>

<p>I am passing this fake file to controller like</p>

<pre><code>[Fact]
public async sample()
{
    var formFile = GetMockFormFile();
    var file = formFile.Object;
    var SavedFile = new AttachmentMetadata
    {
        Id = 4231,
        DocumentName = file.FileName,
        DocumentType = file.ContentType,
        CreatedDateTime = dateTime,
        ModifiedDateTime = dateTime
    };
    var viewModel = new AttachmentViewModel()
    {
        File = new List&lt;IFormFile&gt; { file }
    };

    await controller.AddAttachment(viewModel);
    fileStreamProviderMock.Verify(_ =&gt; _.Create(@""C:\TestFolder\Test.txt""));
    formFile.Verify(_ =&gt; _.CopyToAsync(It.IsAny&lt;Stream&gt;(), It.IsAny&lt;CancellationToken&gt;()));
}
</code></pre>

<p>and inside my controller i have some code as like</p>

<pre><code>foreach (var file in model.File)
  {
    using (var ms = new MemoryStream())
       {
            file.CopyTo(ms);
            fileBytes = ms.ToArray();
       } 
  ----
  ----
}
</code></pre>

<p>which should return the fileBytes something except 0, currently I am getting fileBytes as 0 which cause issues in further code execution.
So is there any other way where I can mock this fake bytes size?</p>
",https://stackoverflow.com/questions/57325390/how-to-mock-fake-file-size-in-bytes-array-in-unit-testing,"['c#', 'unit-testing', '.net-core']",1399,False,0,0
PHP Unit Testing - Test a feature with a service instance inside it,"<p>I am learning the art of testing and need some of your help. I have a feature (legacy code) that I need to test, this feature receives some data as parameters, save it temporally in the database and sends to an external API. If the api response is 200 then updates the data in the table to persist it definitely, otherwise it deletes it.</p>

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

<pre><code>public function sendAssignments(Challenge $challenge, int $reportType)
{
    $reportModel      = new Report($challenge, $reportType);
    $pointsList       = $this-&gt;calculateAssignments($challenge, $reportType);
    $pharmsToSend     = $pointsList['pharmsCollection'];
    $pointsArray      = $pointsList['pointsArray'];

    $savedAt          = Date('Y-m-d H:i:s');
    $symfonyService   = new SymfonyService();
    $requestUid       = \uniqid('AS-', false);

    $sentAt           = Date('Y-m-d H:i:s');
    $reportModel-&gt;persistReportAssignments($pharmsToSend, $savedAt, $sentAt, false);
    $symfonyResult    = $symfonyService-&gt;sendReportPoints(
        $requestUid, 
        $challenge-&gt;challenge_id, 
        $pointsArray
    );

    if ($symfonyResult-&gt;code == ""200"") {
        // Actualizamos los datos
        $reportModel-&gt;persistReportAssignments($pharmsToSend, $savedAt, $sentAt, true);
        FlashMessage::addSuccess('Se han asignado los puntos del reporte.', 'Asignación correcta');
    } else {
        $reportModel-&gt;deleteFailedAssignmentsFromDatabase($savedAt);
        FlashMessage::addError($symfonyResult-&gt;msg, 'Error '.$symfonyResult-&gt;code.' - No se han asignado los puntos');
    }

    if ($reportType == Report::REPORT_CONNECTED) {
        return redirect()-&gt;route('reports.showConnectedReport', ['challenge'=&gt;$challenge]);
    } else if ($reportType == Report::REPORT_MANUAL) {
        return redirect()-&gt;route('reports.showManualReport', ['challenge'=&gt;$challenge]);
    }
}
</code></pre>

<p>I am testing the feature, not the API call, so I wanna mock the SymfonyService class, for this I has written a new class:</p>

<pre><code>class SymfonyServiceMock
{
    public function sendReportPoints()
    {
        return [""operation""=&gt;""ok"", ""code"" =&gt; 200];
    }
}
</code></pre>

<p>But the problem is that SymfonyService is being instantiated inside the feature, so I cannot use the SymfonyServiceMock class to simulate the API call. And here is my doubt, may I have to refactor the feature in order to pass the SymfonyService to it? Is this the correct approach?</p>

<p>I mean some refactor like this one:</p>

<pre><code>public function sendAssignments(Challenge $challenge, int $reportType, SymfonyService $symfonyService)
{
    // The rest of the code here, but without instantiating SymfonyService
}
</code></pre>

<p>If you have another better idea about how it would be the best way to test it (following SOLID principles of course) I would be glad to know.</p>

<p>Thanks a lot in advance</p>

<p><strong>EDIT:</strong>
I had this idea, I have registered the SymfonyService on the AppServiceContainer, and now I inject the SymfonyService on the controller so I can refactor like this:</p>

<pre><code>public function sendAssignments(Challenge $challenge, int $reportType)
{
    $this-&gt;executeSendAssignmentsOperation($challenge, $reportType);

    if ($reportType == Report::REPORT_CONNECTED) {
        return redirect()-&gt;route('reports.showConnectedReport', ['challenge'=&gt;$challenge]);
    } else if ($reportType == Report::REPORT_MANUAL) {
        return redirect()-&gt;route('reports.showManualReport', ['challenge'=&gt;$challenge]);
    }
}

public function executeSendAssignmentsOperation(Challenge $challenge, int $reportType)
{
    $reportModel      = new Report($challenge, $reportType);
    $pointsList       = $this-&gt;calculateAssignments($challenge, $reportType);
    $pharmsToSend     = $pointsList['pharmsCollection'];
    $pointsArray      = $pointsList['pointsArray'];

    $savedAt          = Date('Y-m-d H:i:s');
    $sentAt           = Date('Y-m-d H:i:s');

    $reportModel-&gt;persistReportAssignments($pharmsToSend, $savedAt, $sentAt, false);
    $symfonyResult    = $this-&gt;_symfonyService-&gt;sendReportPoints(
        $challenge, 
        $pointsArray,
        $reportType
    );

    $sentAt           = Date('Y-m-d H:i:s');

    if ($symfonyResult-&gt;code == ""200"") {
        // Actualizamos los datos
        $reportModel-&gt;persistReportAssignments($pharmsToSend, $savedAt, $sentAt, true);
        FlashMessage::addSuccess('Se han asignado los puntos del reporte.', 'Asignación correcta');
    } else {
        $reportModel-&gt;deleteFailedAssignmentsFromDatabase($savedAt);
        FlashMessage::addError($symfonyResult-&gt;msg, 'Error '.$symfonyResult-&gt;code.' - No se han asignado los puntos');
    }
}
</code></pre>

<p>With this refactor now I can write the test. But, I am still wondering if this is the correct approach for the problem. If not, could you please explain why?</p>
",https://stackoverflow.com/questions/58377860/php-unit-testing-test-a-feature-with-a-service-instance-inside-it,"['php', 'phpunit']",127,False,0,1
Can I downgrade from .net 2.1 to 2.0 for unit testing purposes,"<p>I am looking for some advice please. I have built a web app  in visual studio community edition which leverages on .NET 2.1. 
I want to start unit testing but when referencing the main project in the unit test project I get the error ""NET Framework 4.6.1 can not reference a project that targets 2.1. etc. etc."" 
I understand that .NET Framework will not support .NET Standard 2.1 or any other later version anymore. 
Would you have any advice on whether it would make sense to downgrade to .NET Standard 2.0 (assuming that is possible and I apologise if the question is stupid) or do I risk messing up the entire thing and therefore I should explore alternatives (for which I am happy to do my own research). 
Thanks in advance</p>
",https://stackoverflow.com/questions/55986778/can-i-downgrade-from-net-2-1-to-2-0-for-unit-testing-purposes,"['.net', 'unit-testing', 'asp.net-core-mvc']",183,True,0,1
Providing/Injecting third party service to component while angular component unit testing,"<p>I have just started with Angular Unit testing, <code>LoginComponent</code> is dependent on third party module's (Fuse) service <code>FuseConfigService</code>. </p>

<p>Here is how <code>FuseConfigService</code> look like</p>

<pre><code>@Injectable({
    providedIn: 'root'
})
export class FuseConfigService
{
    private _configSubject: BehaviorSubject&lt;any&gt;;
    private readonly _defaultConfig: any;

    /**
     * Constructor
     *
     * @param {Platform} _platform
     * @param {Router} _router
     * @param _config
     */
    constructor(
        private _platform: Platform,
        private _router: Router,
        @Inject(FUSE_CONFIG) private _config
    )
    {
</code></pre>

<p>And here is how <code>LoginComponent</code> <code>constructor</code> look like</p>

<pre><code>constructor(
        private fuseConfig: FuseConfigService,
        private formBuilder: FormBuilder,
        private router: Router,
        private authenticationService: AuthService,
        private route: ActivatedRoute,
        private snackBar: MatSnackBar,
        private fuseNavigationService: FuseNavigationService,
        private pbiService: PbiService,
        private translateService: TranslateService
    ) {
        this.incorrectCredentials = false;
        this.loginFormErrors = {
            email: {},
            password: {},
        };
    }
</code></pre>

<p>I don't know how to configure testing module using TestBed, as it is throwing error like</p>

<pre><code>Error: StaticInjectorError(DynamicTestModule)[FuseConfigService -&gt; InjectionToken fuseCustomConfig]: 
  StaticInjectorError(Platform: core)[FuseConfigService -&gt; InjectionToken fuseCustomConfig]: 
    NullInjectorError: No provider for InjectionToken fuseCustomConfig!
</code></pre>

<p>This is what I am trying</p>

<pre><code>TestBed.configureTestingModule({
            declarations: [LoginComponent],
            imports: [FormsModule, ReactiveFormsModule, MatFormFieldModule,
                MatInputModule,
                MatCheckboxModule,
                MatSnackBarModule,
                MatButtonModule,
                MatRadioModule],
            providers: [
                FuseConfigService,
                { provide: Router, useClass: class { navigate = jasmine.createSpy(""navigate""); } },
                FuseNavigationService
            ]
        });
</code></pre>

<p>Any help will be appreciated.</p>
",https://stackoverflow.com/questions/57524902/providing-injecting-third-party-service-to-component-while-angular-component-uni,"['angular', 'unit-testing', 'dependency-injection', 'karma-jasmine']",1505,True,-1,1
Unit testing presence of mat-error after touching and untouching mat-input,"<p>How would I test that the mat-error is present in the DOM when I haven't touched the input, and also when I have touched and untouched the input without entering any text?</p>

<p>I am testing using Jest</p>

<p><strong>HTML</strong></p>

<pre><code>&lt;mat-form-field&gt;
  &lt;input matInput formControlName=""someInput""/&gt;
  &lt;mat-error id=""my_error""&gt;* required&lt;/mat-error&gt;
&lt;/mat-form-field&gt;
</code></pre>

<p><strong>Test</strong></p>

<pre><code>it('Should not show error', () =&gt; {
  const myEl = fixture.debugElement.query(By.css('#my_error'));

  expect(myEl).toBeUndefined();
});

it('Should show error', () =&gt; {
  const myEl = fixture.debugElement.query(By.css('#my_error'));

 // code to touch and untouch the element

  expect(myEl).not.toBeUndefined();
});
</code></pre>
",https://stackoverflow.com/questions/54218755/unit-testing-presence-of-mat-error-after-touching-and-untouching-mat-input,"['html', 'angular', 'typescript', 'unit-testing', 'dom']",1045,False,1,1
RxJS Unit Testing: what&#39;s the functionality of the callback passed to TestScheduler,"<p>I'm trying to use <code>TestScheduler</code> to write unit test for my RxJs functions. There are many posts related to it, and I'm following this post : <a href=""https://medium.com/@kevinkreuzer/marble-testing-with-rxjs-testing-utils-3ae36ac3346a"" rel=""nofollow noreferrer"">https://medium.com/@kevinkreuzer/marble-testing-with-rxjs-testing-utils-3ae36ac3346a</a></p>

<p>There is one confusing point for the following part: </p>

<p><strong><a href=""https://i.stack.imgur.com/E3eYx.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/E3eYx.png"" alt=""strong text""></a></strong></p>

<p>I don't understand why we need to pass the callback function into <code>TestScheduler</code> constructor. In the post, it mentioned that it is <code>assertDeppEqual function which tells the TestScheduler how to compare values. The methods used to compare values depends on your testing framework.</code></p>

<p>But this explanation is not clear for me. I don't figure out what's the relationship between this function and the  actual test logic we write, for example the following case:</p>

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

<p>in the above case, it assert that <code>expectObservable().toBe()</code>. what's the relationship between them? </p>
",https://stackoverflow.com/questions/58306240/rxjs-unit-testing-whats-the-functionality-of-the-callback-passed-to-testschedu,"['unit-testing', 'rxjs']",461,True,0,1
Unit testing a method in which I am doing a dependency injection,"<p>I have a terminal app with two classes: Todo and TodoApp. The method below lives in TodoApp, I would like to unit test this method and keep it isolated in my test. Since I am doing a dependency injection within the method, how could I mock that? (@todos is an empty array in TodoApp initialize)     </p>

<pre><code> def add(task, day, todo = Todo)
    @todos.push(todo.new(task, day))
    return ""#{task} was added to your todos""
 end
</code></pre>

<p>Thanks in advance for your help.</p>
",https://stackoverflow.com/questions/54971445/unit-testing-a-method-in-which-i-am-doing-a-dependency-injection,"['ruby', 'unit-testing', 'rspec']",140,True,0,1
Unit Testing: Null Reference Exception when doing FindAll on List with Predicate,"<p>I have a method in an abstract class FakeEntityBaseRepository, called FindBy with the following code: </p>

<pre><code>    public IEnumerable&lt;T&gt; FindBy(Expression&lt;Func&lt;T, bool&gt;&gt; predicate, params string[] includeProperties)
    {
        Func&lt;T, bool&gt; func = predicate.Compile();
        Predicate&lt;T&gt; pred = func.Invoke;

        var result = list.FindAll(pred);

        if (result == null)
        {
            list.Clear();
            return list;
        }

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

<p>I have several Unit Tests that are failing after updating the code above to what it is, an example test would be written as follows: </p>

<pre><code>[Test]
        public void GetSequencedParts_WhenCalled_ReturnsAllSequencedParts()
        {
            // Arrange
            PartController partController = GetController(null, null, null, null);

            // Act
            OkObjectResult result = (OkObjectResult)partController.GetSequencedParts();

            // Assert
            Assert.IsInstanceOf&lt;List&lt;PartViewModel&gt;&gt;(result.Value);
            List&lt;PartViewModel&gt; PartList = (List&lt;PartViewModel&gt;)result.Value;
            Assert.AreEqual(1, PartList.Count);
        }
</code></pre>

<p>The Controller Method Looks like this: </p>

<pre><code>    [HttpGet(""sequenced"")]
    public IActionResult GetSequencedParts()
    {
        try
        {
            IEnumerable&lt;Part&gt; parts = partRepository
                .FindBy(x =&gt; x.Sequences.Count &gt; 0, ""SomeString"", ""SomeString2"")
                .ToList();

            IEnumerable&lt;PartViewModel&gt; partVMs = Mapper.Map&lt;IEnumerable&lt;Part&gt;, IEnumerable&lt;PartViewModel&gt;&gt;(parts);
            return new OkObjectResult(partVMs);
        }
        catch (Exception ex)
        {
            return new BadRequestObjectResult(ex);
        }
    }
</code></pre>

<p>I'm receiving an exception for this particular method. I should mention that the FindBy method works for other unit tests but is failing on these few.</p>

<p>the exception is a type of NullReferenceException and the following stack trace message is attached: </p>

<pre><code>at lambda_method(Closure , Part )
   at System.Collections.Generic.List`1.FindAll(Predicate`1 match)
   at API.Tests.Fakes.FakeEntityBaseRepository`1.FindBy(Expression`1 predicate, String[] includeProperties) in C:\Jake_Projects\API\JakeUnitTestsRecovery\API.Tests\Fakes\FakeRepositories\FakeEntityBaseRepository.cs:line 82
   at API.Controllers.PartController.GetSequencedParts() in C:\Jake_Projects\API\JakeUnitTestsRecovery\API\Controllers\PartController.cs:line 68
</code></pre>

<p>Thank you for your time,</p>

<p>Jake</p>
",https://stackoverflow.com/questions/57660767/unit-testing-null-reference-exception-when-doing-findall-on-list-with-predicate,"['c#', 'unit-testing', 'nunit', 'nullreferenceexception', 'predicate']",32,False,0,0
Xcode 11 : iOS 13 specifically no longer triggers `viewDidAppear` when unit testing,"<p>Specifically this used to pass when testing using iOS 12:</p>

<pre><code>let viewController = ViewController()
let _ = viewController.view
let window = UIWindow(frame: UIScreen.main.bounds)
window.layer.speed = 10
viewController.modalPresentationStyle = .fullScreen
viewController.beginAppearanceTransition(true, animated: false)
window.rootViewController = viewController
window.makeKeyAndVisible()
viewController.endAppearanceTransition()
...
XCTAssert(vc.viewDidAppearCalled == true)
</code></pre>

<p>No longer passes.
The ViewController's <code>viewDidLoad</code> and <code>viewWillAppear</code> still gets called.</p>

<p>Any ideas what's going on?</p>

<p>Full example found here: <a href=""https://github.com/nickm01/Test13ViewWillAppear"" rel=""nofollow noreferrer"">https://github.com/nickm01/Test13ViewWillAppear</a></p>
",https://stackoverflow.com/questions/59366231/xcode-11-ios-13-specifically-no-longer-triggers-viewdidappear-when-unit-test,"['swift', 'xcode', 'unit-testing', 'uiviewcontroller', 'viewcontroller']",367,True,0,1
Mapper already initialized issue when using Automapper and xUnit for unit testing,"<p>I am a bit new to unit testing with xUnit, and I have some problems with AutoMapper. I am getting the <strong>Mapper already initialized</strong> issue.</p>

<p>I am using Automapper 8.0.0., ASP.NET Core 2.2 and xUnit 2.4.1.</p>

<p>I am writing unit tests for my controllers.
I have unit tests in 3 different classes. Each class looks basically like this:</p>

<pre><code>/* Constructor */
public ControllerGetTests()
{
    /// Initialize AutoMapper
    AutoMapper.Mapper.Reset();
    MapperConfig.RegisterMaps();

    /* Some mocking code here using Moq */

    _controller = new MyController();
}


[Fact]
public async void Get_WhenCalled_ReturnsOkResult()
{
    // Act
    var okResult = await _controller.Get();

    // Assert
    Assert.IsType&lt;OkObjectResult&gt;(okResult);
}

/* etc. */
</code></pre>

<p>All three classes are similar and are basic tests for controllers.
All controllers are using AutoMapper.
I am using the same static class MapperConfig to register my mappings:</p>

<pre><code>public static class MapperConfig
{
    public static void RegisterMaps()
    {
        AutoMapper.Mapper.Initialize(config =&gt;
        {
            config.CreateMap&lt;SomeClass, SomeClassViewModel&gt;();    
            config.CreateMap&lt;SomeClassViewModel, SomeClass&gt;();

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

<p>I call this method in the constructor of each of the 3 test classes.
Before calling it, I call the Mapper.Reset() - some answers here suggest that:
<a href=""https://stackoverflow.com/questions/47241708/automapper-mapper-already-initialized-error"">Automapper - Mapper already initialized error</a></p>

<p>In the Test Explorer in VS when I select one test class and choose ""Run selected tests"", they all pass. However, when I select the main ""Run all"", some tests fail with the message <strong>Mapper already initialized</strong>. And each time it is different tests in different classes that fail. </p>

<p>I assume that different threads are created for different methods, but they are all trying to initialize the same mapper instance which throws an error.</p>

<p>However, I am not sure where am I supposed to call the initialization in one (and only one) place and have that same initialization be used for all my test classes (like I do in Startup.cs Configure method).</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/55616503/mapper-already-initialized-issue-when-using-automapper-and-xunit-for-unit-testin,"['c#', 'unit-testing', '.net-core', 'automapper', 'xunit']",2138,True,0,2
Unit testing a function which consumes request from django rest api view,"<p>I'm not sure what's the proper way to test functions which are used inside views/permission classes.</p>

<p>This is the payload of my request:</p>

<pre><code>{""name"": ""John""}
</code></pre>

<p>And this is the function I want to test:</p>

<pre class=""lang-py prettyprint-override""><code>def get_name(request):
    return request.data['name']
</code></pre>

<p>This is the view that will be using the function:</p>

<pre class=""lang-py prettyprint-override""><code>class SomeView(APIView):
    def get(self, request):
        name = get_name(request=request)
        return Response(status=200)
</code></pre>

<p>How should I create a fixture to test the <code>get_name</code> function? I've tried this:</p>

<pre class=""lang-py prettyprint-override""><code>@pytest.fixture
def request_fixture()
    factory = APIRequestFactory()
    return factory.get(
        path='',
        data={""name"": ""John""},
        format='json')

def test_get_name(request_fixture):
    assert get_name(request=request_fixture) == ""John""
</code></pre>

<p>But I'm getting an error:
<code>AttributeError: 'WSGIRequest' object has no attribute data</code>.</p>

<p>One workaround seems to be decoding the <code>body</code> attribute:</p>

<pre class=""lang-py prettyprint-override""><code>def get_name(request):
    data = json.loads(request.body.decode('utf-8'))
    return data['name']
</code></pre>

<p>But it doesn't feel like the right way to do this and I guess I'm missing something about the <code>WSGIRequest</code> class. Can someone explain to me how it should be tested? It would be great if I could use the same fixture to test the view too.</p>
",https://stackoverflow.com/questions/58411309/unit-testing-a-function-which-consumes-request-from-django-rest-api-view,"['python', 'django', 'rest', 'unit-testing', 'django-rest-framework']",586,False,0,1
Where is FrameworkUap10 used in VSTest.Console.exe for Win Universal Apps Unit testing,"<p>I've been tasked with adding Unit Testing to our WinUA. The developer said he added a new unit test for UWP project to his solution and I'm to add calling this at build time. He wasn't sure how to do it and pointed me to this article: <a href=""https://learn.microsoft.com/en-us/windows/uwp/packaging/auto-build-package-uwp-apps"" rel=""nofollow noreferrer"">Set up automated builds for your UWP app</a></p>

<p>I've added a ""Visual Studio Test"" step and set the following:</p>

<pre><code>Test Assembly = **\*.UnitTests.build.appxrecipe
Other console options = /framework:FrameworkUap10
</code></pre>

<p>Running it throws the following error:</p>

<blockquote>
  <p>[error]Error: Invalid .Net Framework version:FrameworkUap10. Supported .Net Framework versions are Framework35, Framework40 and Framework45.</p>
</blockquote>

<p>If I remove the invalid framework, no error is thrown but also no tests are run. </p>

<p>I cannot find any information on the /framework:FrameworkUap10 option. Searched MS, here and web and all that comes up is its use in this article... nothing about installing it on the build machine.</p>

<p>How does one install FrameworkUap10?</p>
",https://stackoverflow.com/questions/54203900/where-is-frameworkuap10-used-in-vstest-console-exe-for-win-universal-apps-unit-t,"['testing', 'tfs', 'uwp']",216,True,0,1
How to provide injected values while unit testing a component in angular5+,"<p>I am writing tests for a component that is initialized dynamically as a modal (entryComponent). Inputs for this component are retrieved via injector.
I need a way to provide these inputs in my component creation step in beforeEach.</p>

<pre><code>this.modalService.create({
    component: sampleComponent, inputs: {
        test: 'testMsg'
    }
});

</code></pre>

<p>SampleComponent:</p>

<pre><code>@Modal()
@Component({
    selector: 'sample-component',
    templateUrl: './sample.component.html',
    styleUrls: ['./sample.component.scss']
})
export class SampleComponent implements OnInit {
    test: string;

    constructor(private injector: Injector) {
    }

    ngOnInit() {
        this.test= this.injector.get('test');
    }
}

</code></pre>

<p>Test for sampleComponent:</p>

<pre><code>describe('sampleComponent', () =&gt; {
    let component: SampleComponent;
    let fixture: ComponentFixture&lt;SampleComponent&gt;;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [SampleComponent],
            imports: [
                ModalModule,
                BrowserAnimationsModule,
            ],
            providers: [
                ModalService,
            ]
        })
        .compileComponents();
        })
    );
    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(SampleComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        component.ngOnInit();
    });
    it('should create', () =&gt; {
        expect(component).toBeTruthy();
    });
});
</code></pre>

<p>test fails with:
 Error: StaticInjectorError(DynamicTestModule)[test]:
      StaticInjectorError(Platform: core)[test]:
        NullInjectorError: No provider for test!</p>

<p>How do provide value for 'test' in this case?</p>
",https://stackoverflow.com/questions/54240356/how-to-provide-injected-values-while-unit-testing-a-component-in-angular5,"['javascript', 'unit-testing', 'angular5']",30,False,0,1
Issue in dependency injection while implementing Unit testing in ASP.NET MVC 6,"<p>My unit testing code is </p>

<pre><code>[TestClass]
public class ProjectControllerTest
{
    Mock&lt;IProjectService&gt; addressRepositoryMock = new Mock&lt;IProjectService&gt;();
    ProjectController controller;

    [TestInitialize]
    public void TestInit()
    {
        controller = new ProjectController(addressRepositoryMock.Object);
    }

    [TestMethod]
    public void TestMethod1()
    {
        var response = controller.GetOverrides(1) as HttpResponseMessage;
    }
}
</code></pre>

<p>My controller code is:</p>

<pre><code>[Route(""GetOverrides"")]
[HttpGet]
public HttpResponseMessage GetOverrides(int Project_Id)
{
        List&lt;OverridesDto&gt; overrides = new List&lt;OverridesDto&gt;();

        try
        {
            overrides = projectService.GetOverrides(Project_Id);
        }
        catch (Exception ex)
        {
            Log.Logger.Error(ex, ""Exception:{Ex}"", null);
            ThrowHttpExceptionOnError(ex.ToString());
        }

        return Request.CreateResponse(HttpStatusCode.OK, overrides);
 }
</code></pre>

<p>I am able to hit method <code>GetOverrides</code> in controller from  unit testing project in debug mode but the problem is I can not hit BAL method <code>projectService.GetOverrides(Project_Id);</code> which is returning null</p>

<p>Please help me out with the above issue.</p>
",https://stackoverflow.com/questions/58760962/issue-in-dependency-injection-while-implementing-unit-testing-in-asp-net-mvc-6,"['c#', 'asp.net-mvc', 'testing']",41,False,0,0
Xcode unit testing session exited error while running the unit test cases,"<p>I am executing the unit test cases using <code>XCTest</code> but the test cases are failed without running the method call.
The below error is displayed in the test log.</p>

<blockquote>
  <p>Test session exited(45) without completing.</p>
</blockquote>

<p><strong>Below are the log file contents.</strong></p>

<pre><code>10:13:51.477 Xcode[27399:424996] &lt;IDETestOperationCoordinator: 0x7fec86f3a2d0&gt;: parseConsoleOutputFromOriginalOutput: called, 78 bytes written out to StandardOutputAndStandardError
10:13:51.581 Xcode[27399:463189] Lost connection to the test daemon.
10:13:51.581 Xcode[27399:462510] Closing socket 69 to testmanagerd for Sim iPhone 5
10:13:51.582 Xcode[27399:462503] Closing socket 58 to testmanagerd for Sim iPhone 5
10:13:51.585 Xcode[27399:424996] Got death notice for pid 31596, removing from SimulatorSessionMap
10:13:51.585 Xcode[27399:424996] Checking to see if pid 31476 is valid: kill(pid, 0) = 0 (YES, it's still running)
10:13:51.585 Xcode[27399:424996] &lt;IDETestOperationCoordinator: 0x7fec86f3a2d0&gt;: parseConsoleOutputFromOriginalOutput: called, 0 bytes written out to StandardOutputAndStandardError
10:13:51.585 Xcode[27399:424996] &lt;IDETestOperationCoordinator: 0x7fec86f3a2d0&gt; is flushing delegate queue, count: 1
10:13:51.592 Xcode[27399:424996] Launch session LaunchSessionClaim_0x7fec86ee5630 relinquised claim on simulator 8678C2A5-960D-4E64-A1CC-9F485D7A1DFC
10:13:51.592 Xcode[27399:424996] Launch session LaunchSessionClaim_0x7fec86ee5630 relinquised claim on simulator 8678C2A5-960D-4E64-A1CC-9F485D7A1DFC
10:13:51.840 Xcode[27399:424996] &lt;IDETestOperationCoordinator: 0x7fec86f3a2d0&gt; finished receiving data from &lt;IDEConsoleAdaptor: 0x7fec86a9fe30 'target' stdin: (null) 0 stdout: (null) 0 stderr: (null) 0&gt;
10:13:51.840 Xcode[27399:424996] &lt;IDETestOperationCoordinator: 0x7fec86f3a2d0&gt;: _considerFlushingDelegateBlockQueue - nothing to flush
10:13:53.785 Xcode[27399:424996] Test operation failure: Test session exited(45) without completing.
10:13:53.785 Xcode[27399:424996] _finishWithError:Error Domain=IDETestOperationsObserverErrorDomain Code=5 ""Test session exited(45) without completing."" UserInfo={NSLocalizedDescription=Test session exited(45) without completing.}
</code></pre>

<p>Need to know the reason for this error.</p>
",https://stackoverflow.com/questions/56353313/xcode-unit-testing-session-exited-error-while-running-the-unit-test-cases,"['ios', 'xcode', 'unit-testing', 'cocoa-touch', 'xctest']",189,False,0,0
How to handle abort() while unit-testing Google Cloud Functions using Mock,"<p>The Cloud Function I am testing calls <code>abort(410)</code> and I want to test if the proper HTTP error code is received in my unit tests.</p>

<p>On simply making the request, I get the following error:</p>

<pre class=""lang-sh prettyprint-override""><code>/usr/lib/python3.7/site-packages/werkzeug/exceptions.py:707: in abort
    return _aborter(status, *args, **kwargs)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = &lt;werkzeug.exceptions.Aborter object at 0x7fd474096b00&gt;, code = 410, args = (), kwargs = {}

    def __call__(self, code, *args, **kwargs):
        if not args and not kwargs and not isinstance(code, integer_types):
            raise HTTPException(response=code)
        if code not in self.mapping:
            raise LookupError('no exception for %r' % code)
&gt;       raise self.mapping[code](*args, **kwargs)
E       werkzeug.exceptions.Gone: 410 Gone: The requested URL is no longer available on this server and there is no forwarding address. If you followed a link from a foreign page, please contact the author of this page.

/usr/lib/python3.7/site-packages/werkzeug/exceptions.py:687: Gone
</code></pre>

<p>Here is my code for making the Mock request:</p>

<pre class=""lang-py prettyprint-override""><code>from unittest.mock import Mock
from cloud_functions import main

data = { ... }
headers = { ... }

req = Mock(get_json=Mock(return_value=data), args=data, headers=headers)
resp = main.my_function(req)
</code></pre>
",https://stackoverflow.com/questions/55855617/how-to-handle-abort-while-unit-testing-google-cloud-functions-using-mock,"['python', 'unit-testing', 'mocking', 'http-error', 'werkzeug']",249,True,0,1
Unit Testing a Public method with private supporting methods inside of it?,"<p>When trying to perform test driven development on my JSF app, I have a hard time understanding how to make my classes more testable and decoupled..  For instance:</p>

<pre><code>@Test
public void testViewDocumentReturnsServletPath(){
    DocumentDO doc = new DocumentDO();
    doc.setID(7L);
    doc.setType(“PDF”);
    DocumentHandler dh = new DocumentHandler(doc);
    String servletPath = dh.viewDocument();
    assertTrue(servletPath, contains(“../../pdf?path=“);
}
</code></pre>

<p>This is only testable (with my current knowledge) if I remove some of the supporting private methods inside viewDocument() that are meant to interact with external resources like the DB.</p>

<p>How can I unit test the public API with these supporting private methods inside as well?</p>
",https://stackoverflow.com/questions/56051572/unit-testing-a-public-method-with-private-supporting-methods-inside-of-it,"['java', 'unit-testing', 'testing', 'junit', 'encapsulation']",36,True,0,1
TypeError: Cannot read property &#39;subscribe&#39; of undefined on unit testing angular app,"<p>I am running the unit test for an angular app. I expect ngOnInit to be called, but the test fails as  TypeError: Cannot read property 'subscribe' of undefined. </p>

<p>This is Component.ts</p>

<pre><code>ngOnInit() {
    this.topToolBarService.change.subscribe(customer =&gt; {
      this.filter.customerid = customer;
      this.customerid = customer;
      this.getData();

    });
}
</code></pre>
",https://stackoverflow.com/questions/55453662/typeerror-cannot-read-property-subscribe-of-undefined-on-unit-testing-angular,"['angular', 'unit-testing']",236,False,0,1
My DbSet&lt;Entity&gt; won&#39;t update when trying from Unit Testing (MSTest) code,"<p>I am unit testing my MVC application. One of the tests is validating if my controller is correctly returning data for provided id.</p>

<p>To Unit test it, I want to add data from my [TestMethod] to the Context.DBSet and then call my Controller method and validate its output.</p>

<p>However, my added record isn't reflected inside the Context.DBSet object.</p>

<p>Below is the code that I currently have.</p>

<pre><code>    ///for purpose of unit testing, there is no underlying database
    public class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser&gt;
    {
        public ApplicationDbContext()
        {
            Database.SetInitializer(new ApplicationDbContextInitializer());
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
        public DbSet&lt;Book&gt; Books { get; set; }
        public DbSet&lt;Customer&gt; Customers { get; set; }
    }
</code></pre>

<pre><code>    public class ApplicationDbContextInitializer : CreateDatabaseIfNotExists&lt;ApplicationDbContext&gt;
    {
        protected override void Seed(ApplicationDbContext context)
        {
            InitializeBooks(context);
            InitializeCustomers(context);
            base.Seed(context);
        }
    }
    //for brevity, i haven't posted the InitializeBooks &amp; InitializeCustomers()
    //these methods create Book and Customer objects
    //and do context.Book.Add(objBook) and context.Customer.Add(objCustomer)

</code></pre>

<p>My Controller class has DbContext object which I use in my MS Test</p>

<pre><code>    public class CustomersController : Controller
    {
        public ApplicationDbContext db = new ApplicationDbContext();

        ///other methods exist too
    }
</code></pre>

<p>Finally my MSTest</p>

<pre><code>[TestMethod]
public void TestCustomerIDReplacedCorrectly()
{
    var objCtrl = new CustomersController();
    Customer objCust = new Customer()
    {
        Name = ""Foo Bar"",
        Address = ""Hello World"",
    };

    Console.WriteLine(objCtrl.db.Customers.Count()) //returns 4 correctly
    objCtrl.db.Customers.Add(objCust);
    Console.WriteLine(objCtrl.db.Customers.Count()) //still returns 4!? it should return 5

    ///calls are given to controller method
    ///to fetch ViewResult and ViewBag
    ///to validate if it is processing the
    ///instance put inside the objCtrl.db.Customers
}
</code></pre>

<p>I see that the added customer is not reflected inside by Customer's DbContext object, thus even my actual controller method which I'm supposed to validate, doesn't reflect my desired behavior either. How do I ensure that my <code>objCust</code> is added to <code>objCtrl.db.Customers.Add</code></p>

<p>Here is the InitializeCustomers() code which is called for seeding</p>

<pre><code>        private void InitializeCustomers(ApplicationDbContext context)
        {
            Customer cust1 = new Customer()
            {
                Name = ""James Butt"",
                Address = ""6649 N Blue Gum St"",
                Contact = ""50-621 8927"",
                NationalID = ""12312312312""
            };

            Customer cust2 = new Customer()
            {
                Name = ""Josephine Darakjy"",
                Address = ""Chanay, Jeffrey A Esq"",
                Contact = ""81-292 9840"",
                NationalID = ""123123124""
            };

            Customer cust3 = new Customer()
            {
                Name = ""Art Venere"",
                Address = ""Chemel, James L Cpa"",
                Contact = ""85-636 8749"",
                NationalID = ""123123456""
            };


            Customer cust4 = new Customer()
            {
                Name = ""Lenna Paprocki"",
                Address = ""Feltz Printing Service"",
                Contact = ""90-385 4412"",
                NationalID = ""32165498712""
            };

            context.Customers.Add(cust1);
            context.Customers.Add(cust2);
            context.Customers.Add(cust3);
            context.Customers.Add(cust4);

        }
</code></pre>
",https://stackoverflow.com/questions/58957405/my-dbsetentity-wont-update-when-trying-from-unit-testing-mstest-code,"['c#', 'asp.net-mvc', 'entity-framework', 'mstest', 'dbcontext']",681,True,-1,1
How to stop event faking (toggle event faking) in Laravel unit testing,"<p>I am developing a Laravel application and doing the unit test. Now, I am having a bit of an issue with faking and un-faking Laravel event in the unit test. What I am trying to do is something like this.</p>

<pre><code>public function test_something()
{
     Event::fake();
     //Do somethng
     //Then I want to stop faking event here something like this
     Event::stopFaking(); //maybe
}
</code></pre>

<p>I think my code is self-explanatory. How can I achieve something like that in Laravel?</p>
",https://stackoverflow.com/questions/54238338/how-to-stop-event-faking-toggle-event-faking-in-laravel-unit-testing,"['laravel', 'unit-testing', 'laravel-events']",708,True,0,2
Angular: Unit Testing - Not able to test Ternary branch for code coverage,"<p>I'm trying to test a ternary branch which is using <code>window.location</code>.</p>

<pre><code>@Injectable()
export class ABCService {
  private hostUrl = (window.location.host.indexOf('localhost') &gt; -1) ? 'example.com' : window.location.host;
...
</code></pre>

<p>TestCase:</p>

<pre><code>it('check alternate URL', () =&gt; {
        const URL = 'http://example.org/postMethod';
        service.getData().subscribe(data =&gt; {
            expect(data.length).toBe(1);
        });
        const req = httpMock.expectOne(URL);
        expect(req.request.url).toBe(URL);
        req.flush({data:[1]});
    });
</code></pre>

<p>Getting Error: </p>

<pre><code>   Error: Expected one matching request for criteria ""Match URL: http://example.org/postMethod"", found none.
</code></pre>

<p>Any ideas of how can I test if <code>window.location.host</code> is not localhost.
Tried  <code>(window as any).location = { ...window.location, host: 'http://example.org' };</code>
still getting host == <code>localhost:9876;</code> 
<strong>OR</strong>
Is there any way I can override <code>window.location.host</code> value of mock it?</p>
",https://stackoverflow.com/questions/56912416/angular-unit-testing-not-able-to-test-ternary-branch-for-code-coverage,"['javascript', 'angular', 'unit-testing', 'karma-jasmine']",859,True,0,2
Template file &quot;Error/error500.ctp&quot; is missing. during Unit testing in CakePHP,"<p>I have set up PHPUnit into my CakePHP application, </p>

<p>but when I try to run it I receive this error:</p>

<p>Cake\View\Exception\MissingTemplateException: Template file ""Error/error500.ctp"" is missing.</p>

<p>I have tried several times with different settings of the phpunit.xml.dist page and nothing changes.</p>

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

<pre><code>public function testLogin()
{
    $this-&gt;get(""/admin/users/login"");
    $this-&gt;assertResponseOk();
}
</code></pre>

<p>Very simple method I am try to test within the tests/TestCase/Controller/Admin/UsersControllerTest.php</p>
",https://stackoverflow.com/questions/54326454/template-file-error-error500-ctp-is-missing-during-unit-testing-in-cakephp,"['php', 'cakephp', 'phpunit']",942,True,0,1
how to test methods which set private variables in viewcontroller unit testing?,"<p>I have a ViewController, which conforms to a protocol. ViewController has the following private UI components:
backgroundImage, logoimage,  loginButton , signupButton - all of these are private. (hence not accessible by unit tests)</p>

<p>How can I test the below protocol method implementation in unit testing? I am using <code>XCTestFramework</code> for unit testing.</p>

<pre><code>extension ViewController : ViewControllerProtocol{
    func setbackgroundImage(_ image: UIImage) {
        backgroundImage.image = image
    }

    func setLogoImage(_ image: UIImage) {
        logoImage.image = image
    }

    func setLoginButtontitle(_ title: String) {
        loginButton.setTitle(title, for: .normal)
    }

    func setSignupButtonTitle(_ title: String) {
        signupButton.setTitle(title, for: .normal)
    }
}

protocol ViewControllerProtocol {
    func setbackgroundImage(_ image : UIImage)
    func setLogoImage(_ image : UIImage)
    func setLoginButtontitle(_ title: String)
    func setSignupButtonTitle(_ title: String)
    func setTitleLabel(_ title: String)
    func setContinuewithoutsignupTitle(_ title: String)
}

</code></pre>
",https://stackoverflow.com/questions/59310593/how-to-test-methods-which-set-private-variables-in-viewcontroller-unit-testing,"['ios', 'swift', 'tdd']",95,True,0,1
Can anyone give me an example about unit testing in iOS Swift?,"<p>I am new in iOS development and want to learn unit testing. I want to add two numbers using text fields and show the result in a label when clicking on the action. Can anyone suggest me how to make a unit test for this?</p>
",https://stackoverflow.com/questions/55947493/can-anyone-give-me-an-example-about-unit-testing-in-ios-swift,"['ios', 'swift', 'unit-testing']",774,True,-4,2
Unit Testing methods within which extension methods are used for external resources,"<p>I need to Unit test <code>RequestToken</code> method that uses <code>HttpClient</code> and extension method <code>RequestPasswordTokenAsync</code>. </p>

<p>I have got a <code>null</code> reference exception even when a <code>delegatingHandler</code> is passed to the <code>HttpClient</code>.</p>

<pre><code>var delegatingHandler = new DelegatingHandlerStub(false);
var httpClient = new HttpClient(delegatingHandler);

var tokenServices = new TokenServices(httpClient)
tokenServices.RequestToken(passwordTokenRequest);  //exception


 public class TokenServices : ITokenServices
    {
        private readonly HttpClient _httpClient;
        public TokenServices(HttpClient httpClient) 
        {
            _httpClient = httpClient;           
        }

            public async Task&lt;TokenResponse&gt; RequestToken(PasswordTokenRequest request)
        {           

            var response = await _httpClient.RequestPasswordTokenAsync(request);

            }

    }

     public class DelegatingHandlerStub : DelegatingHandler
    {
        private readonly Func&lt;HttpRequestMessage, CancellationToken, Task&lt;HttpResponseMessage&gt;&gt; _handlerFunc;
        public DelegatingHandlerStub(bool toThrowException)
        {
            _handlerFunc = (request, cancellationToken) =&gt;
            {
                if (toThrowException)
                    throw new Exception();

                return Task.FromResult(request.CreateResponse(HttpStatusCode.OK));
            };

        }

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


namespace IdentityModel.Client
{

    public static class HttpClientTokenRequestExtensions
    {
        public static Task&lt;TokenResponse&gt; RequestPasswordTokenAsync(this HttpMessageInvoker client, PasswordTokenRequest request, CancellationToken cancellationToken = default(CancellationToken));

    }
}           
</code></pre>
",https://stackoverflow.com/questions/55341201/unit-testing-methods-within-which-extension-methods-are-used-for-external-resour,"['c#', 'unit-testing', 'nunit', 'identityserver4', 'xunit.net']",155,False,0,1
How to Mock AutoMapper IConfigurationProvider in x-unit unit testing in asp.net core,"<p>I'm writing unit test for my <code>UserRepository</code> class where I'm using AutoMapper <code>ProjectTo&lt;T&gt;</code> Queryable Extensions for projection. Here is how the class looks like:</p>

<pre><code>public class UserRepository:IUserRepository
    {
        private readonly UserManager&lt;UserEntity&gt; _userManager;
        private readonly IConfigurationProvider _mappingConfiguration;

        public UserRepository(
            UserManager&lt;UserEntity&gt; userManager,
            IConfigurationProvider mappingConfiguration)
        {
            _userManager = userManager;
            _mappingConfiguration = mappingConfiguration;
        }

        public async Task&lt;IEnumerable&lt;User&gt;&gt; GetUsersAsync()
        {
            IQueryable&lt;UserEntity&gt; query = _userManager.Users;

            var size = await query.CountAsync();

            var items = await query
                .ProjectTo&lt;User&gt;(_mappingConfiguration)
                .ToArrayAsync();

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

<p>I'm using x-unit unit test project. Here is my test class,</p>

<pre><code>public class UserRepositoryTests
    {
        [Fact]
        public async void GetUsers_AtleastOne_ReturnOneOrMore()
        {
            // Arrange
            var connectionStringBuilder =
                new SqliteConnectionStringBuilder { DataSource = "":memory:"" };
            var connection = new SqliteConnection(connectionStringBuilder.ToString());

            var options = new DbContextOptionsBuilder&lt;GallaContext&gt;()
                .UseSqlite(connection)
                .Options;

            var mockHttpContextAccessor = new Mock&lt;IHttpContextAccessor&gt;();
            var mockUserManager = new Mock&lt;UserManager&lt;UserEntity&gt;&gt;(new Mock&lt;IUserStore&lt;UserEntity&gt;&gt;().Object,
                    new Mock&lt;IOptions&lt;IdentityOptions&gt;&gt;().Object,
                    new Mock&lt;IPasswordHasher&lt;UserEntity&gt;&gt;().Object,
                    new IUserValidator&lt;UserEntity&gt;[0],
                    new IPasswordValidator&lt;UserEntity&gt;[0],
                    new Mock&lt;ILookupNormalizer&gt;().Object,
                    new Mock&lt;IdentityErrorDescriber&gt;().Object,
                    new Mock&lt;IServiceProvider&gt;().Object,
                    new Mock&lt;ILogger&lt;UserManager&lt;UserEntity&gt;&gt;&gt;().Object);
            var mockAutoMapper = new Mock&lt;IConfigurationProvider&gt;();

            using (var context = new GallaContext(options, mockHttpContextAccessor.Object))
            {
                context.Database.OpenConnection();
                context.Database.EnsureCreated();

                var userRepository = new UserRepository( mockUserManager.Object, mockAutoMapper.Object);

                // Act
                var users = await userRepository.GetUsersAsync();

                // Assert
                users.Should().HaveCountGreaterOrEqualTo(1);
            }
        }
    }
</code></pre>

<p>I'm getting the following error when executing <code>ProjectTo&lt;User&gt;</code> in my repository class.</p>

<blockquote>
  <p>{System.NullReferenceException: Object reference not set to an
  instance of an object.    at
  AutoMapper.QueryableExtensions.ProjectionExpression.ToCore[TResult](Object
  parameters, IEnumerable`1 memberPathsToExpand)</p>
</blockquote>

<p>I'm new to Moq and Unit Testing, I searched a lot but couldn't find a way to Mock this. Please assist on how to properly Mock AutoMapper <code>IConfigurationProvider</code> along with my <code>MappingProfile</code></p>

<p>Here is the Error Details</p>

<pre><code>System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.

  Source=AutoMapper

  StackTrace:
   at AutoMapper.QueryableExtensions.ProjectionExpression.ToCore[TResult](Object parameters, IEnumerable '1 memberPathsToExpand)
   at AutoMapper.QueryableExtensions.Extensions.ProjectTo[TDestination](IQueryable source, IConfigurationProvider configuration, Expression`1[] membersToExpand)
   at Repositories.UserRepository.&lt;GetUsersAsync&gt;d__5.MoveNext() in ..path\:line 46
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter '1.GetResult()
   at Repositories.Test.UserRepositoryTests.&lt;GetUsers_AtleastOne_ReturnOneOrMore&gt;d__0.MoveNext() in ..path\Repositories.Test\UserRepositoryTests.cs:line 53
</code></pre>

<p>Thanks,</p>

<p>Abdul</p>
",https://stackoverflow.com/questions/56890008/how-to-mock-automapper-iconfigurationprovider-in-x-unit-unit-testing-in-asp-net,"['c#', 'unit-testing', 'automapper', 'moq', 'xunit']",2233,True,4,2
ObjectBox ToOne object is null inside entity only on Android Local Unit Testing,"<p>I'm trying to write a test for one of my repositories, but I' can't save my Entity object due to the following error:</p>

<pre><code>java.lang.IllegalStateException: ToOne object is null inside br.com.CalendarEvent
</code></pre>

<p>My Entities are these two:</p>

<pre><code>@Entity
data class CalendarEvent(
    @Id var boxId: Long = 0,

    @Index var id: String = UUID.randomUUID().toString(),

    var userId: String = """",

    var title: String = """",

    var discipline: String = """",

    var hour: Int = 1,

    var dateInEpochDay: Long = 0L,

    var isOnline: Boolean = false,

    var estimatedTime: Int = 1,

    var userAttended: Boolean? = null) {

    lateinit var nucleus: ToOne&lt;SupportNucleus&gt;

    lateinit var specialNeeds: ToMany&lt;SpecialNeed&gt;

}
@Entity
data class SupportNucleus(
@Id var boxId: Long = 0,

@Index var id: String = UUID.randomUUID().toString(),

var name: String = """",

var location: String = """",

var contact: String = """",

var phones: String = """",

var startWorkingHour: Int = 9,

var endWorkingHour: Int = 23,

@Transient var unavailableDays: List&lt;Long&gt; = listOf())
</code></pre>

<p>As you can see both entities have their no-arg constructors, and I works as fine when I'm saving an CalendarEvent running the app or running an instrumented test. This error only occurs on Local Unit Test</p>

<p>My test class:</p>

<pre><code>class CalendarBoxRepositoryTest : BaseObjectBoxTest() {

    lateinit var subjectRepository: CalendarRepository

    var dataSourceMock: CalendarDataSource = mockk()
    var dataMapperMock: CalendarDataMapper = mockk()

    @Before
    fun setup() {
        subjectRepository = CalendarBox(dataSourceMock)
    }


    @Test
    fun save_calendar_event_correctly() {
        //Given no event was saved
        val calendarBoxBefore = store?.boxFor(CalendarEvent::class.java)
        assertEquals(0, calendarBoxBefore?.all?.size)

        val calendar = CalendarEvent(userId = ""userId"", title = ""Title"", discipline = ""Discipline"",
            dateInEpochDay = 123, isOnline = false, estimatedTime = 1, userAttended = null)

        val nucleus = SupportNucleus(name = ""Support"")


        calendar.nucleus = ToOne(calendar, CalendarEvent_.nucleus)
        calendar.nucleus.target = nucleus

        //When Saved
        runBlocking {
            subjectRepository.saveCalendarEvent(calendar)
        }

        //Verify saved correctly
        val calendarBoxAfter = store?.boxFor(CalendarEvent::class.java)
        assertEquals(1, calendarBoxAfter?.all?.size)
    }
}
</code></pre>

<p>The error actually occurs when I'm trying to fetch after saving to assert that it was saved correctly btw.</p>
",https://stackoverflow.com/questions/59361866/objectbox-toone-object-is-null-inside-entity-only-on-android-local-unit-testing,"['android', 'one-to-one', 'objectbox']",836,True,4,1
Uncaught Error: listen EADDRINUSE: address already in use :::3000 when mocha unit testing,"<p>I'm getting this error when unit testing code,</p>

<blockquote>
  <p>2 passing (14ms)   1 failing</p>
  
  <p>1) Uncaught error outside test suite:
       Uncaught Error: listen EADDRINUSE: address already in use :::3000
        at Server.setupListenHandle [as _listen2] (net.js:1255:14)
        at listenInCluster (net.js:1303:12)
        at Server.listen (net.js:1391:7)
        at Function.listen (node_modules/express/lib/application.js:618:24)
        at Object.listen (main.js:39:5)
        at Module._compile (internal/modules/cjs/loader.js:721:30)
        at Module._compile (node_modules/pirates/lib/index.js:99:24)
        at Module._extensions..js (internal/modules/cjs/loader.js:732:10)
        at Object.newLoader [as .js] (node_modules/pirates/lib/index.js:104:7)
        at Module.load (internal/modules/cjs/loader.js:620:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
        at Function.Module._load (internal/modules/cjs/loader.js:552:3)
        at Module.require (internal/modules/cjs/loader.js:657:17)
        at require (internal/modules/cjs/helpers.js:22:18)
        at Object. (test/main.test.js:4:1)
        at Module._compile (internal/modules/cjs/loader.js:721:30)
        at Module._compile (node_modules/pirates/lib/index.js:99:24)
        at Module._extensions..js (internal/modules/cjs/loader.js:732:10)
        at Object.newLoader [as .js] (node_modules/pirates/lib/index.js:104:7)
        at Module.load (internal/modules/cjs/loader.js:620:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
        at Function.Module._load (internal/modules/cjs/loader.js:552:3)
        at Module.require (internal/modules/cjs/loader.js:657:17)
        at require (internal/modules/cjs/helpers.js:22:18)
        at Array.forEach ()
        at StatWatcher.onchange (internal/fs/watchers.js:50:8)</p>
</blockquote>

<p>I'm using <a href=""https://mochajs.org"" rel=""nofollow noreferrer"">mocha</a>, and i have <code>--watch</code> on my package.json. I'm using an es6 approach to express. </p>

<p><strong>Package.json</strong></p>

<pre><code>{
  ""name"": ""elies6express"",
  ""version"": ""1.0.0"",
  ""description"": """",
  ""main"": ""index.js"",
  ""scripts"": {
    ""test"": ""./node_modules/.bin/mocha --watch --require @babel/register"",
    ""start"": ""nodemon --exec babel-node main.js""
  },
  ""author"": """",
  ""license"": ""ISC"",
  ""dependencies"": {
    ""body-parser"": ""^1.19.0"",
    ""bookshelf"": ""^0.14.2"",
    ""chai-http"": ""^4.3.0"",
    ""cookie-parser"": ""^1.4.4"",
    ""cors"": ""^2.8.5"",
    ""dotenv"": ""^8.0.0"",
    ""express"": ""^4.17.0"",
    ""knex"": ""^0.16.5"",
    ""morgan"": ""^1.9.1"",
    ""path"": ""^0.12.7"",
    ""pg"": ""^7.11.0""
  },
  ""devDependencies"": {
    ""@babel/cli"": ""^7.4.4"",
    ""@babel/core"": ""^7.4.5"",
    ""@babel/node"": ""^7.4.5"",
    ""@babel/preset-env"": ""^7.4.5"",
    ""@babel/register"": ""^7.4.4"",
    ""chai"": ""^4.2.0"",
    ""mocha"": ""^6.1.4"",
    ""nodemon"": ""^1.19.0"",
    ""reify"": ""^0.19.1"",
    ""request"": ""^2.88.0""
  }
}
</code></pre>

<p><strong>main.js</strong></p>

<pre><code>import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from 'morgan';
import path from 'path';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import userRoute from './routes/users';

const app = express();

app.use(cors());
app.use(logger('dev'));
// For React Stuff if need be
// app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
app.use(cookieParser());
app.use(bodyParser.json());

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

app.use('/users', userRoute);

app.use(() =&gt; (req, res, next)  =&gt;{
  res.locals.user = req.user; // This is the important line
  // req.session.user = user
  console.log(res.locals.user);
  next();
});
app.use(bodyParser.urlencoded({ extended:false})); 

//build mode
// app.get('*', (req, res) =&gt; {
//   res.sendFile(path.join(__dirname+'/client/public/index.html'));
// })

app.listen(process.env.PORT, () =&gt;
  console.log(`Example app listening on port ${process.env.PORT}!`),
);

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

<p><strong>main.test.js</strong></p>

<pre><code>import chai from ""chai""
import chaiHttp from 'chai-http';
import request from 'request';
import server from '../main';
const expect = chai.expect;
const should = chai.should();


chai.use(chaiHttp);

// should get / 

describe('should GET /',  () =&gt; {
    it('should get 200 status', (done) =&gt;{
        chai.request(server)
        .get('/')
        .end( (err, res) =&gt; {
            res.should.have.status(200);
            done();
        });
    });

})
// should check for Hello World!
describe('Should check for Hello World! text', () =&gt; {
    it('should check for hello world text', (done) =&gt;{
        chai.request(server)
        .get('/')
        .end( (err, res) =&gt; {
            expect(res.body).to.be.an('object') // works
            expect(res.text).to.equal('Hello World!')  // use res.text to check for res.send() text
            done();
        })
    })

})
</code></pre>
",https://stackoverflow.com/questions/56308581/uncaught-error-listen-eaddrinuse-address-already-in-use-3000-when-mocha-uni,"['node.js', 'express', 'mocha.js']",8706,True,4,5
What is the difference between dispatchEvent() and triggerEventHandler() in angular unit testing using karma?,"<p>I am writing unit test for a directive(called on input event), which is modifying an input value on a formControl. I've created a test component in my spec file for the same. I noticed a difference between triggerEventHandler() and dispatchEvent(), while dispatchEvent() was triggering the event correctly and directive was triggered, in the case of triggerEventHandler() event wasn't triggered. Can anyone let me know, what's the difference between them, apart from that dispatchEvent() is called on nativeElement.</p>

<pre><code>// directive
export class AlphaNumericCheckDirective {

  constructor(private ctrl: NgControl) {
  }
  @HostListener('input')
  onInputChange() {
    const pattern = /[^0-9]/g;
    const elVal = (this.ctrl.control as AbstractControl).value;
    if (pattern.test(elVal)) {
      const newVal = elVal.replace(pattern, '');
      (this.ctrl.control as AbstractControl).setValue(newVal);
    }
  }
}

// relevant code of test
it('should allow only numerics', () =&gt; {
   const fixture = TestBed.createComponent(TestComponent);
   const inputEl = fixture.debugElement.query(By.css('input'));
   (fixture.componentInstance.testGroup.get('testControl') as 
   AbstractControl).patchValue('12a');
   inputEl.triggerEventHandler('input', null); // not triggering the directive
   inputEl.nativeElement.dispatchEvent(new Event('input')); // triggering the directive
});
</code></pre>
",https://stackoverflow.com/questions/56446174/what-is-the-difference-between-dispatchevent-and-triggereventhandler-in-angu,"['angular', 'jasmine']",9354,True,9,2
How to do unit testing on Image as input and output in python?,"<p>I am doing unit testing on object detection <a href=""https://stackoverflow.com/questions/54576667/how-can-i-correctly-classify-the-number-of-positive-bright-color-circles-and-n"">code</a> (accepted answer) in Python. I know that in unit testing, we basically put in test parameters to functions we have defined in our program and we enter the expected result. If the expected result is output, we get OK, otherwise, we will get an error.</p>

<p>So my problem is that my <strong>input</strong> is the <strong>Image</strong> and my <strong>output</strong> is the also an image (i.e. <strong>object detected in the image</strong>) and later on, the result is represented using the bar chart and the histogram with slider. <strong>How can I do unit testing on such data?</strong></p>

<p>So far, this is what I have tried (This <a href=""https://stackoverflow.com/questions/54576667/how-can-i-correctly-classify-the-number-of-positive-bright-color-circles-and-n"">code</a> is saved as cirCode)</p>

<pre><code>from unittest import TestCase

import unittest
from unittest import TestCase
import cirCode

class TestFind_circles(TestCase):

        def setUp(self):
            pass

        def tearDown(self):
            pass

        #def test_circle(self):
         #   self.fail()

        def test_find_circles(self):

            Negative_circles, Positive_circles, out_filepath, circles, threshold = cirCode.find_circles('blobs.jpg')

            self.assertEqual(Negative_circles, 20)
            self.assertEqual(Positive_circles, 8)

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

<p>Now, I do not know how to test <strong>def circle</strong> function. Also, I am not sure if it is a correct way to test <strong>find_circles</strong> function. </p>

<p>Do you guys have any better idea to do the unit test on this <a href=""https://stackoverflow.com/questions/54576667/how-can-i-correctly-classify-the-number-of-positive-bright-color-circles-and-n"">code</a> and also how can I proceed with the unit test on the <em>circle</em> function?</p>
",https://stackoverflow.com/questions/56416041/how-to-do-unit-testing-on-image-as-input-and-output-in-python,"['python', 'unit-testing', 'opencv', 'oop', 'hough-transform']",4347,True,3,1
"Nodejs Jest Unit testing unable to return value from inside Mongodb find, findOne","<p>I am getting data with console.log(data); but it doesnot return even req.params._id from inside findOne method But it returns from outside of findOne Method </p>

<pre><code>unitMethodTest = async (req, res, next) =&gt; {
    await this.model.findOne({ _id: req.params._id }).exec((err, data) =&gt; {
        if (err) {
            console.log('===++++++ failed ');
            return req.params._id;
        }
        else {
            console.log(' Ok ')
            // console.log(data);  
            return req.params._id;  // Getting Error &lt;--
        }
    });
  // return req.params._id; // Test--2 Working fine &lt;--
}
</code></pre>

<p>and My Test  Code Here :-</p>

<pre><code>const req = {
  params: { _id: '5cc14019fa1c2c68ee7e17f9', },
  body: 'body'
 }, next = 'next', res = 'response';

  test('First Method Testing Demo for req.params and req.body', () =&gt; {
  // expect.assertions(1);
  const dataTest = controller.unitMethodTest(req, res, next);
  console.log(dataTest);
  // console.log(dataTest);
   expect(dataTest).toEqual(""5cc14019fa1c2c68ee7e17f9"");    
  })
</code></pre>

<p>I am Getting Output  as follow </p>

<pre><code>   expect(received).toEqual(expected) // deep equality

Expected: ""5cc14019fa1c2c68ee7e17f9""
Received: {}

  53 |       // console.log(dataTest);
  54 |       // // const dataTest = 11257;
&gt; 55 |        expect(dataTest).toEqual(""5cc14019fa1c2c68ee7e17f9"");
     |                         ^
  56 |        done();
  57 |       // return controller.unitMethodTest(req, res, next).catch(e =&gt; expect(e).toEqual(""5cc14019fa1c2c68ee7e17f9""));
  58 |    })

  at Object.&lt;anonymous&gt; (server/unitTesting/caseload.test.ts:55:25)

 console.log server/unitTesting/caseload.test.ts:52
Promise { &lt;pending&gt; }

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        18.606s

Cannot log after tests are done. Did you forget to wait for something 
async in your test?
Attempted to log "" Ok "".
</code></pre>
",https://stackoverflow.com/questions/56183577/nodejs-jest-unit-testing-unable-to-return-value-from-inside-mongodb-find-findon,"['node.js', 'unit-testing', 'testing', 'jestjs']",1206,False,3,1
how to write unit testing for modal or alert popup in ionic 4,"<p>I want to cover unit testing for alert controller popup and callback handler in ionic 4?</p>

<pre class=""lang-js prettyprint-override""><code>it('should open popup', () =&gt; {
  component.showAlertPopup();
  const popupElem = fixture.debugElement.queryAll(By.css('alert-inner-button'));
  console.log('popup element', popupElem);
});
</code></pre>

<pre class=""lang-js prettyprint-override""><code>async showAlertPopup() {
  const alertOpts: AlertOptions = {
    message: 'applied successfully',
    button: [{
      text: 'YES',
      handler: () =&gt; {
        this.router.navigateByUrl('app/home');
      }
    }]
  };
  const alert = await this.alertCtrl.create(alertOpts);
  console.log('alert', alert);
  alert.present();
}
</code></pre>

<p>I expected the popup element but it is undefined.</p>
",https://stackoverflow.com/questions/57772546/how-to-write-unit-testing-for-modal-or-alert-popup-in-ionic-4,"['unit-testing', 'angular7', 'ionic4']",508,False,3,0
ReactWrapper::state() can only be called on class components Unit Testing Jest and Enzyme,"<p>Writing unit testing in react using jest and enzyme. While checking with a component state , it throws an error ""ReactWrapper::state() can only be called on class components "". </p>

<pre><code>import React from 'react';
import { mount } from 'enzyme';
import expect from 'expect';
import CustomerAdd from '../CustomerAdd'
import MUITheme from '../../../../Utilities/MUITheme';
import { ThemeProvider } from '@material-ui/styles';

describe('&lt;CustomerAdd /&gt;', () =&gt; {
    const wrapper = mount(
        &lt;ThemeProvider theme={MUITheme}&gt;
          &lt;CustomerAdd {...mockProps}&gt;&lt;/CustomerAdd&gt;
        &lt;/ThemeProvider&gt;
        );
        test('something', () =&gt; {
            expect(wrapper.find(CustomerAdd).state('addNewOnSubmit')).toEqual(true);
        });
});
</code></pre>

<p>In the above code CustomerAdd Component is class component.I don't what wrong with my code. Can any one help me out of this problem. Thanks in advance.</p>
",https://stackoverflow.com/questions/58429807/reactwrapperstate-can-only-be-called-on-class-components-unit-testing-jest-a,"['reactjs', 'unit-testing', 'jestjs', 'material-ui', 'enzyme']",20188,True,8,1
How to swap a resource file path for a test file during unit testing?,"<p>I have a resource file which has some settings. I have a ResourceLoader class which loads the settings from this file. This class is currently an eagerly instantiated singleton class. As soon as this class loads, it reads the settings from the file (file path stored as a constant field in another class). Some of these settings are not suitable for unit tests. For example, I have thread sleep time in this file, which may be hours for production code, but I'd like it to be a couple of milliseconds for unit tests. So I have another test resource file which has a different set of values.</p>
<p>How do I go about swapping the main resource file with this test file during unit testing? The project is a Maven project and I'm using TestNG as the testing framework. These are some of the approaches I've been thinking about but none of them seem ideal:</p>
<ol>
<li><p>Use <code>@BeforeSuite</code> and modify the <code>FilePath</code> constant variable to point to the test file and use <code>@AfterSuite</code> to point it back to the original file. This seems to be working, but I think because the <code>ResourceLoader</code> class is eagerly instantiated, there is no guarantee that the <code>@BeforeSuite</code> method will always execute before the <code>ResourceLoader</code> class is loaded and hence old properties may be loaded before the file path is changed. Although most compilers load a class only when it is required, I'm not sure if this is a Java specification requirement. So in theory this may not work for all Java compilers.</p>
</li>
<li><p>Pass the resource file path as a command line argument. I can add the test resource file path as command line argument in the surefire configuration in the pom. This seems a bit excessive.</p>
</li>
<li><p>Use the approach in 1. and make <code>ResourceLoader</code> lazy instantiated. This guarantees that if <code>@BeforeMethod</code> is called before the first call to <code>ResourceLoader.getInstance().getProperty(..)</code>, <code>ResourceLoader</code> will load the correct file. This seems to be better than the first 2 approaches, but I think making a singleton class lazy instantiated makes it ugly as I can't use a simple pattern like making it an enum and such (as is the case with eager instantiation).</p>
</li>
</ol>
<p>This seems like a common scenario, what is the most common way of going about it?</p>
",https://stackoverflow.com/questions/59492790/how-to-swap-a-resource-file-path-for-a-test-file-during-unit-testing,"['java', 'unit-testing', 'design-patterns', 'singleton', 'testng']",1591,True,8,2
hostEl.createShadowRoot is not a function in Angular 6 using jest for unit testing,"<p>I am getting this error when running a test for the component I created.</p>

<p>Anyone who can help</p>
",https://stackoverflow.com/questions/54801151/hostel-createshadowroot-is-not-a-function-in-angular-6-using-jest-for-unit-testi,"['angular6', 'jestjs']",191,False,3,0
What is the proper way to stub dependencies when unit testing in TypeScript?,"<p>I am migrating a set of Firebase Cloud Functions from Javascript to Typescript. With JS I was able to unit test with mocha, chai, and sinon and stub out various database dependencies for testing. With TS I am running into problems and unexpected behavior I don't understand.</p>

<p>The pattern is something like:
<code>mainFunction</code> calls <code>helperFunction</code> which calls <code>nestedHelperFunction</code>.</p>

<p>I want to stub or spy on <code>nestedHelperFunction</code> in my tests when I call <code>mainFunction</code> with some test data.</p>

<p><code>mainFunction</code> is in an <code>index.ts</code> and <code>helperFunction</code> and <code>nestedHelperFunction</code> are in something like a <code>utils.ts</code> file.</p>

<p><em>Example of odd behavior</em></p>

<pre class=""lang-js prettyprint-override""><code>// index.ts
import * as utils from './utils';


export async function mainFunction() {
    console.log('Starting mainFunction...');

    const promiseResults = await Promise.all([
        Promise.resolve('One'),
        utils.helperFunction(),
        Promise.resolve('Three'),
    ]);

    console.log(promiseResults);
    return 1;
}
</code></pre>

<pre class=""lang-js prettyprint-override""><code>// utils.ts
export async function helperFunction() {
    const newString = await nestedHelperFunction();
    return 'helperFunction Result | ' + newString;
}

export async function nestedHelperFunction() {
    return '***Nested***';
}
</code></pre>

<p>Test file</p>

<pre class=""lang-js prettyprint-override""><code>//index.test.ts
import * as myFunctions from '../index';
import * as utils from '../utils';
import * as sinon from 'sinon';
import * as chai from 'chai';

const expect = chai.expect;


describe(""Test Suite"", () =&gt; {

    let functionSpy: sinon.SinonStub;

    beforeEach(() =&gt; {
        functionSpy = sinon.stub(utils, 'helperFunction');
        functionSpy.returns(Promise.resolve('Stubbed Function Results!'))
    });

    afterEach(() =&gt; {
        functionSpy.restore();
    });

    it('should resolve and call the correct functions.', async () =&gt; {
        const returnValue = await myFunctions.mainFunction();

        expect(returnValue).to.equal(1);
        expect(functionSpy.callCount).to.equal(1);
    })
})
</code></pre>

<p><strong>Output:</strong>
Tests pass and I get : <code>[ 'One', 'Stubbed Function Results!', 'Three' ]</code></p>

<p>However, If I try to stub the <code>nestedHelperFunction</code> it does not work.</p>

<pre class=""lang-js prettyprint-override""><code>// index.test.js
import * as myFunctions from '../index';
import * as utils from '../utils';
import * as sinon from 'sinon';
import * as chai from 'chai';

const expect = chai.expect;


describe(""Test Suite"", () =&gt; {

    let functionSpy: sinon.SinonStub;

    beforeEach(() =&gt; {
        functionSpy = sinon.stub(utils, 'nestedHelperFunction'); // Changed
        functionSpy.returns(Promise.resolve('Stubbed Function Results!'))
    });

    afterEach(() =&gt; {
        functionSpy.restore();
    });

    it('should resolve and call the correct functions.', async () =&gt; {
        const returnValue = await myFunctions.mainFunction();

        expect(returnValue).to.equal(1);
        expect(functionSpy.callCount).to.equal(1);
    })
})
</code></pre>

<p><strong>Output</strong>
Test fails and I get unmodified output: <code>[ 'One', 'helperFunction Result | ***Nested***', 'Three' ]</code></p>

<p>Why does it not work when stubbing <code>nestedHelperFunction</code> but works for  <code>helperFunction</code>?</p>

<p><em>Working Example</em></p>

<p>Something that works, but I don't understand why, is within <code>utils.ts</code> creating <code>helperFunction</code> and <code>nestedHelperFunction</code> as methods on a class instead of 'top level' functions.</p>

<pre class=""lang-js prettyprint-override""><code>// utils.ts

export class Utils {
    static async helperFunction(): Promise&lt;string&gt; {
        const newString = await this.nestedHelperFunction();
        return 'helperFunction Result | ' + newString;
    }

    static async nestedHelperFunction (): Promise&lt;string&gt; {
        return '***Nested Output***';
    }
}
</code></pre>

<p>Tests File</p>

<pre class=""lang-js prettyprint-override""><code>// index.test.ts
import {mainFunction} from '../index';
import {Utils} from '../utils';
import sinon from 'sinon';
import * as chai from 'chai';

const expect = chai.expect;


describe(""Test Suite"", () =&gt; {

    let functionSpy: sinon.SinonStub;

    beforeEach(() =&gt; {
        functionSpy = sinon.stub(Utils, 'nestedHelperFunction');
        functionSpy.returns(Promise.resolve('Stubbed Function Results!'));
    });

    afterEach(() =&gt; {
        functionSpy.restore();
    });

    it('should resolve and call the correct functions.', async () =&gt; {
        const returnValue = await mainFunction();

        expect(returnValue).to.equal(1);
        expect(functionSpy.callCount).to.equal(1);
    })
})
</code></pre>

<pre class=""lang-js prettyprint-override""><code>// index.ts
import {Utils} from './utils';

export async function mainFunction() {
    console.log('Starting mainFunction...');

    const promiseResults = await Promise.all([
        Promise.resolve('One'),
        Utils.helperFunction(),
        Promise.resolve('Three'),
    ]);

    console.log(promiseResults);
    return 1;
}
</code></pre>

<p><strong>Output</strong>
Tests pass and I get the desired/expect output: <code>[ 'One',
  'helperFunction Result | Stubbed Function Results!',
  'Three' ]</code></p>

<p>Material I've read suggests to me something going on with importing es6 modules or how Typescript compiles and can change the names of imported items. In Javascript I was using Rewire to set stubs, some were private functions, but I had issues with that in Typescript.</p>

<p>Thanks for any help.</p>
",https://stackoverflow.com/questions/57361658/what-is-the-proper-way-to-stub-dependencies-when-unit-testing-in-typescript,"['typescript', 'unit-testing', 'sinon']",2541,True,2,1
How to mock a service call in a function in angular unit testing?,"<p>I am trying to write a test case for the following function:</p>

<pre><code>foo = () =&gt; { 
  this.someService.getDetails({key:'value'}).subscribe(details =&gt; {
  //do stuff
    this.someService.getMoreDetails().subscribe(moreDetails =&gt; {
    //do stuff
   });
  });
}
</code></pre>

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

<pre><code>    getDetails = (args) :Observable&lt;any&gt; {
      return this.http.post&lt;any&gt;(//calls)
    } 
// similar for getMoreDetails
</code></pre>

<p>The test file that I have written looks like this:</p>

<pre><code>     const someServiceStub = jasmine.createSpyObj('someService', ['getDetails', 'getMoreDetails']);
...
...

    it('should called getMoreDetails', () =&gt; {
        component.foo();
        fixture.detectChanges();
        someServiceStub.getDetails.and.returnValue(Observable.of
          ({ Details: 'Tired of giving you details'})
        );
        expect(someServiceStub.getMoreDetails).toHaveBeenCalled();
      });
</code></pre>

<p>However, my test case fails giving the error 'Cannot read property subscribe of undefined' (for the first line inside foo function).</p>

<p>I have tried using mockservice classes too but the same error comes up.
What is the possible reason for this and how can I solve it?</p>
",https://stackoverflow.com/questions/54050891/how-to-mock-a-service-call-in-a-function-in-angular-unit-testing,"['angular', 'unit-testing', 'jasmine', 'karma-runner']",5443,True,2,1
How to fix &#39;cannot read property subscribe&#39; of undefined during angular unit testing?,"<p>Angular6 - Unit testing error “Cannot read property 'subscribe' of undefined”</p>

<p>I was writing a unit test for an angular component which is having several dependencies. One of those dependent service has some properties as observables. I tried to mock this service but is throwing error as in title,</p>

<p>spec.ts</p>

<pre><code>describe('Component', () =&gt; {
let mockService= jasmine.createSpyObj(['property1', 'property2', 'property3']);

beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
declarations: [testComponent],
providers: [
......someOther,
{ provide service, useValue: mockService},
......someOther
]
}).compileComponents();

fixture = TestBed.createComponent(testComponent);
component = fixture.componentInstance;
}));

it('should be created', () =&gt; {
expect(component).toBeTruthy();
  });
});
</code></pre>

<p>ts file has</p>

<pre><code>this.Service.property1.subscribe(() =&gt; {})
this.Service.property2.subscribe(() =&gt; {})
this.Service.property3.subscribe(() =&gt; {})
</code></pre>

<p>Expect test case to pass but fails with error as in title</p>
",https://stackoverflow.com/questions/54017368/how-to-fix-cannot-read-property-subscribe-of-undefined-during-angular-unit-tes,"['angular', 'karma-jasmine']",810,False,2,1
Swift unit testing: module name of object class causes type check to fail,"<p>I've had unit tests in my project for a couple weeks and they've been working fine up until now.</p>

<p>One of my new unit tests instantiates one of my custom view controllers. Said view controller instantiates and adds a subview of type <code>CoolSearchBar</code>, a class I've created myself (both .swift file and .xib file).</p>

<p>In said view controller, I load that <code>CoolSearchBar</code> instance programmatically, before adding it to the view hierarchy, like this:</p>

<pre><code>guard let searchBar = Bundle.main.loadNibNamed(String(describing: CoolSearchBar.self), owner: nil, options: nil)?.first as? CoolSearchBar else {
    fatalError(""Search bar could not be loaded from nib"")
}
</code></pre>

<p>When I run the app normally, this check passes, and the rest of the code continues executing.</p>

<p>However, when I run my unit tests, the fatal error in the code above gets hit. I did some digging, and found that the reason why the error gets hit is that the class name alone (<code>CoolSearchBar</code>) does not tell the whole story.</p>

<p>Specifically, I used <code>NSStringFromClass</code> to get more verbose descriptions of the classes of the objects I'm comparing. Basically, the xib being created is evaluating to class type:</p>

<p><code>MyApp.CoolSearchBar</code></p>

<p>But the class that is being tested against (the <code>as? CoolSearchBar</code> part) is evaluating to:</p>

<p><code>MyAppTests.CoolSearchBar</code></p>

<p>Does anyone know why the module names vary on the classes? How I can get these two seemingly identical classes to evaluate to the same thing, so that my unit tests will pass again?</p>

<p>Thanks, and please comment if you need more information.</p>
",https://stackoverflow.com/questions/55765869/swift-unit-testing-module-name-of-object-class-causes-type-check-to-fail,"['ios', 'swift', 'unit-testing']",200,True,2,1
Unit testing KeyboardEvent returning &quot;isTrusted: false&quot; and &quot;Cannot read property &#39;nextElementSibling&#39; of null&quot;,"<p>I have a function that is triggered via <code>keydown.enter</code> and will focus on the next available element, however I cannot get the test to accept my fake KeyboardEvent...</p>

<pre><code>@ViewChild('btnOne') btnOne: ElementRef&lt;HTMLInputElement&gt;;
@ViewChild('btnTwo') btnTwo: ElementRef&lt;HTMLInputElement&gt;;

myFunct(evt: KeyboardEvent) {
  const next = &lt;HTMLElement&gt;evt.srcElement.nextElementSibling;
  next.focus();
}
</code></pre>

<p>Test:</p>

<pre><code>it('Should shift focus from btnOne to btnTwo', () =&gt; {
  const b1 = component.btnOne.nativeElement;
  const b2 = component.btnTwo.nativeElement;

  const button2 = {nodeName:'BUTTON'}
  const button1 = {nodeName:'BUTTON', nextElementSibling: button2};

  const evtObj = {'code': 'Enter', srcElement: button1);
  const kbEvent = new KeyboardEvent('keydown.enter', evtObj);

  focusSpy = spyOn(b2, 'focus'); // Spy on focus for 2nd button to be focused
  b1.focus(); // Manually apply focus to 1st button so it will progress from here

  component.myFunct(kbEvent); // I get the failures here (see below)

  expect(b2.focus).toHaveBeenCalled();

});
</code></pre>

<p>The test error with the message:</p>

<blockquote>
  <p>TypeError: Cannot read property 'nextElementSibling' of null</p>
</blockquote>

<p>I have also printed out the <code>evt</code> as it comes from the test into the function itself:</p>

<blockquote>
  <p>KeyboardEvent{isTrusted: false}</p>
</blockquote>

<p>I have searched for the <code>isTrusted</code> issue and found <a href=""https://stackoverflow.com/questions/47101648/angular-4-unit-test-for-keyboardevent"">this question</a>, but I couldn't resolve my issue with their answer...</p>
",https://stackoverflow.com/questions/54460136/unit-testing-keyboardevent-returning-istrusted-false-and-cannot-read-propert,"['javascript', 'angular', 'typescript', 'unit-testing', 'keyboard-events']",1447,False,2,0
How to mock custom JdbcCursorItemReader during individual step unit testing on Spring Batch?,"<p>I am trying to create a Junit test case for testing an individual step of my batch Job which in turn has a custom <code>JdbcCursorItemReader</code> and writes data into Flat file. I am unable to mock the data that can be injected into the processor for writing it into the Flatfile. Please help.</p>

<p>I followed steps in below link to create a test case to launch an individual step:</p>

<p><a href=""https://docs.spring.io/spring-batch/trunk/reference/html/testing.html"" rel=""nofollow noreferrer"">https://docs.spring.io/spring-batch/trunk/reference/html/testing.html</a></p>

<p>Since my reader component is stepscope I am using the context around section 10.4 in above link to put the required domain objects into <code>ExecutionContext</code> but while launching the step it does not recognize the same instead it executes the actual SQL query which I am injecting through config xml.</p>

<p>My config xml has step as below :</p>

<pre><code>&lt;step id=""sample-step"" next=""next-step""&gt;
 &lt;tasklet&gt;
    &lt;chunk reader=""customJDBCReader"" processor=""customProcessor"" 
     writer=""customFlatFileItemWriter"" commit-interval=""XXX"" /&gt;
 &lt;/tasklet&gt;
&lt;/step&gt;
</code></pre>

<p>My customreader implements <code>JdbcCursorItemReader</code> which has a SQL defined for reading information from database.</p>

<p>During my unit testing I am trying to mock the data instead of depending on actual data from database</p>

<pre><code>private StepExecution execution;

@BeforeStep
public StepExecution getStepExection() {
    execution = MetaDataInstanceFactory.createStepExecution();
    return execution;
}

@Test
public void testSampleStep() throws UnexpectedInputException, ParseException, Exception {
    MyDomainObject domainObject= new MyDomainObject ();
    domainObject.setID(""sampleID"");
    domainObject.setName(""sampleName"");
    domainObject.setImage(""sampleImage"");
    execution.getExecutionContext().put(""someKey"", domainObject);
    execution.setReadCount(1);

    JobExecution jobExecution = jobLauncherTestUtils.launchStep(""sample-step"", jobParameters, execution.getExecutionContext());
    AssertFile.assertFileEquals(new FileSystemResource(EXPECTED_FILE), new FileSystemResource(OUTPUT_FILE));
}
</code></pre>

<p>The expected result should be the launchstep needs to get the data from <code>executionContext</code> instead of database to write the same into faltfile.</p>
",https://stackoverflow.com/questions/54713720/how-to-mock-custom-jdbccursoritemreader-during-individual-step-unit-testing-on-s,"['spring-boot', 'spring-batch']",2134,True,1,1
Unit testing - how to test a method that takes in a lambda function?,"<p>can someone help me to figure out how i can unit tests the below code effectively. its kotlin but can be anything:   </p>

<pre><code> myMainObject.doSomethingSpecial({ differentObject -&gt;
                differentObject.doFirst()
                differentObject.doSecond()
                differentObject.doThird()
            })
</code></pre>

<p>i would like to test that doSomethingSpecial actually works.  </p>

<p>i thought about trying to mock the lambda:</p>

<pre><code>val function1: () -&gt; Int = mock()
    whenever(function1.invoke())
        .thenReturn(1)
</code></pre>

<p>but this is not what i really want. i want to test that all the methods in the lamda get called so i want to test that <strong>doFirst,doSecond,doThird</strong>, etc are all called i think is how best to unit test this.  do i have use argument capture for this, how ? To be clear, my question is how to unit test the method doSomethingSpecial ?</p>
",https://stackoverflow.com/questions/54811098/unit-testing-how-to-test-a-method-that-takes-in-a-lambda-function,"['unit-testing', 'lambda', 'junit', 'kotlin']",1881,True,1,1
"property &#39;then&#39; does not exist on type void, Angular 6 unit testing error","<p>( angular 6 app, unit testing using karma and jasmine ) <br>
Hellooo,<br>
Being new at unit testing, I tried http testing on one of my Service's functions by copying and pasting this code that i found in a tutorial :</p>

<pre><code>let httpClientSpy: { get: jasmine.Spy };
import { TestBed, async, inject } from '@angular/core/testing';
import { TrainerCalendarService } from './trainer-calendar.service';
import { asyncData } from '../helpers/async-observable-helpers';
import { Appointment } from '../models/appointment';

let service: TrainerCalendarService;

describe('Service: TrainerCalendar', () =&gt; {
beforeEach(() =&gt; {
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get', 'post']);
service = new TrainerCalendarService(&lt;any&gt; httpClientSpy);
 });

it('should returns list of appointment', () =&gt; {
const list: Appointment[] = [
  new Appointment(),
  new Appointment()
];

httpClientSpy.get.and.returnValue(asyncData&lt;Appointment[]&gt;(list));

service.getAll().then(items =&gt; expect(items).toEqual(list, 'same items'));
});
});
</code></pre>

<p>And i got this after changing it according to my app: </p>

<pre><code>import { grpService } from ""./app/Services/grp.service""; 
import { of } from 'rxjs'
import { EtudiantComponent } from './app/etudiant/etudiant.component';

let httpClientSpy: { get: jasmine.Spy };

let service: grpService;

describe('Service: Test attendency ', () =&gt; {
beforeEach(() =&gt; {
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get', 'post']);
service = new grpService(&lt;any&gt; httpClientSpy);
 });

 it('should returns list of students', () =&gt; {
 const list: EtudiantComponent[] = [
  new EtudiantComponent(service),
  new EtudiantComponent(service)
];

httpClientSpy.get.and.returnValue(of&lt;EtudiantComponent[]&gt;(list));

service.getGroupesFromServer.then(items =&gt; expect(items).toEqual(list, 'same items'));
 });
});
</code></pre>

<p>i get an error for that last line of code : Property 'then' does not exist on type '() => void'.</p>

<p>How can i fix that?</p>
",https://stackoverflow.com/questions/59516298/property-then-does-not-exist-on-type-void-angular-6-unit-testing-error,"['unit-testing', 'angular6', 'karma-runner']",648,False,1,1
How to code coverage a promise inside functions while unit testing using Jest,"<p>How to code cover then and catch function of a promise inside a function while unit testing using jest? Please see code below.</p>

<p>Service.js</p>

<pre><code>export const userLogin = data =&gt; {
  return AjaxService.post(
    ""http://localhost/3000/signin"", data
  ).then(
    res =&gt; {
      return res.data;
    },
    error =&gt; {
      return error.response.data;
    }
  );
};
</code></pre>

<p>AjaxService.js</p>

<pre><code>export const AjaxService = {
  post: (url, data, headers) =&gt; {
    return axios({
      method: ""POST"",
      url: url,
      headers: headers || { ""content-type"": ""application/json"" },
      data: data
    });
  }
</code></pre>

<p>}</p>

<p>Example.js</p>

<pre><code>class Login extends Component {

  handleSubmit = (event) =&gt; {
    if (this.props.handleSubmit) this.props.handleSubmit(); 
    this.setState({isLoggedIn: true})
    userLogin().then((res) =&gt; {
     // when promise resolve
     var response = res;
    }, (err) =&gt; {
      // when promise reject  
      var error = err;
    })
  }
  render() {
   return (
    &lt;form id=""login-form"" onSubmit={(e) =&gt; this.handleSubmit(e)} &gt;
     &lt;input type=""username"" /&gt;
     &lt;input type=""password"" /&gt;
     &lt;button type=""submit""&gt;Login&lt;/button&gt;
    &lt;/form&gt;
   )
  }

}
</code></pre>

<p>Example.test.js</p>

<pre><code>it(""test login form submit "", () =&gt; {
    wrapper = shallow(&lt;Login /&gt;);
    let instance = wrapper.instance(); // get class instance
    instance.handleSubmit(); // will trigger component method
    let actualVal = wrapper.state().isLoggedIn; // get state key value
    expect(true).to.eql(actualVal);
  });
</code></pre>

<p>After generating coverage report using <code>--coverage</code> in Jest</p>

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

<p>We can see that the code inside promise success and error function doesn't get covered as part of unit testing. So please help cover this. Thanks.</p>
",https://stackoverflow.com/questions/58110463/how-to-code-coverage-a-promise-inside-functions-while-unit-testing-using-jest,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'code-coverage']",2451,True,1,2
Test dependencies for white-box unit testing Java modules with Maven and Eclipse,"<p>I'm trying to convert existing Java projects with Maven and Eclipse into Java 9+ modules. The projects have unit tests and the unit tests have test dependencies. I need the test dependencies to be available in the test code, but I don't want them exposed to the rest of the world in the published modules.</p>

<p>I think <a href=""https://sormuras.github.io/blog/2018-09-11-testing-in-the-modular-world.html"" rel=""nofollow noreferrer"">Testing in the Modular World</a> describes the Maven solutions well. In summary one solution is to create one <code>module-info.java</code> in the main source folder and another in the testing folder. The file in the main folder has the real dependencies. The file in the test folder adds the test dependencies.</p>

<p>The solution works well in Maven and I can build and run tests from the command line. However, when I import the project into Eclipse as a Maven project it balks. Eclipse complains that ""build path contains duplicate entry module-info"" and refuses to build the project at all.</p>

<p>Using the other suggested solution in the article with a <code>module-info.test</code> containing <code>--add-reads</code> has no effect and the build fails in both Maven and Eclipse as the tests can't find their dependencies.</p>

<p>To make matters more complex I need to import the test dependencies from Maven, but I also need to import standard Java modules that are not used by the main code. For example one unit test relies on the built-in web server provided by <code>java.httpserver</code> and as it is part of the JDK any magic done on the test dependencies will miss it.</p>

<p>Is there a solution for this that works in Maven and Eclipse (latest versions)? It sounds like a very common problem and the module system has been around for a while by now.</p>

<p>Note that I really don't want to change the project settings in Eclipse. I can fiddle with plugins in the pom files, but adding a manual routine where all developers need to edit the generated/imported project settings manually is not an option.</p>

<p>EDIT:
There is an open Eclipse bug report for this, see <a href=""https://bugs.eclipse.org/bugs/show_bug.cgi?id=536847"" rel=""nofollow noreferrer"">Eclipse bug 536847</a>. It seems it is not supported yet, but perhaps someone can suggest a workaround?</p>
",https://stackoverflow.com/questions/59429579/test-dependencies-for-white-box-unit-testing-java-modules-with-maven-and-eclipse,"['java', 'eclipse', 'maven', 'junit', 'java-module']",550,False,1,1
Best practices for unit testing in Python - multiple functions apply to same object,"<p>I have a bunch of functions which apply to a similar object, for example a Numpy array which represents an n-dimensional box:</p>

<pre class=""lang-py prettyprint-override""><code># 3-D box parameterized as:
#     box[0] = 3-D min coordinate
#     box[1] = 3-D max coordinate
box = np.array([
    [1, 3, 0],
    [4, 5, 7]
])
</code></pre>

<p>Now I have a whole bunch of functions that I want to run on lists of boxes, eg. <code>volumes</code>, <code>intersection</code>, <code>smallest_containing_box</code>, etc. In my mind here is the way I was hoping to set this up:</p>

<pre class=""lang-py prettyprint-override""><code># list of test functions:
test_funcs = [volume, intersection, smallest_containing_box, ...]
# manually create a bunch of inputs and outputs
test_set_1 = (
    input = [boxA, boxB, ...], # where each of these are np.Array objects
    output = [
        [volA, volB, ...], # floats I calculated manually
        intersection, # np.Array representing the correct intersection
        smallest_containing_box, # etc.
    ]
)
# Create a bunch of these, eg. test_set_2, test_set_3, etc. and bundle them in a list:
test_sets = [test_set_1, ...]
# Now run the set of tests over each of these:
test_results = [[assertEqual(test(t.input), t.output) for test in test_funcs] for t in test_sets]
</code></pre>

<p>The reason I want to structure it this way is so that I can create multiple sets of (input, answer) pairs and just run all the tests over each. Unless I'm missing something, the structure of <code>unittest</code> doesn't seem to work well with this approach. Instead, it seems like it wants me to create an individual TestCase object for each pair of function and input, i.e.</p>

<pre class=""lang-py prettyprint-override""><code>class TestCase1(unittest.TestCase):
    def setUp(self):
        self.input = [...]
        self.volume = [volA, volB, ...]
        self.intersection = ...
        # etc.

    def test_volume(self):
        self.assertEqual(volume(self.input), self.volume)

    def test_intersection(self):
        self.assertEqual(intersection(self.input), self.output)

    # etc.

# Repeat this for every test case!?
</code></pre>

<p>This seems like a crazy amount of boilerplate. Am I missing something?</p>
",https://stackoverflow.com/questions/55208694/best-practices-for-unit-testing-in-python-multiple-functions-apply-to-same-obj,"['python', 'unit-testing', 'testing']",2006,False,1,2
Got an issue unit testing with NUnit and an asp.net class that inherits,"<p>First sorry for my English, it's not my native language.</p>

<p>I work on an Asp.Net application with a homemade framework by my company.</p>

<p>I have an issue when I start unit tests with NUnit framework. I want to test methods that are in a class who inherits from an other but I have many errors before started any tests : </p>

<blockquote>
  <p>NUnit Adapter 3.12.0.0: Test execution started
  Running all tests in C:\PRIV\Projects\WebSite0\test\bin\Debug\test.dll
     NUnit3TestExecutor converted 1 of 1 NUnit test cases
  SetUp failed for test fixture test.Class1
  System.InvalidOperationException : Aucune implémentation fournie pour ExecEnv
     à CDM.DevbCommon.Global.ExecEnv.get_Implementation() dans d:\BuildAreas\mk_build\DEVBCOMMON\V5.210\PROJECTS\devbcommon\Global\ExecEnv.cs:ligne 38
     à CDM.DevbCommon.TraceLog.TraceBase.GetObjectFromStorage() dans d:\BuildAreas\mk_build\DEVBCOMMON\V5.210\PROJECTS\devbcommon\TraceLog\TraceBase.cs:ligne 37
     à CDM.DevbCommon.Toolkit.DocReflectionToolkit.GetDocumentation(Assembly asm) dans d:\BuildAreas\mk_build\DEVBCOMMON\V5.210\PROJECTS\devbcommon\Toolkit\DocReflectionToolkit.cs:ligne 115
     à CDM.DevbCommon.Toolkit.DocReflectionToolkit.GetDocumentation(Type type) dans d:\BuildAreas\mk_build\DEVBCOMMON\V5.210\PROJECTS\devbcommon\Toolkit\DocReflectionToolkit.cs:ligne 46
     à CDM.DevbCommon.Navigation.ReflexiveSteps.Reflection.ReflexiveActionProviderBase.SetupSignature(PublicStepSignature Signature) dans d:\BuildAreas\mk_build\DEVBCOMMON\V5.210\PROJECTS\devbwebapplication4\Navigation\ReflexiveSteps\Reflection\ReflexiveActionProviderBase.cs:ligne 371
     à CDM.DevbCommon.Navigation.ReflexiveSteps.PageStep..ctor() dans d:\BuildAreas\mk_build\DEVBCOMMON\V5.210\PROJECTS\devbwebapplication4\Navigation\ReflexiveSteps\Steps\PageStep.cs:ligne 27
     à CDM.DevbCommon.Navigation.ReflexiveSteps.ObjectPageStep`1..ctor() dans d:\BuildAreas\mk_build\DEVBCOMMON\V5.210\PROJECTS\devbwebapplication4\Navigation\ReflexiveSteps\Steps\ObjectPageStep.cs:ligne 27
     à CDM.WebSite0.Commands.EmptyPage..ctor()
     à test.Class1..ctor() dans C:\PRIV\Projects\WebSite0\test\Class1.cs:ligne 17
  NUnit Adapter 3.12.0.0: Test execution complete</p>
</blockquote>

<p>When I hide the inheritance, the unit test works normally without problems.
But with the inheritance, I receive a <code>System.InvalidOperationException</code></p>

<p>Here the unit test class :</p>

<pre><code>namespace test
{
    [TestFixture]
    public class Class1 
    {
        private readonly EmptyPage vm = new EmptyPage();

        [Test]
        public void TestAddition()
        {
            double actAddNumberResult = vm.AddNumber(5, 7);
            Assert.That(actAddNumberResult, Is.EqualTo(12) );
        }


</code></pre>

<p>And here the class to test : </p>

<pre><code> public class EmptyPage : ObjectPageStep&lt;EmptyPageViewModel&gt;
    {

        public void Prepare()
        {
        }

        public double AddNumber(double nombre1, double nombre2)
        {
            return nombre1 + nombre2;
        }
</code></pre>

<p>I tried with XUnit and I have the same problem.</p>

<p>Any idea?</p>
",https://stackoverflow.com/questions/54443027/got-an-issue-unit-testing-with-nunit-and-an-asp-net-class-that-inherits,"['c#', '.net']",223,True,1,1
Unit testing a form element with Jasmine and Karma in AngularJS for $setPrisrine(),"<p>I have a input form element as below in my HTML:</p>

<pre><code>&lt;form name='myForm'&gt;
    &lt;input type=""text"" id=""description"" name=""description""
           ng-model=""vm.description"" /&gt;
&lt;/form&gt;
</code></pre>

<p>And I set it pristine as below in my controller by its name.</p>

<pre><code>$scope.myForm.description.$setPristine();
</code></pre>

<p>How can I write a unit test to check if the input is being set to pristine or not?</p>
",https://stackoverflow.com/questions/58139028/unit-testing-a-form-element-with-jasmine-and-karma-in-angularjs-for-setprisrine,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'karma-runner']",42,False,1,0
Unit testing features missing for .NET Core in VS 2019 and Visual Studio Installer?,"<p>I just added a MSTest .NET Core unit test project to a solution in VS 2019 but there now don't appear to be any features for adding a new unit test file to that project.</p>

<h3>Missing Add > Unit test... context menu option</h3>

<p>Steps to reproduce missing context menu issue:</p>

<ul>
<li>In Visual Studio 2019, add a new 'MSTest Project (.NET Core)' project to an existing solution</li>
<li>Right click on the name of the new test project in Solution Explorer</li>
<li>See if the option for 'Add > Unit test...' is present?</li>
</ul>

<p>That option, which was present in earlier versions of VS (and that's still present in VS2019 for full unit test projects targeting the full .NET framework projects) is missing for me:</p>

<p><a href=""https://i.stack.imgur.com/APwgU.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/APwgU.png"" alt=""VS2019 Context menu without &#39;Add &gt; Unit test...&#39; option""></a></p>

<h3>Missing unit test templates</h3>

<p>Steps to reproduce missing unit test template issue:</p>

<ul>
<li>In Visual Studio 2019, add a new 'MSTest Project (.NET Core)' project to an existing solution</li>
<li>Right click on the name of the new test project in Solution Explorer</li>
<li>Select 'Add > New item...' </li>
<li>See if there are any C# related testing options?</li>
</ul>

<p>I'm not seeing any unit test templates whatsoever:
<a href=""https://i.stack.imgur.com/6ALGx.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/6ALGx.png"" alt=""Add New Item dialog filtered for test showing no results""></a></p>

<h3>What I've tried</h3>

<p>I thought the issue might be that I <a href=""https://stackoverflow.com/a/42975299/1879019"">hadn't got the unit testing workload installed</a> for VS2019, but looking at the 'Individual components' option in the Visual Studio Installer for VS2019 the option for 'Testing tools core features' seems to have disappeared too:</p>

<p><a href=""https://i.stack.imgur.com/JJ041.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/JJ041.png"" alt=""VS2019 installer with no test options""></a></p>

<p>These are the same options for VS2017 for comparison:
<a href=""https://i.stack.imgur.com/Nkx41.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/Nkx41.png"" alt=""VS2017 installer showing Testing tools core features option""></a></p>

<p>I know that the 'Create Unit Test' context menu option <a href=""https://stackoverflow.com/q/42876897/1879019"">is not expected to be present in VS2019</a> yet, but to my knowledge the normal unit testing functionality and templates should be there?</p>

<p>(PS: I appreciate I can just write unit tests from scratch, I'm just asking if the functionality in VS has changed)</p>
",https://stackoverflow.com/questions/55703609/unit-testing-features-missing-for-net-core-in-vs-2019-and-visual-studio-install,"['c#', 'unit-testing', '.net-core', 'mstest', 'visual-studio-2019']",5674,False,6,0
Swift Unit Testing: Checking for equality of two objects of the same class,"<p>How would you create a test function to compare the contents of two objects of the same class? </p>

<p>Background:
I have a function which extracts data from a CSV file and uses that data to create an object. I want to know if this function is generating the correct output. </p>
",https://stackoverflow.com/questions/54778359/swift-unit-testing-checking-for-equality-of-two-objects-of-the-same-class,"['ios', 'swift', 'xcode', 'unit-testing', 'testing']",1647,True,-1,2
Unable to do angular unit testing due to method call present inside constructor,"<p>Unable to run angular unit test due to method present inside component constructor.</p>

<pre><code> export class AppComponent  {
  name = 'Angular 4';
   constructor(){
    this.testMethod();
   }

   testMethod(){
         console.log(""test method"");
   }

  testMethodNonc(){
     console.log(""test method nc"");
  }
}
</code></pre>

<p>//my spec file</p>

<pre><code>describe('MyComponent', () =&gt; {
  let fixture, element;

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

    fixture = TestBed.createComponent(AppComponent);
    element = fixture.debugElement;
  })
  it('works', () =&gt; {
    fixture.detectChanges();
    expect(component.testMethodNonc()).toHaveBeenCalled();
  });
});
</code></pre>

<p>when i tried to run unit test for testMethodNonc() ,function testMethod() also running along with this method since its present inside constructor. is it possible to execute testMethodNonc() alone by mocking function testMethod?</p>
",https://stackoverflow.com/questions/54814943/unable-to-do-angular-unit-testing-due-to-method-call-present-inside-constructor,"['angular', 'karma-jasmine', 'angular-test', 'spyon']",1427,True,0,1
How do I start in doing unit testing my web component with mocha?,"<p>I am currently tasked in creating a unit test for a web-component using mocha. My first Idea is to do something like <code>document.createElement('custom-component')</code> and then check the <code>innerHTML</code> or the attribute if I want to check for correctness, but I know that I cannot do that since the document is not yet defined. Is there a way to approach this problem?</p>
",https://stackoverflow.com/questions/55931746/how-do-i-start-in-doing-unit-testing-my-web-component-with-mocha,"['javascript', 'mocha.js', 'web-component']",597,False,1,1
ABAP Unit Testing - local test class testing a code of other global class,"<p>is there a clean way to write a unit test of a productive code (especially the private methods) of global class <code>CL_A</code> from local test class <code>LCL_B</code> which is under the global test class <code>TC_B</code>? So far I have figured out a trick, which is far from clean coding practice. <code>TC_B</code> is a friend of <code>CL_A</code> and <code>LCL_B</code> is a local friend with <code>TC_B</code>. If I want to test method <code>M_A</code> of class <code>CL_A</code> I have to create extra wrapper method <code>M_B</code> in a global test class <code>TC_B</code> which calls <code>M_A</code>. See a pseudo code sample lower as this could be confusing without structured example.</p>

<p>Thanx!</p>

<hr>

<pre><code>CLASS CL_A definition global friends TC_B.
   private:
      METHODS: M_A.
</code></pre>

<hr>

<pre><code>CLASS TC_B definition for testing.
   private:
      METHODS: M_B
         IMPORTING cut TYPE REF TO CL_A.

   METHOD M_B.
      cut-&gt;M_A().
   ENDMETHOD.

CLASS LCL_B definition deferred.
CLASS TC_B definition local friends LCL_B.
CLASS LCL_B definition final for testing.
   private:
      DATA: cut TYPE REF TO CL_A.
            env TYPE REF TO TC_B.

      METHODS: test_M_A for testing,
               setup.

   METHOD setup.
      CREATE OBJECTS cut, env.
   ENDMETHOD.

   METHOD test_M_A.
      env-&gt;M_B( cut ).
   ENDMETHOD.
</code></pre>
",https://stackoverflow.com/questions/59376079/abap-unit-testing-local-test-class-testing-a-code-of-other-global-class,"['unit-testing', 'abap']",1674,True,0,1
What is the operating principle of IOS Unit Testing Bundle in Xcode 10?,"<p>please ask the operating principle of IOS Unit Testing Bundle in Xcode 10, such as how the unit test Bundle is compiled? How does the test cases execute? What is the relationship with the tested APP?</p>
",https://stackoverflow.com/questions/54059675/what-is-the-operating-principle-of-ios-unit-testing-bundle-in-xcode-10,"['unit-testing', 'xctest']",34,True,0,1
unit testing not running in vs but run fine in azure CI pipeline,"<p>I have some unit tests made with MSTest, everything was running fine locally in Visual Studio Enterprise 2019 and tests also ran fine in Azure DevOps CI build. I had to change to a new machine today with a freshly installed VS. The problem is no tests will run locally ever since I started working in this new VS environment (the tests still run fine in the CI build).</p>

<p>Can anyone tell me why this is? Am I missing some packages or so? MSTest framework/adapter etc. is installed locally of course </p>

<p>Locally in VS:</p>

<p><img src=""https://i.stack.imgur.com/LZliY.png"" alt=""6 not run""></p>

<p>Azure DevOps CI build:</p>

<p><img src=""https://i.stack.imgur.com/mm0dX.png"" alt=""total tests passed: 6""></p>
",https://stackoverflow.com/questions/59473653/unit-testing-not-running-in-vs-but-run-fine-in-azure-ci-pipeline,"['c#', 'asp.net', 'azure-devops', 'azure-pipelines', 'mstest']",338,True,0,1
Unit testing failing because of - Objects are not valid as a React child,"<p>Following is my code in which I am testing <code>mytestFunc</code> called on checkbox checked condition.</p>

<p>Checkbox -
<code>&lt;input id=""mycheck"" type=""checkbox"" onClick={this.mytestFunc} /&gt;</code></p>

<p><strong>mytestFunc</strong> function -</p>

<pre><code>mytestFunc = e =&gt; {
    const mockdata = this.state.myList
    const newArr = mockdata.map(x =&gt; e.target.checked ? {
      ...x, checked: (&lt;label className=""label""&gt;
        &lt;input type=""checkbox"" /&gt;
        &lt;span className=""checkbox"" /&gt;
      &lt;/label&gt;)
    } : {
        ...x, checked: (&lt;label className=""label""&gt;
        &lt;input type=""checkbox"" /&gt;
        &lt;span className=""checkbox"" /&gt;
      &lt;/label&gt;) })
    this.setState({ myList: newArr })
}
</code></pre>

<p>and I am testing it using jest/enzyme -</p>

<pre><code>it('test mytestFunc function', () =&gt; {
    const component = mount(&lt;MyComponent {...props} /&gt;);
    const customEvent = {
      ""target"": {
        ""checked"": true
      }
    }
    const dataList = [
      {
        ""id"": ""DS64XX123"",
        ""name"": ""test"",
        ""gender"": ""male""
    ]
    component.setState({ myList: dataList });
    component.instance().mytestFunc(customEvent);
    expect(component.state().myList).toBe(true);
  })
</code></pre>

<p>Error -</p>

<blockquote>
  <p>Invariant Violation: Objects are not valid as a React child (found:
  object with keys {$$typeof, type, key, ref, props, _owner, _store}).
  If you meant to render a collection of children, use an array instead.</p>
</blockquote>

<p>Let me know what I am doing wrong here and how to correct it.</p>
",https://stackoverflow.com/questions/56110168/unit-testing-failing-because-of-objects-are-not-valid-as-a-react-child,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",364,False,0,1
Unit Testing component that depends on RouterExtensions from &quot;nativescript-angular/router&quot; for navigation,"<p>I am writing unit test on a nativescript-angular component to test a number of things 1)Submit function for a login form and 2) router navigation/view after successful login.</p>

<p>In the component I am using <code>RouterExtensions</code> from <code>nativescript-angular/router</code> for navigation</p>

<p>In the component constructor i am initializing the component with default user credentials and passing the routerextension as an argument.</p>

<pre><code>constructor(private page: Page,private routerExtensions: RouterExtensions){
     this.page.actionBarHidden = true;
     this.user = new User();
     this.user.email = ""dennis@gmail.com"";
     this.user.password = ""password"";
 }
</code></pre>

<p>on successful logging i am  navigating the user to<code>home</code> page and the logic for that looks like this.</p>

<pre><code>    submit(){
        if (!this.user.email || !this.user.password) {
            this.alert(""Please provide both an email address and password."");
            return;
        }
        this.processing = true;
        if(this.isLoggingIn){
            this.login();
        }else{
            this.register();
        }

    }
    login() {
        console.log(this.user)
        if(this.user){
            this.processing = false;
            this.routerExtensions.navigate([""/home""], { clearHistory: true });
        }else{
            this.processing = false;
            this.alert(""Unfortunately we could not find your account."");
        }

    }

</code></pre>

<p>I am using mocha for testing and my unit test at the moment looks like this</p>

<pre><code>var reflect = require(""reflect-metadata"");
var component = require(""../app/login/login.component"");

describe(""Test for Login component"", ()=&gt;{
    var appComponent;
    beforeEach(()=&gt;{
        appComponent = new component.LoginComponent();
    });

    it(""Should Login User"", ()=&gt; {
        appComponent.submit();

        assert.equal(appComponent.user.email,""dennis@gmail.com"")
        assert.equal(appComponent.user.password,""password"")
    });

    it(""Should navigate user to home page"",()=&gt;{
        // Logic for testing that the view is home page.
    })
});

</code></pre>

<p>On running the test I get this error </p>

<pre><code>    TypeError: Cannot read property 'navigate' of undefined

</code></pre>

<p>I understand that this error is as a result of this line:
<code>this.routerExtensions.navigate([""/home""], { clearHistory: true });</code> in the <code>login()</code> method because on commenting it the test passes.</p>

<p>What I am not sure is how do I write unit test to test for both page routing and view that the user is at .How do i mock the navigation issue.Thanks</p>
",https://stackoverflow.com/questions/58519271/unit-testing-component-that-depends-on-routerextensions-from-nativescript-angul,"['angular', 'unit-testing', 'mocha.js', 'nativescript', 'nativescript-angular']",153,False,0,1
"How to trigger (matSortChange)=&quot;sortData(i, $event)&quot; for unit testing in angular app","<p>I am running unit test for an angular app. I want to manually trigger a matSortChange event and ensure a method is called upon firing this event</p>

<pre><code>&lt;table matSort (matSortChange)=""sortData(i, $event)"" matSortActive=""enddate"" matSortDirection=""asc"" matSortDisableClear style=""margin:0px;"" class=""table table-striped table-bordered""&gt;

&lt;tr&gt;
  &lt;ng-container *ngFor=""let subheader of subheaders; let j = index""&gt;
  &lt;ng-container *ngIf=""subheader[1] == 'activationid'; else second""&gt;
    &lt;th class=""headers"" style=""width:300px;"" mat-sort-header="" 
     {{subheader[1]}}""&gt;{{subheader[0]}} &lt;/th&gt;
&lt;/tr&gt;
</code></pre>
",https://stackoverflow.com/questions/55608976/how-to-trigger-matsortchange-sortdatai-event-for-unit-testing-in-angular,"['angular', 'unit-testing']",4150,False,0,2
Unit testing methods which depend on other member of the interface being called,"<p>Let's say I have an interface called <code>IOrderContainer</code>:</p>

<pre><code>public interface IOrderContainer
{
    ReadOnlyCollection&lt;Order&gt; Orders { get; }
    void AddOrder(Order order);
    void RemoveOrder(Order order);
    Order GetOrderById(int orderId);
}
</code></pre>

<p>The implementation keeps a private collection of orders, which is exposed by a public read-only collection <code>Orders</code></p>

<p><code>AddOrder</code> and <code>RemoveOrder</code> modifies the private collection.</p>

<p>How would I unit test <code>GetOrderById</code> and <code>RemoveOrder</code> methods, if there's no public members on the interface to initialize the private orders collection? </p>

<p>The obvious way is to call AddOrder a bunch of times to populate the private collection, but I feel that it violates the definition of a unit test, because to test <code>RemoveOrder</code>/<code>GetOrderById</code>, we depend on another ""unit"" - <code>AddOrder</code>.</p>

<p>Should I create two constructors? One parameterless constructor and another one that takes in the collection and assigns it to the private collection.</p>
",https://stackoverflow.com/questions/59262229/unit-testing-methods-which-depend-on-other-member-of-the-interface-being-called,"['c#', 'unit-testing']",36,True,0,1
How to perform string validation &amp; unit testing using google test in C++?,"<p>I am trying to write some string validation functions such as</p>

<ul>
<li><p>check whether <strong>the string is NULL, Empty or have only spaces!</strong></p></li>
<li><p>check whether <strong>the string is alphanumeric or uppercase!</strong></p></li>
</ul>

<p>I am only interested in strings with <strong>lowercase alphabets from a-z.(VALID strings)</strong> rest I want to block, so I have written the following functions:</p>

<pre><code>std::string isEmpty(const std::string &amp;input){
    // empty string
    if (NULL ==input || input==""\0"" || !input.size())
        return """";
}
std::string isMalfunctioned(const std::string &amp;input){
    for (int i = 0; i &lt; input.size(); ++i){
        // string is not a-z or alphanumeric or uppercase
        if ( input[i] &lt; 'a' || input[i] &gt; 'z'|| isalpha(input[i]) || isupper(input[i]) )
            return """";
    }
}
</code></pre>

<p>and from the main function, I am just calling myFunc() using a reference to the input string &amp; it calls the validation function written above to notify a user of incoming invalid strings:</p>

<pre><code>#include""myFunc.h""

std::string myFunc(const std::string &amp; input){
    if( isEmpty(input)== """")
        std::cout&lt;&lt;""Empty input""&lt;&lt; std::endl;
    if( isMalfunctioned(input)== """")
        std::cout&lt;&lt;""malfunctioned input""&lt;&lt; std::endl;
    return input;
}
int main(){
    std::string input=""1234"";
    std::cout &lt;&lt; myFunc(input)&lt;&lt; std::endl;
    return  0;
}
</code></pre>

<p><strong><em>My question:</em></strong></p>

<ul>
<li>First, I think my validation functions are not syntaticaly correct, since I am getting compile time errors as below, could anyone help in this regards?</li>
</ul>

<hr>

<pre><code>mismatched types ‘const __gnu_cxx::__normal_iterator&lt;_
Iterator, _Container&gt;’ and ‘long int’

candidate: template&lt;class _Iterator,
 class _Container&gt; bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&lt;_Iterat
or, _Container&gt;&amp;, const __gnu_cxx::__normal_iterator&lt;_Iterator, _Container&gt;&amp;)
     operator==(const __normal_iterator&lt;_Iterator, _Container&gt;&amp; __lhs,
</code></pre>

<ul>
<li><p>Second, I think, my validation functions are not fully covering my specifications. Any suggestion for it?</p></li>
<li><p>Third, I have written some test cases using google test, but unable to interface with the above functionality, Any suggestions on what I am doing wrong &amp; how to correct them? Also, any suggestion on refactoring the code is also welcomed!</p></li>
</ul>

<hr>

<pre><code>#include ""myfunc.h""
#include &lt;gtest/gtest.h&gt;

TEST(testbundle, EmptyString){
  ASSERT_EQ("""", myfunc(""""));
}

TEST(testbundle, Malfunctioned){
  ASSERT_EQ("""", myfunc(""ad34534654""));
  ASSERT_EQ("""", myfunc(""!$#sadasfd1""));
}

TEST(testbundle, LowerCase){
  ASSERT_EQ(""abbsbdbbdbdb"", myfunc(""abbsbdbbdbdb""));
}
TEST(PreliminaryTest, UpperCaseString){
  ASSERT_EQ("""", myfunc(""ASDFFGGGHH""));
}

int main(int argc, char **argv){
  testing::InitGoogleTest(&amp;argc, argv);
  return RUN_ALL_TESTS();
}
</code></pre>
",https://stackoverflow.com/questions/54468636/how-to-perform-string-validation-unit-testing-using-google-test-in-c,"['c++', 'c++11', 'googletest']",3389,False,0,0
How to perform unit testing on a void method in web api controller,"<p>Hi I have a update method in webAPI and that is a void method and I want to perform unit testing on that method.How do I do that??</p>

<p>Not Found any solution.</p>

<p>Below is webapi controller method :-</p>

<pre><code>[HttpPut]      
public void UpdatePushNotification(PushNotificationQueueBO pushnotificationqueueBO)
{
   PushNotificationQueueBO.UpdatePushNotificationQueue(pushnotificationqueueBO);
}
</code></pre>

<p>Below is the unit test case for above method</p>

<pre><code>[TestMethod]
public void UpdatePushNotificationQueue_ShouldUpdate()
{        
    var item = GetDemoPushNotificationQueue();      

    var controller = new PushNotificationQueueController();

    var result = controller.UpdatePushNotification(item) as ;

    Assert.IsNotNull(result);       
}
</code></pre>

<p>I want what do I write after as in </p>

<pre><code>var result = controller.UpdatePushNotification(item) as ???
</code></pre>
",https://stackoverflow.com/questions/57882700/how-to-perform-unit-testing-on-a-void-method-in-web-api-controller,"['asp.net-mvc', 'unit-testing', 'asp.net-web-api']",856,True,-1,2
Newbie in Unit Testing - How would you test this code using Jest Testing?,"<p>I'm a newbie in Unit Testing.
I want to learn how to test correctly using Jest and after articles, demos, and a course on Udemy, I'm still pretty confused (especially using Jest mocking).
I should mention that all our code is outside react so it seems to confuse me even more.</p>

<p>I've written an AB test for my company and already recognized it should be easy to test but I don't think I'm doing it right. It seems like I'm just copying my original code over to test and although I feel the function is validated, it seems wrong to me.</p>

<p>Here's my code in question and the test. How would you guys who have more experience do this ""right""?</p>

<p>Thanks!</p>

<p>JS:</p>

<pre><code>let ABTestValue = 30;
ABTest();

export function ABTest() {
  const roll = Math.floor(Math.random() * 100);

  if (debugMode) {
    console.log('TimedRefresh - AB Test Issue-831 (90 and above get their refresh time changed) randomized value = ', roll);
  }

  const ABTestMappings = [
    {
      roll: 90,
      ABTestValue: 40
    },
    {
      roll: 91,
      ABTestValue: 40
    },
    {
      roll: 92,
      ABTestValue: 50
    },
    {
      roll: 93,
      ABTestValue: 50
    },
    {
      roll: 94,
      ABTestValue: 60
    },
    {
      roll: 95,
      ABTestValue: 60
    },
    {
      roll: 96,
      ABTestValue: 70
    },
    {
      roll: 97,
      ABTestValue: 70
    },
    {
      roll: 98,
      ABTestValue: 80
    },
    {
      roll: 99,
      ABTestValue: 80
    }
  ];

  if (roll &gt; 89 &amp;&amp; roll &lt; 100) {
    ABTestValue = ABTestMappings.filter((a) =&gt; a.roll === roll)[0].ABTestValue;
  }

  window.rg_version = `time${ABTestValue}`;

  if (debugMode) {
    console.log('TimedRefresh - ABTestValue - change in refresh time in seconds (30 is default) - ', ABTestValue);
  }
}
</code></pre>

<p>test.js:</p>

<pre><code>import { ABTest } from './index';

describe('ABTEST test', () =&gt; {
  it('ABTest function', () =&gt; {
    expect(ABTest).toBeDefined();
  })

  describe('test different rolls', () =&gt; {
    const ABTestMappings = [
      {
        roll: 90,
        ABTestValue: 40
      },
      {
        roll: 91,
        ABTestValue: 40
      },
      {
        roll: 92,
        ABTestValue: 50
      },
      {
        roll: 93,
        ABTestValue: 50
      },
      {
        roll: 94,
        ABTestValue: 60
      },
      {
        roll: 95,
        ABTestValue: 60
      },
      {
        roll: 96,
        ABTestValue: 70
      },
      {
        roll: 97,
        ABTestValue: 70
      },
      {
        roll: 98,
        ABTestValue: 80
      },
      {
        roll: 99,
        ABTestValue: 80
      }
    ];

    const roll = 92;
    const roll2 = 95;
    const roll3 = 99;
    const roll4 = 80;
    let ABTestValue = 30;
    let ABTestValue2 = 30;
    let ABTestValue3 = 30;
    let ABTestValue4 = 30;

    if (roll &gt; 89 &amp;&amp; roll &lt; 100) {
      ABTestValue = ABTestMappings.filter((a) =&gt; a.roll === roll)[0].ABTestValue;
    }

    if (roll2 &gt; 89 &amp;&amp; roll2 &lt; 100) {
      ABTestValue2 = ABTestMappings.filter((a) =&gt; a.roll === roll2)[0].ABTestValue;
    }

    if (roll3 &gt; 89 &amp;&amp; roll3 &lt; 100) {
      ABTestValue3 = ABTestMappings.filter((a) =&gt; a.roll === roll3)[0].ABTestValue;
    }

    if (roll4 &gt; 89 &amp;&amp; roll4 &lt; 100) {
      ABTestValue4 = ABTestMappings.filter((a) =&gt; a.roll === roll4)[0].ABTestValue;
    }

    it('if roll is 92', () =&gt; {
      if (roll) {
        expect(ABTestValue).toEqual(50);
      }
    })

    it('if roll is 95', () =&gt; {
      if (roll2) {
        expect(ABTestValue2).toEqual(60);
      }
    })

    it('if roll is 99', () =&gt; {
      if (roll3) {
        expect(ABTestValue3).toEqual(80);
      }
    })

    it('if roll is less than 90', () =&gt; {
      if (roll4) {
        expect(ABTestValue4).toEqual(30);
      }
    })
  })
})
</code></pre>
",https://stackoverflow.com/questions/58258206/newbie-in-unit-testing-how-would-you-test-this-code-using-jest-testing,"['javascript', 'unit-testing', 'mocking', 'jestjs']",574,False,0,1
React.createElement: type is invalid -- expected a string warning in unit testing with enzyme,"<p>I am unit testing my react-native app. I have a login page which consist of a component and has following props passed from container component.</p>

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

<p>I am doing snapshot testing with jest and enzyme. I passed these props to Login Component like this</p>

<pre><code>import Login from ""../index"";
import React from 'react';
import { shallow } from 'enzyme';
import globalStyles from '../../../../../global/styles';

let theme = 'DefaultTheme', wrapper;

const createTestProps = (props) =&gt; ({
    navigation: {
        navigate: jest.fn()
    },
    theme: theme,
    globalStyles: globalStyles(theme),
    session: {},
    changeScene: jest.fn(),
    changeTheme: jest.fn(),
    setUser: jest.fn(),
    logout: jest.fn(),
    ...props
});
beforeEach(() =&gt; {
    const props = createTestProps({});
    console.log(JSON.stringify(props));
    wrapper = shallow(&lt;Login {...props} /&gt;);
});
test('should render login component correctly', () =&gt; {
    expect(wrapper).toMatchSnapshot();
});
</code></pre>

<p>Test passed and snapshot is created however this warning is shown in console. </p>

<blockquote>
  <p>Warning: React.createElement: type is invalid -- expected a string
  (for built-in components) or a class/function (for composite
  components) but got: object.</p>
</blockquote>

<p>I check the export type it is default one.</p>

<pre><code>export default Login
</code></pre>

<p>The global style object is a nested style object mainly consist of styles for button, text etc and it passed as a prop in every component of my app. Need help what I'm doing wrong.</p>
",https://stackoverflow.com/questions/57082779/react-createelement-type-is-invalid-expected-a-string-warning-in-unit-testin,"['reactjs', 'react-native', 'jestjs', 'enzyme']",423,False,0,0
"Java Unit Testing: Mocking method that returns a boolean not working, getting NPE","<p>This is a head-scratcher.  I have this:</p>

<pre><code>@Autowired
KafkaConsumer kafkaConsumer;
...
private void ensureKafkaConsumerIsRunning() {
    if(!kafkaConsumer.isRunning()) {
        Thread kafkaThread = new Thread(kafkaConsumer);
        synchronized(KafkaConsumer.class) {
            kafkaThread.start();
        }
    }
}
</code></pre>

<p>The test:</p>

<pre><code>@InjectMocks
private GreetingService greetingService;
...
@Mock
private KafkaConsumer kafkaConsumer;
...
@Test
public void sendToKafka_Msg_Test() throws Exception {
    RecordMetadata recordMetadata = new RecordMetadata(null, 0L,0L,0L,0L,0,0);
    when(kafkaConsumer.isRunning()).thenReturn(true);
    when(kafkaProducer.sync(anyString())).thenReturn(recordMetadata);
    assertEquals((long) greetingService.sendToKafka(""test""), 0L);
}
</code></pre>

<p>I am getting a NPE in the class under test where it reads:</p>

<pre><code>if(!kafkaConsumer.isRunning()) {
</code></pre>

<p>All isRunning() does is return a boolean 'isRunning' that is set either to true or false.  Nothing more.</p>

<p>I have tried making ensureKafkaConsumerIsRunning() public.  I have tried using Answers in the test instead of just when()s but to no avail.</p>

<p>Any ideas?</p>

<hr>

<p>UPDATE:</p>

<p>It was so obvious it went right past us all!  Simply:</p>

<pre><code>@Before
public void initMocks(){
     MockitoAnnotations.initMocks(this);
}
</code></pre>

<p>Then that was that.  It worked.</p>

<p>Thank you to all who took the time to read and answer.</p>
",https://stackoverflow.com/questions/56905632/java-unit-testing-mocking-method-that-returns-a-boolean-not-working-getting-np,"['java', 'unit-testing', 'mockito']",403,False,0,2
What is the difference between these tests ? unit testing React JS - jest / enzyme,"<p>Unable to run the following test:</p>

<p>file2.test.js both methods are listed but i am trying to test the deleteAxisByid method . The first method I already have a test case for it</p>

<pre><code> addNewAxis = (obj) =&gt; {
let localState = Object.assign({}, this.state)
localState.axis[obj.id] = obj
let updateObj = {
  0: {
    pipe: 'chart',
    action: 'transform',
    transformType: 'replaceElement',
    matchValue: 'axes',
    axes: localState.axis
  }
}
this.props.addAxisList(updateObj)
this.setState(localState)
}

 it ('Testing deleteAxisByID method: ',() =&gt; {
 const wrapper = shallow(&lt;AxisList {...baseProps } /&gt;);
let id = {test : 'test'}
wrapper.instance().deleteAxisByID(id)
expect(wrapper.instance().state.axis).toHaveProperty('test')

});
</code></pre>

<p>Here is the main code : file.js </p>

<pre><code>    deleteAxisByID = (id) =&gt; {
delete this.state.axis[id]
let updateObj = {
  0: {
    pipe: 'chart',
    action: 'transform',
    matchValue: 'axes',
    axes: this.state.axis
  }
}
this.props.addAxisList(updateObj)
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/54429189/what-is-the-difference-between-these-tests-unit-testing-react-js-jest-enzy,"['javascript', 'reactjs', 'unit-testing']",59,False,0,0
How to compare 2 lists containing json values in C# for unit testing,"<p>How to compare 2 lists in c#?
1st list data</p>

<pre><code>DBvalues = [{ ""_id"" : ObjectId(""5d98298f9110f5f13812f3c1""), ""PartName"" : null, ""MAP"" : null, ""MPN"" : null, ""IsActive"" : true, ""Gtin"" : ""ab085347019069"" }, { ""_id"" : ObjectId(""5d98298f9110f5f13812f3c0""), ""PartName"" : null, ""MAP"" : null, ""MPN"" : null, ""IsActive"" : true, ""Gtin"" : ""085347014064"" }]
</code></pre>

<p>2nd list data</p>

<pre><code>actualExcelvalues = [{ ""_id"" : ObjectId(""5d98298f9110f5f13812f3c0""), ""PartName"" : null, ""MAP"" : null, ""MPN"" : null, ""IsActive"" : true, ""Gtin"" : ""085347014064"" }, { ""_id"" : ObjectId(""5d98298f9110f5f13812f3c1""), ""PartName"" : null, ""MAP"" : null, ""MPN"" : null, ""IsActive"" : true, ""Gtin"" : ""ab085347019069"" }]
</code></pre>

<p>irrespective of their order/index.</p>
",https://stackoverflow.com/questions/58461874/how-to-compare-2-lists-containing-json-values-in-c-for-unit-testing,"['c#', 'unit-testing']",83,True,0,1
Unit testing a debounce function to see if timer times out after 500ms,"<pre><code>  export const debounce = (func: (arg?: any) =&gt; void, timeOut: number = 500) =&gt; {
      let timer: ReturnType&lt;typeof setTimeout&gt;;
      return function(...args: any) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(func, timeOut, ...args);
      };
    };
</code></pre>

<p>I am trying to create a simple test for this debounce function. How do i begin this? </p>
",https://stackoverflow.com/questions/58396972/unit-testing-a-debounce-function-to-see-if-timer-times-out-after-500ms,"['javascript', 'jestjs']",363,False,0,1
Inject dependency of mock service object in play controller while unit testing it,"<p>I have a controller which looks like </p>

<pre><code>class MyController @Inject()(service: MyService,
                                 cc: MessagesControllerComponents
                     )(implicit ec: ExecutionContext)
  extends MessagesAbstractController(cc) {

def getAll ....// all methods of controller
</code></pre>

<p>Now, I am trying to unit test the controller using Mockito and Scalatest where I am trying to inject the mocked object of MyService in unit test. My unit test is as follows</p>

<pre><code>class MyControllerTest extends PlaySpec with GuiceOneAppPerSuite {

  ""MyController"" should {

    def fakeApplication(): Application = new GuiceApplicationBuilder().build()

    ""not return 404"" when {
      ""we try to hit the route /ads"" in {
        val fakeRequest = FakeRequest(GET, ""/ads"")
        val futureResult: Future[Result] = route(fakeApplication, fakeRequest).get
        val resultJson: JsValue = contentAsJson(futureResult)(Timeout(2, TimeUnit.SECONDS))
        resultJson.toString mustBe """"""{""status"":""success""}""""""
      }
    }
  }
}
</code></pre>

<p>Now to unit test the controller, I need to pass in the mock of the service in the controller while building it via guice. I tried the following method to inject the mocked dependency in controller,</p>

<pre><code>val application = new GuiceApplicationBuilder()
  .overrides(bind[MyService])
  .build
</code></pre>

<p>However, it fails to inject the mocked service object. Any pointers on where I am going wrong will be highly appreciated. Thanks in advance.</p>
",https://stackoverflow.com/questions/54112358/inject-dependency-of-mock-service-object-in-play-controller-while-unit-testing-i,"['scala', 'playframework', 'mockito', 'guice', 'scalatest']",1267,True,0,1
Unit Testing xunit The following constructor parameters did not have matching fixture data,"<p>The following constructor parameters did not have matching fixture data for unit testing using moq and xunit. </p>

<p>Already using dependency injection and mock to test the class. </p>

<pre><code>//this is how i register the DI.
services.AddScoped&lt;IWaktuSolatServiceApi, WaktuSolatServiceApi&gt;(); 


 public interface IWaktuSolatServiceApi
 {
    Task&lt;Solat&gt; GetAsyncSet();
 }


// the unit test. 
public class UnitTest1 
{
    Mock&lt;IWaktuSolatServiceApi&gt; waktu;

    public UnitTest1(IWaktuSolatServiceApi waktu)
    {
        this.waktu = new Mock&lt;IWaktuSolatServiceApi&gt;();
    }

    [Fact]
    public async Task ShoudReturn()
    {
        var request = new Solat
        {
            zone = ""lala""
        };

        var response = waktu.Setup(x =&gt; 
        x.GetAsyncSet()).Returns(Task.FromResult(request));
    }
}
</code></pre>

<p>But i got this error The following constructor parameters did not have matching fixture data.</p>
",https://stackoverflow.com/questions/56754176/unit-testing-xunit-the-following-constructor-parameters-did-not-have-matching-fi,"['c#', 'testing', 'moq', 'xunit']",7721,True,-1,1
"Error: InvalidPipeArgument: &#39;function () { return fn.apply(this, arguments); }&#39; for pipe &#39;AsyncPipe&#39; Angular 7 Unit testing","<p>I'm writing unit test cases in Angular 7 in this process got stuck to create unit
test for a service variable 'isLoading'.</p>

<p>here is my app component html file:</p>

<pre><code>&lt;router-outlet&gt;&lt;/router-outlet&gt;


&lt;div *ngIf=""guestUserService.isLoading | async""  class=""loaderdiv""&gt;
  &lt;mat-spinner class=""loader""&gt;&lt;/mat-spinner&gt;
&lt;/div&gt; 
</code></pre>

<p>The service file:</p>

<pre><code>export class GuestUserService {

  public isLoading: any = new BehaviorSubject(false);

}
</code></pre>

<p>The unit test case:</p>

<pre><code> fdescribe('AppComponent', () =&gt; {
         let guestUserService: any;
         let guestUserServiceSpy: any;

          beforeEach(async(() =&gt; {
            guestUserService = jasmine.createSpyObj('GuestUserService', ['isLoading']);
            TestBed.configureTestingModule({
              providers: [
                { provide: GuestUserService, useValue: guestUserService }]
            }).compileComponents();
}));

 it('should render loader if isLoading true', () =&gt; {
    guestUserServiceSpy = guestUserService.isLoading.and.returnValue(true);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(guestUserService).toBeDefined();
    expect(guestUserServiceSpy).toBeDefined();
    expect(guestUserService.isLoading).toBeTruthy();
    expect(fixture.debugElement.query(By.css('.loader'))).toBeDefined();
    expect(compiled.querySelector('mat-spinner')).toBeTruthy();
  });
</code></pre>

<p>Getting error:</p>

<blockquote>
  <p>Error: InvalidPipeArgument: 'function () { return fn.apply(this,
  arguments); }' for pipe 'AsyncPipe'</p>
</blockquote>

<p>Is there any proper way to create unit test case for this type of scenarios.</p>
",https://stackoverflow.com/questions/56866208/error-invalidpipeargument-function-return-fn-applythis-arguments,"['angular', 'typescript', 'unit-testing', 'karma-jasmine']",2498,True,5,2
How to check which option is selected in mat-select angular 8 unit testing,"<pre><code>it( 'Should set the initial value for test dropdown', async () =&gt; {
    let testDropdown : HTMLElement;
    const debugElement : DebugElement = fixture.debugElement;
    fixture.detectChanges();
    testDropdown = debugElement.queryAll( By.css( 'mat-select' ) )[ 0 ].nativeElement;
    expect( testDropdown ).toBeTruthy();
// How to get the selected value from the mat-select, like below code, which is not working
    console.log( testDropdown.children[ 0 ].innerHTML ); 
} );
</code></pre>

<p>In the HTML template, I am setting the default value for mat-select while looping options. How to get that selected value in unit testing</p>
",https://stackoverflow.com/questions/57451260/how-to-check-which-option-is-selected-in-mat-select-angular-8-unit-testing,"['angular', 'unit-testing', 'typescript2.0']",6119,False,3,2
How can I test a method call inside an asynchronous operation in unit testing,"<p>I have a method that first performs a series of actions, after which it starts an asynchronous task. I want to test this method, but I don’t understand how I can verify that the asynchronous operation has completed.</p>

<p>Using Moсkito, I want to verify that the <em>foo</em> method was executed 2 times, once before the start of the asynchronous task and once inside it. The problem is that at the time of the Mockito check the asynchronous task might not yet call the method inside the asynchronous operation. Therefore, the test is sometimes performed, and sometimes not.</p>

<p>This is the example of my method:</p>

<pre><code>void testingMethod() {
    // some operations
    someObject.foo();
    CompletableFuture.runAsync(() -&gt; {
        // some other operations
        someObject.foo();
    });
}
</code></pre>

<p>And example of my test where someObject is mocked:</p>

<pre><code>@Test
public void testingMethodTest() {
    testObject.testingMethod();

    Mockito.verify(someObject, Mockito.times(2)).foo();
}
</code></pre>

<p>Is there a way to wait for an asynchronous operation to complete before the verify method. Or is this a bad way to test and what can you advise in this case?</p>
",https://stackoverflow.com/questions/58520164/how-can-i-test-a-method-call-inside-an-asynchronous-operation-in-unit-testing,"['java', 'asynchronous', 'mockito', 'junit5', 'completable-future']",5023,True,3,3
Asynchronously unit testing a Sanic app throws RuntimeError: this event loop is already running,"<p>I have a Sanic app that makes some async calls to an external api. I wish to write some unit tests which mock these external calls.</p>

<p>In the code below the tests do pass as we can see from the logs. However after they have completed a RuntimeError: this event loop is already running is thrown</p>

<p>Simplified Sanic app:</p>

<pre><code>app = Sanic(__name__)
app.config.from_pyfile('/usr/src/app/config.py')
Initialize(
    app,
    access_token_name='jwt',
    authenticate=lambda: True,
    claim_aud=app.config.AUTH_JWT_TOKEN['service']['audience'],
    claim_iss=app.config.AUTH_JWT_TOKEN['service']['issuer'],
    public_key=app.config.AUTH_JWT_TOKEN['service']['secret'],
    responses_class=JWTResponses
)


@app.listener('before_server_start')
def init(app, loop):
    ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    ssl_ctx.load_cert_chain(app.config.SSL_CERT, app.config.SSL_CERT_KEY)
    ssl_ctx.load_verify_locations(app.config.SSL_SERVER_CERT)
    ssl_ctx.check_hostname = False
    ssl_ctx.verify_mode = ssl.CERT_REQUIRED
    conn = aiohttp.TCPConnector(ssl_context=ssl_ctx)
    app.aiohttp_session = aiohttp.ClientSession(loop=loop, connector=conn)
    access_logger.disabled = True


@app.listener('after_server_stop')
def finish(app, loop):
    loop.run_until_complete(app.aiohttp_session.close())
    loop.close()


@app.route(""endpoint/&lt;mpn&gt;"")
@protected()
async def endpoint(request, mpn):
    msg = msg(
        mpn,
    )
    headers = {'content-type': 'text/xml'}
    async with session.post(
        config.URL,
        data=msg.tostring(pretty_print=True, encoding='utf-8'),
        headers=headers,
    ) as response:
        response_text = await response.text()
        try:
            response = (
                Response.from_xml(response_text)
            )
            return response
        except ResponseException:
            logger.error(e.get_message()['errors'][0]['message'])
            return response.json(
                e.get_message(),
                status=HTTPStatus.INTERNAL_SERVER_ERROR
            )


if __name__ == '__main__':
    app.run(host=""0.0.0.0"", port=8000)
</code></pre>

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

<pre><code>from server import app as sanic_app


@pytest.yield_fixture
def app():
    app = sanic_app
    yield app


@pytest.fixture
def test_cli(loop, app, sanic_client):
    return loop.run_until_complete(sanic_client(app))


token = jwt.encode(
    {
        ""iss"": (
            sanic_app.config.AUTH_JWT_TOKEN['service']
            ['issuer']
        ),
        ""aud"": (
            sanic_app.config.AUTH_JWT_TOKEN['service']
            ['audience']
        ),
        ""exp"": datetime.datetime.utcnow() + datetime.timedelta(
            seconds=int(100)
        )
    },
    sanic_app.config.AUTH_JWT_TOKEN['service']['secret'],
    algorithm='HS256'
).decode('utf-8')
token = 'Bearer ' + token


async def test_success(test_cli):
    with aioresponses(passthrough=['http://127.0.0.1:']) as m:
        with open('tests/data/summary.xml') as f:
            data = f.read()
        m.post(
            'https://external_api',
            status=200,
            body=data
        )
        resp = await test_cli.get(
            'endpoint/07000000000',
            headers={""Authorization"": token}
        )
        assert resp.status == 200
        resp_json = await resp.json()
        assert resp_json == {SOME_JSON}
</code></pre>

<p>As mentioned above the test does pass but then the error is thrown. </p>

<pre><code>================================================================================================= ERRORS ==================================================================================================
____________________________________________________________________________________ ERROR at teardown of test_success ____________________________________________________________________________________

tp = &lt;class 'RuntimeError'&gt;, value = None, tb = None

    def reraise(tp, value, tb=None):
        try:
            if value is None:
                value = tp()
            if value.__traceback__ is not tb:
                raise value.with_traceback(tb)
&gt;           raise value
/usr/local/lib/python3.6/site-packages/six.py:693:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/local/lib/python3.6/site-packages/six.py:693: in reraise
    raise value
/usr/local/lib/python3.6/site-packages/six.py:693: in reraise
    raise value
/usr/local/lib/python3.6/site-packages/pytest_sanic/plugin.py:212: in sanic_client
    loop.run_until_complete(client.close())
uvloop/loop.pyx:1451: in uvloop.loop.Loop.run_until_complete
    ???
/usr/local/lib/python3.6/site-packages/pytest_sanic/utils.py:230: in close
    await self._server.close()
/usr/local/lib/python3.6/site-packages/pytest_sanic/utils.py:134: in close
    await trigger_events(self.after_server_stop, self.loop)
/usr/local/lib/python3.6/site-packages/pytest_sanic/utils.py:25: in trigger_events
    result = event(loop)
server.py:84: in finish
    loop.run_until_complete(app.aiohttp_session.close())
uvloop/loop.pyx:1445: in uvloop.loop.Loop.run_until_complete
    ???
uvloop/loop.pyx:1438: in uvloop.loop.Loop.run_until_complete
    ???
uvloop/loop.pyx:1347: in uvloop.loop.Loop.run_forever
    ???
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

&gt;   ???
E   RuntimeError: this event loop is already running.

uvloop/loop.pyx:448: RuntimeError
</code></pre>

<p>Any help or suggestions is greatly appreciated. Thanks in advance</p>
",https://stackoverflow.com/questions/56594314/asynchronously-unit-testing-a-sanic-app-throws-runtimeerror-this-event-loop-is,"['python', 'asynchronous', 'pytest', 'aiohttp', 'sanic']",2495,True,2,2
Asynchronously unit testing a Sanic app throws RuntimeError: this event loop is already running,"<p>I have a Sanic app that makes some async calls to an external api. I wish to write some unit tests which mock these external calls.</p>

<p>In the code below the tests do pass as we can see from the logs. However after they have completed a RuntimeError: this event loop is already running is thrown</p>

<p>Simplified Sanic app:</p>

<pre><code>app = Sanic(__name__)
app.config.from_pyfile('/usr/src/app/config.py')
Initialize(
    app,
    access_token_name='jwt',
    authenticate=lambda: True,
    claim_aud=app.config.AUTH_JWT_TOKEN['service']['audience'],
    claim_iss=app.config.AUTH_JWT_TOKEN['service']['issuer'],
    public_key=app.config.AUTH_JWT_TOKEN['service']['secret'],
    responses_class=JWTResponses
)


@app.listener('before_server_start')
def init(app, loop):
    ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    ssl_ctx.load_cert_chain(app.config.SSL_CERT, app.config.SSL_CERT_KEY)
    ssl_ctx.load_verify_locations(app.config.SSL_SERVER_CERT)
    ssl_ctx.check_hostname = False
    ssl_ctx.verify_mode = ssl.CERT_REQUIRED
    conn = aiohttp.TCPConnector(ssl_context=ssl_ctx)
    app.aiohttp_session = aiohttp.ClientSession(loop=loop, connector=conn)
    access_logger.disabled = True


@app.listener('after_server_stop')
def finish(app, loop):
    loop.run_until_complete(app.aiohttp_session.close())
    loop.close()


@app.route(""endpoint/&lt;mpn&gt;"")
@protected()
async def endpoint(request, mpn):
    msg = msg(
        mpn,
    )
    headers = {'content-type': 'text/xml'}
    async with session.post(
        config.URL,
        data=msg.tostring(pretty_print=True, encoding='utf-8'),
        headers=headers,
    ) as response:
        response_text = await response.text()
        try:
            response = (
                Response.from_xml(response_text)
            )
            return response
        except ResponseException:
            logger.error(e.get_message()['errors'][0]['message'])
            return response.json(
                e.get_message(),
                status=HTTPStatus.INTERNAL_SERVER_ERROR
            )


if __name__ == '__main__':
    app.run(host=""0.0.0.0"", port=8000)
</code></pre>

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

<pre><code>from server import app as sanic_app


@pytest.yield_fixture
def app():
    app = sanic_app
    yield app


@pytest.fixture
def test_cli(loop, app, sanic_client):
    return loop.run_until_complete(sanic_client(app))


token = jwt.encode(
    {
        ""iss"": (
            sanic_app.config.AUTH_JWT_TOKEN['service']
            ['issuer']
        ),
        ""aud"": (
            sanic_app.config.AUTH_JWT_TOKEN['service']
            ['audience']
        ),
        ""exp"": datetime.datetime.utcnow() + datetime.timedelta(
            seconds=int(100)
        )
    },
    sanic_app.config.AUTH_JWT_TOKEN['service']['secret'],
    algorithm='HS256'
).decode('utf-8')
token = 'Bearer ' + token


async def test_success(test_cli):
    with aioresponses(passthrough=['http://127.0.0.1:']) as m:
        with open('tests/data/summary.xml') as f:
            data = f.read()
        m.post(
            'https://external_api',
            status=200,
            body=data
        )
        resp = await test_cli.get(
            'endpoint/07000000000',
            headers={""Authorization"": token}
        )
        assert resp.status == 200
        resp_json = await resp.json()
        assert resp_json == {SOME_JSON}
</code></pre>

<p>As mentioned above the test does pass but then the error is thrown. </p>

<pre><code>================================================================================================= ERRORS ==================================================================================================
____________________________________________________________________________________ ERROR at teardown of test_success ____________________________________________________________________________________

tp = &lt;class 'RuntimeError'&gt;, value = None, tb = None

    def reraise(tp, value, tb=None):
        try:
            if value is None:
                value = tp()
            if value.__traceback__ is not tb:
                raise value.with_traceback(tb)
&gt;           raise value
/usr/local/lib/python3.6/site-packages/six.py:693:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/usr/local/lib/python3.6/site-packages/six.py:693: in reraise
    raise value
/usr/local/lib/python3.6/site-packages/six.py:693: in reraise
    raise value
/usr/local/lib/python3.6/site-packages/pytest_sanic/plugin.py:212: in sanic_client
    loop.run_until_complete(client.close())
uvloop/loop.pyx:1451: in uvloop.loop.Loop.run_until_complete
    ???
/usr/local/lib/python3.6/site-packages/pytest_sanic/utils.py:230: in close
    await self._server.close()
/usr/local/lib/python3.6/site-packages/pytest_sanic/utils.py:134: in close
    await trigger_events(self.after_server_stop, self.loop)
/usr/local/lib/python3.6/site-packages/pytest_sanic/utils.py:25: in trigger_events
    result = event(loop)
server.py:84: in finish
    loop.run_until_complete(app.aiohttp_session.close())
uvloop/loop.pyx:1445: in uvloop.loop.Loop.run_until_complete
    ???
uvloop/loop.pyx:1438: in uvloop.loop.Loop.run_until_complete
    ???
uvloop/loop.pyx:1347: in uvloop.loop.Loop.run_forever
    ???
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

&gt;   ???
E   RuntimeError: this event loop is already running.

uvloop/loop.pyx:448: RuntimeError
</code></pre>

<p>Any help or suggestions is greatly appreciated. Thanks in advance</p>
",https://stackoverflow.com/questions/56594314/asynchronously-unit-testing-a-sanic-app-throws-runtimeerror-this-event-loop-is,"['python', 'asynchronous', 'pytest', 'aiohttp', 'sanic']",2495,True,2,2
Django unable to create tables for unit testing after upgrade from 1.8 to 2.2.4,"<p>After a successful upgrade from Django 1.8 to Django 2.2.4, when 
I run the tests it fails because Django does not create the database tables.</p>

<p>My test_settings.py file was working appropriately before the upgrade.</p>

<p>after debugging the Django db/backends it looks like the connection was created, but the tables were not. 
my suspicion is that test_setting.py is not configured well, although I copied everything from the setting.py file except the database configuration (that remained SQLite).</p>

<p>database configuration:</p>

<pre><code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'test_database'
    }
}
</code></pre>

<pre><code>INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'my_app',
    'mptt',
    'corsheaders',
    # audit app
    'easyaudit',
    'kronos',
    'django.contrib.admin',
]
</code></pre>

<p>The traceback that I'm getting (here it's, for example, the auth_user, but it reproduces for all the tables the same way):</p>

<pre><code>Traceback (most recent call last):
  File ""C:\Users\owner\Desktop\workspace\my_project\MyProject\services\tests\test_logging.py"", line 33, in setUpClass
    cls.user = User.objects.get_or_create(username='logging_test_user', password='test_password')
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\manager.py"", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\query.py"", line 538, in get_or_create
    return self.get(**kwargs), False
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\query.py"", line 402, in get
    num = len(clone)
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\query.py"", line 256, in __len__
    self._fetch_all()
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\query.py"", line 1242, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\query.py"", line 55, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\models\sql\compiler.py"", line 1100, in execute_sql
    cursor.execute(sql, params)
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\backends\utils.py"", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\backends\utils.py"", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\backends\utils.py"", line 84, in _execute
    return self.cursor.execute(sql, params)
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\utils.py"", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\backends\utils.py"", line 84, in _execute
    return self.cursor.execute(sql, params)
  File ""C:\Users\owner\Desktop\workspace\my_project\venv36\lib\site-packages\django\db\backends\sqlite3\base.py"", line 383, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: auth_user
</code></pre>

<p>The tests getting executed with the environment variables of </p>

<pre><code>DJANGO_SETTINGS_MODULE=MyProject.test_settings
</code></pre>
",https://stackoverflow.com/questions/57773274/django-unable-to-create-tables-for-unit-testing-after-upgrade-from-1-8-to-2-2-4,"['django', 'django-models', 'django-testing', 'django-settings', 'django-2.2']",614,True,2,2
"Jasmine unit testing, how do I trigger the click event of ngx-modal-dialog","<p>I am working on an angular application and i am Unit testing the application using Jasmine.</p>

<p>The application uses <code>ngx-modal-dialog</code>(<a href=""https://www.npmjs.com/package/ngx-modal-dialog"" rel=""nofollow noreferrer"">enter link description here</a>) plugin for Pop-up Dialog Box such as a a confirmation box as a dynamic component.</p>

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

<p>What i want is to trigger the click event for the confirm or cancel, whatever the user chooses.</p>

<p>The code for the Pop-up Dialog box is as below:</p>

<pre><code>export class SomeComponent {

constructor(private modalService: ModalDialogService) {}
cancleEditConfirmDialog() {
   this.modalService.openDialog(this.viewRef, {
   title: 'Discard Changes ',
   childComponent: SimpleModalComponent,
   data: {
     text: 'Changes will not be saved. Do you want to proceed?'
   },
   settings: {
     closeButtonClass: 'close theme-icon-close'
   },
   actionButtons: [
     {
       text: 'Discard',
       buttonClass: 'btn btn-success',
       onAction: () =&gt; new Promise((resolve: any) =&gt; {
         // invoke delete
         // do something such as discard changes
         resolve()
       })
     },
     {
       text: 'Cancel',
       buttonClass: 'btn btn-danger',
       onAction: () =&gt; new Promise((resolve: any) =&gt; {
         // cancel and close popup
         setTimeout(() =&gt; {
           resolve();
         }, 20);
       })
     }
   ]
 });
}
}
</code></pre>

<blockquote>
  <p>how do i trigger the <code>onAction: =&gt; ()</code> in the click event for discard button
  and for cancel button.</p>
</blockquote>

<p><a href=""https://i.stack.imgur.com/e46xC.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/e46xC.png"" alt=""enter image description here""></a>
<a href=""https://i.stack.imgur.com/UJQSS.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/UJQSS.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/54939326/jasmine-unit-testing-how-do-i-trigger-the-click-event-of-ngx-modal-dialog,"['javascript', 'angular', 'unit-testing', 'jasmine', 'jasmine-jquery']",7373,True,2,1
Is it still &quot;unit testing&quot; if you&#39;re using React Testing Library / Enzyme&#39;s mount function?,"<p>We're currently unit testing our React application with Enzyme's shallow render function. Every component is tested in isolation so I understand why this is called ""unit testing"". </p>

<p>We're moving towards rendering the component and it's children. You can do this with Enzyme's mount function or with React Testing Library as it never shallow renders. This also means we have to mock Redux if it's a connected component. </p>

<p>What is the name for this type of testing? I've heard it called ""integration testing"", but when I say this at work people think that I mean something else. Is it still a type of ""unit testing"" despite the fact that multiple components are tested together? </p>
",https://stackoverflow.com/questions/57091857/is-it-still-unit-testing-if-youre-using-react-testing-library-enzymes-moun,"['reactjs', 'testing']",1416,True,2,2
Angular unit testing access component&#39;s DOM element conditioned by *ngif after updating the model,"<p>I am setting up unit test case for emit event set to table row selection(or click) operation, also I have configured the component with needed data. Here the table is another component, and even upon assigning the needed data it doesn't renders the needed DOM element of table(i.e row elements) to target  the row element for querySelect. I am adding the code snippet here:</p>

<p>component: Typescript </p>

<pre><code>@Component({
   selector: 'app-user-list',
   templateUrl: './user-list.component.html',
   changeDetection: ChangeDetectionStrategy.OnPush
})

export class UserListComponent implements OnChanges {

   @Input() userSearchResult:UserSearchResult;
   @Output() navigateToUser: EventEmitter&lt;UserInfo&gt; = new EventEmitter();

   navigateToUserInfo(selectedUser: any) {
       this.navigateToUser.emit(selectedUser);
   }
}
</code></pre>

<p>component: Markup</p>

<pre><code>&lt;div *ngIf=""userSearchResult""&gt;
   &lt;div class=""vdl-row""&gt;
   &lt;div class=""vdl-col-md-12""&gt;
   &lt;app-table [headers]=""userSearchResult.columnNames""
              [dataset]=""userSearchResult.userList""
              tableStyle=""list"" (tableRowClick) = ""navigateToUserInfo($event)""&gt;
  &lt;/app-table&gt;
 &lt;/div&gt;
&lt;/div&gt;
</code></pre>

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

<pre><code>import { ComponentFixture, async, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { TextboxComponent } from '@axyz/components/textbox';
import { UserListComponent } from './user-list.component';
import { UserSearchResult } from '../../../shared/models/user-search-result.model';
beforeEach(async( () =&gt; {
TestBed.configureTestingModule({
  imports: [],
  schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA],
  declarations: [UserListComponent],
  providers: [TextboxComponent]
  }).compileComponents();
}))
beforeEach(() =&gt; {
fixture = TestBed.overrideComponent(UserListComponent, {
  set: new Component({
    selector: 'app-user-list',
    templateUrl: './user-list.component.html',
    changeDetection: ChangeDetectionStrategy.Default
  })
}).createComponent(UserListComponent);
//fixture = TestBed.createComponent(UserListComponent);
component = fixture.componentInstance;
debugEle = fixture.debugElement;

it('should emit on click', fakeAsync(() =&gt; {
    debugger;
    let data;
    fixture.detectChanges();

    let spy = spyOn(component.navigateToUser, 'emit');
    console.log(""1"")

    console.log(debugEle.nativeElement);

    component.userSearchResult = userSearchResult; 
    fixture.detectChanges();
    // console.log(""2"")
    console.log(debugEle.nativeElement);

    debugEle.query(By.css('app- 
    table')).triggerEventHandler('click',selectedUser);

    component.navigateToUserInfo(selectedUser);
    expect(spy).toHaveBeenCalledWith(selectedUser);
  }));
 });
</code></pre>

<p>And with that ever that I have tried, I get this error in the console when I use ""overrideComponent"" </p>

<p>Uncaught Error: Cannot find module 'tslib'
    at webpackEmptyContext (./node_modules/@angular/compiler/src_sync?:2)
    at eval (:9876/node_modules/@angular/compiler/src/core.js?:22)
    at eval (:9876/node_modules/@angular/compiler/src/core.js?:10)
    at eval (:9876/node_modules/@angular/compiler/src/core.js?:19)
    at Object../node_modules/@angular/compiler/src/core.js (vendor.js:46)
    at <strong>webpack_require</strong> (main.js:79)
    at eval (:9876/src/user-search/components/user-list/user-list.component.spec.ts?:7)
    at Object../src/user-search/components/user-list/user-list.component.spec.ts (main.js:231)
    at <strong>webpack_require</strong> (main.js:79)
    at webpackContext (./src_sync_.spec.ts$?:9)</p>

<p>I have even installed tslib in my project, cleared nodemodules and did npm install, Is there anything that I am not doing right?</p>
",https://stackoverflow.com/questions/55965301/angular-unit-testing-access-components-dom-element-conditioned-by-ngif-after-u,"['angular', 'typescript', 'karma-jasmine', 'angular2-changedetection']",3046,False,2,1
Django unit testing - is it possible to specify a mime-type for file upload?,"<p>I have a Django (1.11) site that allows media file uploads. I have some basic checking against mime types (eg. to just accept 'video/m4v' files).</p>

<p>This checking works fine when I use the site on my browser (through the web UI) - running through <code>python manage.py runserver</code>.</p>

<p>I'm now writing some unit tests, but am finding that whatever file type I post, it's always picked up as an application/octet-stream mime type.</p>

<p>My unit test code is as follows:</p>

<pre><code>media_file = open('sample_video.m4v','rb') 
self.client.login(username='admin', password='password')
response = self.client.post(reverse('oppia_av_upload'), {'media_file': media_file })
self.assertEqual(response.status_code, 200)
</code></pre>

<p>In the self.client.post command, is there a way I can specify the mime type so that it's picked up correctly?</p>

<p>For info, I'm aware that mime types can be 'fiddled' with, so it won't be a guarantee that the file is of the type it claims.</p>

<p>Any help much appreciated.</p>

<p><strong>Edit:</strong>
Just to include the file upload checking code in the form validation, in case there is something I'm doing incorrectly here:</p>

<pre><code>def clean(self):
        cleaned_data = super(UploadMediaForm, self).clean()
        media_file = cleaned_data.get(""media_file"")
        print(media_file.content_type)
        if media_file is not None and media_file.content_type not in settings.OPPIA_MEDIA_FILE_TYPES:
            raise forms.ValidationError(_(u""You may only upload a media file which is one of the following types: %s"" % ', '.join(settings.OPPIA_MEDIA_FILE_TYPES)))
</code></pre>
",https://stackoverflow.com/questions/54366621/django-unit-testing-is-it-possible-to-specify-a-mime-type-for-file-upload,"['django', 'unit-testing', 'mime-types']",915,True,1,1
PHP Unit Testing -- Is this overly mocked? -- Public method loops/calls other public method,"<p>FUNCTIONALITY</p>

<p>I have a Laravel project in which I have extended <code>Illuminate\Database\Eloquent\Builder</code> as an <code>AbstractSearch</code> class to introduce a <code>params()</code> method that calls the abstract method <code>applyParams()</code> to be defined when <code>AbstractSearch</code> is extended.</p>

<p>Example:</p>

<pre><code>$models = (new ModelSearch)
    -&gt;params(['name' =&gt; 'Model', 'createdBefore' =&gt; now()])
    -&gt;with(['modelCategory', 'modelType'])
    -&gt;paginate();
</code></pre>

<p><code>applyParams()</code> is responsible for taking the array parameter from <code>params()</code> and properly constructing the underlying <code>Illuminate\Database\Query\Builder</code> query.</p>

<p>The <code>AbstractSearch</code> class allows casting of these parameters via a protected <code>$casts</code> attribute and a <code>castParams(array $params = [])</code> method.</p>

<p><code>castParams()</code> loops through the protected <code>$casts</code> attribute and calls <code>$this-&gt;castParam($params, $field, $cast)</code> for each element.</p>

<p>Right now, both <code>castParams()</code> and <code>castParam()</code> are public methods, even though the likelihood of <code>castParam()</code> ever being called that way is practically zero.</p>

<p>Relevent excerpt from <code>AbstractSearch</code>:</p>

<pre><code>public function params(array $params = [])
{
    return $this-&gt;applyParams(
        $this-&gt;prepareParams($params)
    );
}

abstract function applyParams(array $params = []);

public function prepareParams(array $params = []) : array
{
    return $this-&gt;castParams(
        $this-&gt;applyDefaults($params)
    );
}

public function applyDefaults(array $params = []) : array
{
    foreach ($this-&gt;defaults as $field =&gt; $value) {
        data_fill($params, $field, $value);
    }

    return $params;
}

public function getCasts()
{
    return $this-&gt;casts;
}

public function castParams(array $params = []) : array
{
    foreach ($this-&gt;getCasts() as $field =&gt; $cast) {
        $this-&gt;castParam($params, $field, $cast);
    }

    return $params;
}

public function castParam(&amp;$params, $field, $cast)
{
    if (! isset($params[$field])) {
        return;
    }

    switch ($cast) {
        case 'date':
        case 'datetime':
            if (! $params[$field] instanceof Carbon) {
                $params[$field] = Carbon::parse($params[$field]);
            }
            break;

        default:
            break;
    }
}
</code></pre>

<p>TESTING</p>

<p>I have unit tests in place for both methods. The bulk of the testing is done on <code>castParam()</code> to ensure that casting is done properly.</p>

<p>The unit test for <code>castParams()</code> is done with a partial mock of the <code>AbstractSearch</code> class that expects various calls to <code>castParam()</code>.</p>

<p>QUESTIONS</p>

<p>I recently re-read some unit testing principles that made me question this class's setup. You can see from the excerpt above that there are a lot of public methods that should probably be protected. In fact, the only method that <em>needs</em> to be public is <code>params()</code>.</p>

<p>It logically follows that <code>params()</code> should be the only public method; however, <code>params()</code> relies on the abstract method <code>applyParams()</code> so any test of <code>params()</code> would have to be done on the extending class because the results rely on what <code>applyParams()</code> does.</p>

<p>So... </p>

<ol>
<li><p>Have I talked myself to the right spot with the above two paragraphs? It sounds right to me, but it would involve testing that <code>params()</code> returns an instance of <code>Illuminate\Database\Eloquent\Builder</code> and that the expected changes were made to the Builder's underlying <code>Illuminate\Database\Query\Builder</code> and its query. I'm not entirely sure that's even possible.</p></li>
<li><p>Going back to <code>castParams()</code> and the partial mock's expectations that it will call <code>castParam()</code> several times. If both <code>castParams()</code> and <code>castParam()</code> remain public methods <em>and</em> if testing should focus on observable behavior, won't I have redundant tests if I test both? Or is it generally acceptable to mock the <code>castParam()</code> calls in my <code>castParams()</code> test since <code>castParam()</code> will be thoroughly tested? (EDIT: This question also applies generally to any public method that calls other public methods.)</p></li>
</ol>
",https://stackoverflow.com/questions/57226026/php-unit-testing-is-this-overly-mocked-public-method-loops-calls-other-pu,"['php', 'laravel', 'testing', 'phpunit', 'laravel-query-builder']",133,False,1,0
How to fix &quot;Module is not available!&quot; when unit testing a Hybrid Angular app,"<p>I have a hybrid angular app and unit testing with Karma-Jasmine but we hit a small problem. I have a factory and component that is downgraded as an AngularJS app with:</p>

<pre><code>angular
    .module('app.admin.branding')
    .factory('brandingFactory', downgradeInjectable(BrandingFactory));

</code></pre>

<pre><code>angular
    .module('app.admin.branding')
    .directive('BrandNameComponent', downgradeComponent({
        component: BrandNameComponent
    }));
</code></pre>

<p>but it returns a <code>Module 'app.admin.branding' is not available!</code> upon running <code>ng test</code></p>

<p>so the solution was adding brackets.</p>

<pre><code>angular
    .module('app.admin.branding', [])
</code></pre>

<p>for both the component and factory. It works and the unit tests runs but when running on the browser and navigates to a page where the component is used an unknown error occurs and redirected to the main page. </p>

<p>So we just removed the brackets for both classes as it affected our production app. How do we fix our unit test error <code>Module 'app.admin.branding' is not available</code> or is there any workaround with the brackets approach so that it won't redirect?</p>
",https://stackoverflow.com/questions/57648602/how-to-fix-module-is-not-available-when-unit-testing-a-hybrid-angular-app,"['javascript', 'angularjs', 'angular', 'jasmine', 'karma-jasmine']",1138,False,1,2
Relationship between Unit Testing &amp; End-to-End (Integration per se) while following BDD,"<p>My question is also related to who does what in typical BDD. My understanding, Product owner comes up with User Story (may or may not in Gherkin), QA writes Scenarios for End-to-End testing(in feature files), Dev writes his code (how and where, does he follow BDD as well?). At this point if the Dev writes the automated Unit Testing, whether this can be leveraged by the QA for End-to-End or they can be absolutely different? </p>

<p>My question is how the Dev and QA leverage each other's work in terms of coding while following BDD. I am not sure how to connect the dots.</p>

<p>Lets take the example of a JAVA based application and QA is already using Cucumber with Selenium Webdriver for automated testing. </p>
",https://stackoverflow.com/questions/54913972/relationship-between-unit-testing-end-to-end-integration-per-se-while-follow,"['java', 'unit-testing', 'cucumber', 'bdd', 'gherkin']",498,True,1,3
Test classes do not see the classes under test when unit testing for Unity3D,"<p>I am trying to write unit tests in C# for the scripts that need to run inside Unity3D, later. My C# scripts are in the folder ""Assets/Scripts"" of the Unity project.</p>

<p>I am using <strong>Unity version 2019.1.0f2</strong> with <strong>Visual Studio Community for Mac V8.0.5 (build 9)</strong>, under <strong>Mac OS X version 10.14.4</strong>.</p>

<p>Unity has a test runner window that I used: <code>Window &gt; General &gt; Test runner</code>. Inside that test runner window, I clicked on ""Play mode"" and on ""Create Playmode Test Assembly Folder"". Unity created a folder called ""Tests"" for me in which I am supposed to put my tests. So far, so good.</p>

<p>Now here is the problem:</p>

<p><strong>My test code cannot see the classes under test that are in the parent folder of that test folder!</strong></p>

<p>This is the folder hierarchy:</p>

<pre><code>  Assets
    Scripts
      MyFirstScript.cs
      Tests
        MyTestScript.cs
        Tests.asmdef
</code></pre>

<p>When I double-click on MyTestScript.cs, Visual Studio opens the solution and the source file OK. Now, I am trying to write</p>

<pre><code>    var x = new MyFirstScript();
</code></pre>

<p>and the compiler complains ""The type or namespace name 'MyFirstScript' could not be found"".</p>

<p>It seems as if the classes in the Scripts folder are completely unknown inside the classes that are in the Tests folder.</p>

<p>This is MyFirstScript.cs:</p>

<pre class=""lang-cs prettyprint-override""><code>using UnityEngine;

public class MyFirstScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}
</code></pre>

<p>And this is MyTestScript.cs:</p>

<pre class=""lang-cs prettyprint-override""><code>using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;

namespace Tests
{
    public class MyTestScript
    {
        // A Test behaves as an ordinary method
        [Test]
        public void MyTestScriptSimplePasses()
        {
            var x = new MyFirstScript(); // problem occurs HERE!

            // Use the Assert class to test conditions
        }

        // A UnityTest behaves like a coroutine in Play Mode. In Edit Mode you can use
        // `yield return null;` to skip a frame.
        [UnityTest]
        public IEnumerator MyTestScriptWithEnumeratorPasses()
        {
            // Use the Assert class to test conditions.
            // Use yield to skip a frame.
            yield return null;
        }
    }
}
</code></pre>

<p>I expected that I could use the class MyFirstScript in my test code (MyTestScript). What can I do?</p>
",https://stackoverflow.com/questions/55971770/test-classes-do-not-see-the-classes-under-test-when-unit-testing-for-unity3d,"['c#', 'unity-game-engine', 'nunit']",1146,True,1,1
which is better to do unit testing in hadoop of the 2 repos below?,"<p>do you have any experience on using 
<a href=""https://github.com/jetoile/hadoop-unit"" rel=""nofollow noreferrer"">https://github.com/jetoile/hadoop-unit</a>
and
<a href=""https://github.com/sakserv/hadoop-mini-clusters"" rel=""nofollow noreferrer"">https://github.com/sakserv/hadoop-mini-clusters</a>
I am working on some code using <code>sakserv</code> repo but I see the <code>jetoile</code> is more new and more active
do you know which one is the way to use now 
I just need to simulate a cluster with basic hadoop and spark - nothing fancy</p>
",https://stackoverflow.com/questions/58658375/which-is-better-to-do-unit-testing-in-hadoop-of-the-2-repos-below,"['unit-testing', 'hadoop']",89,True,1,1
Error in unit testing (karma). There is no directive with &quot;exportAs&quot; set to &quot;ngbPopover&quot;,"<p>Am using the below ngbPopover in my angular page and while writing Unit testing for it. It throws me an compile error. Like below</p>

<p>There is no directive with ""exportAs"" set to ""ngbPopover""
                      (click)=""p1.open()"" [ERROR ->]#p1=""ngbPopover""></p>

<pre><code>    &lt;span placement=""bottom""  [ngbPopover]=""popContent""  triggers=""manual""
          (click)=""p1.open()"" #p1=""ngbPopover""&gt;
    &lt;/span&gt;




    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NotificationsService as ToasterService } from 'angular2-notifications';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { testComponent } from './test.component';

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [testComponent],
      imports: [ FormsModule, ReactiveFormsModule  ],
    }).compileComponents();
  }));

  beforeEach(() =&gt; {
    const toasterServiceStub = {
      create: () =&gt; ({})
    };
    TestBed.configureTestingModule({
      declarations: [testComponent],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        { provide: ToasterService, useValue: toasterServiceStub }
      ]
    });
    fixture = TestBed.createComponent(testComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    fixture = TestBed.createComponent(testComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>If I remove that #p1 from html, my unit testing gets compiled. But not sure why that causes an error. Please help me out</p>
",https://stackoverflow.com/questions/58874033/error-in-unit-testing-karma-there-is-no-directive-with-exportas-set-to-ngb,"['angular', 'unit-testing', 'karma-jasmine']",1070,True,1,1
Angular 7 swUpdate breaks unit testing and cannot be mock / override for testing (PWA),"<p>Here is my component for implementing the <code>swUpdate</code> :</p>

<pre><code>public thereIsUpdate: boolean;

constructor(public swUpdate: SwUpdate) {
    this.checkForUpdates();
}

checkForUpdates() {
  this.swUpdate.checkForUpdate().then(() =&gt; {
    this.swUpdate.available.subscribe(swEvt =&gt; {
      // an update is available
      this.thereIsUpdate = true;
    });
  });
}
</code></pre>

<p>and here is my unit testing :</p>

<pre><code>class MockSwUpdate {
  available = new Subject&lt;{ available: { hash: string } }&gt;().asObservable();
  activated = new Subject&lt;{ current: { hash: string } }&gt;().asObservable();

  public checkForUpdate(): Promise&lt;void&gt; {
    console.log('This is not working');
    return new Promise((resolve) =&gt; resolve());
  }
  public activateUpdate(): Promise&lt;void&gt; {
    return new Promise((resolve) =&gt; resolve());
  }

  constructor(public isEnabled: boolean) {
  }
}

class MockApplicationRef {
  isStable = new Subject&lt;boolean&gt;();
}

describe('xComponent', () =&gt; {
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        xComponent
      ],
      imports: [
        RouterTestingModule,
        ServiceWorkerModule.register('', {enabled: false})
      ],
      providers: [
        {provide: SwUpdate, useValue: MockSwUpdate},
        {provide: ApplicationRef, useClass: MockApplicationRef}
      ]
    }).compileComponents();
  }));
}
</code></pre>

<p><strong>My problem is cannot doing the ""mock"" for <code>swUpdate</code>, somehow it is not working.</strong></p>

<p>Somehow the <code>SwUpdate</code> is not mocked even i have specify it.</p>

<p>When i run <code>ng test</code>, it is showing this error :</p>

<pre><code>Uncaught TypeError: this.swUpdate.checkForUpdate is not a function thrown
    TypeError: this.swUpdate.checkForUpdate is not a function
</code></pre>

<p>Please note that : The mock is <strong>only not working for the <code>SwUpdate</code></strong>.</p>
",https://stackoverflow.com/questions/58521010/angular-7-swupdate-breaks-unit-testing-and-cannot-be-mock-override-for-testing,"['angular', 'service-worker', 'progressive-web-apps', 'angular-unit-test', 'angular-pwa']",1119,False,1,1
Angular 8: How to spy a constant/static property with Jasmine (Service Unit Testing),"<p>I have the following service code</p>

<pre><code>import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AppConstants } from 'src/app/constants';
import * as _ from 'underscore';

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})

export class ApiService {
    constructor(private httpClient: HttpClient) { }

    get(url: string, options?: any): Observable&lt;any&gt; {
        // console.log('2. AppConstants', AppConstants.apiBaseUrl);
        const requestURL = `${AppConstants.apiBaseUrl}${url}`;
        console.log('url---', requestURL);
        return this.httpClient.get(requestURL, options).pipe(
            catchError(this.handleError)
        );
    }

    post(url: string, body: any, options?: any): Observable&lt;any&gt; {
        return this.httpClient.post(`${AppConstants.apiBaseUrl}${url}`, body, options).pipe(
            catchError(this.handleError)
        );
    }

    put(url: string, body: any, options?: any): Observable&lt;any&gt; {
        return this.httpClient.put(`${AppConstants.apiBaseUrl}${url}`, body, options).pipe(
            catchError(this.handleError)
        );
    }

    delete(url: string, options?: any): Observable&lt;any&gt; {
        return this.httpClient.delete(`${AppConstants.apiBaseUrl}${url}`, options).pipe(
            catchError(this.handleError)
        );
    }

    private handleError(error: HttpErrorResponse) {
        if (_.isUndefined(error) &amp;&amp; _.isNull(error)) {
            throwError(error);
        }

        if (error.error instanceof ErrorEvent) {
            // A client-side or network error occurred. Handle it accordingly.
            console.error('An error occurred:', error.error.message);
        } else {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            console.error(
                `Api returned an error with code ${error.status}, ` +
                `error body was: ${error.error}`);
        }
        return throwError(error.error);
    }
}
</code></pre>

<p>Note: This service uses a file that has specific static conntant variables.</p>

<p>I am trying to mock the AppConstants.apiBaseUrl variable in the .spec file as below</p>

<pre><code>import { AppConstants } from 'src/app/constants';
import { HttpTestingController, HttpClientTestingModule } from '@angular/common/http/testing';
import { async, inject, TestBed } from '@angular/core/testing';

import { ApiService } from './api.service';

class MockAppConstants {
    public static apiBaseUrl = 'test-base-api-url';
}

describe('ApiService', () =&gt; {
    // const spy = spyOnProperty(AppConstants, 'apiBaseUrl', 'get').and.returnValue('base-api-url');
    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule
            ],
            providers: [
                ApiService
                ,
                {
                    provide: AppConstants,
                    useValue: spy
                }
            ]
        });
    }
    );

    it('should get profile data of user', () =&gt; {
        const profileInfo = { login: 'blacksonic', id: 602571, name: 'Gábor Soós' };
        const githubService = TestBed.get(ApiService);
        const appConstants = TestBed.get(AppConstants);
        const http = TestBed.get(HttpTestingController);
        let profileResponse;

        githubService.get('blacksonic').subscribe((response) =&gt; {
            profileResponse = response;
        });

        http.expectOne('undefinedblacksonic').flush(profileInfo);
        expect(profileResponse).toEqual(profileInfo);
    });
</code></pre>

<p>It always getting undefined in the apiBaseUrl property. Any quick help will be much appreciated.</p>

<p>I have tried the spyOn method to create mock objects but it didn't help.</p>
",https://stackoverflow.com/questions/59354785/angular-8-how-to-spy-a-constant-static-property-with-jasmine-service-unit-test,"['angular', 'unit-testing', 'mocking']",4626,True,1,1
"MOQ Unit testing error. Expected invocation on the mock once, but was 0 times","<p>I know this question has been asked on here before, but I am very confused as to why this test is failing. Here is the test I am running:</p>

<pre><code>    public void SubmitWebservicePurchaseOrder_Calls_addQuickAddItemListToPO()
    {
        var input = new PurchaseOrderWebserviceSubmitDTO();
        _service.SubmitWebservicePurchaseOrder(input);

        var dict = It.IsAny&lt;Dictionary&lt;long, QuickAddOrCSVLineItem&gt;&gt;();
        _purchaseOrderMock.Verify(x =&gt; x.addQuickAddItemListToPO(It.IsAny&lt;long&gt;(), It.Is&lt;bool&gt;(y =&gt; y == false), ref dict), Times.Once);
    }
</code></pre>

<p>And Here is what the error says:</p>

<pre><code>Result Message: 
Moq.MockException : 
Expected invocation on the mock once, but was 0 times: x =&gt; x.addQuickAddItemListToPO(It.IsAny&lt;Int64&gt;(), It.Is&lt;Boolean&gt;(y =&gt; y == False), .dict)
No setups configured.

Performed invocations:
IPurchaseOrders.CreateNewPO(OMS.DataLayer.poHeader)
IPurchaseOrders.addQuickAddItemListToPO(0, False, System.Collections.Generic.Dictionary`2[System.Int64,OMS.DataServices.QuickAddOrCSVLineItem])
IPurchaseOrders.GetPOHeaderInfoWithUserToken(0, 00000000, 00000000)

</code></pre>

<p>The function <code>SubmitWebservicePurchaseOrder</code> is definitely calling <code>addQuickAddItemListToPO</code>, yet I am still getting this error... Anyone know why? I havn't worked much with MOQ before and am not really sure how to debug...</p>
",https://stackoverflow.com/questions/59252510/moq-unit-testing-error-expected-invocation-on-the-mock-once-but-was-0-times,"['c#', '.net', 'moq']",636,True,0,2
How to resolve a &quot;NotSerializableException&quot; thrown when unit testing a plain implementation of &quot;LinearState&quot;,"<p>I have a plain implementation of ""LinearState"" where the only parameter is a UniqueIdentifier. I have a simple Contract to go with it. </p>

<p>When I try to put it through unit testing, however, I keep getting ""NotSerializabeException"".</p>

<p>I'm using the Corda v4 java template. Testing setup with Gradle Runner on IntelliJ. </p>

<p>I've tried annotating the class with @CordaSerializable, and the constructor with @ConstructorForDeserialization</p>

<pre><code>@CordaSerializable
public class InvestorState implements LinearState {

    private final UniqueIdentifier linearId;

    @ConstructorForDeserialization
    public InvestorState(UniqueIdentifier id) {
        this.linearId = id;
    }
...
}
</code></pre>

<blockquote>
<pre><code>Error log:
data(net.corda.core.contracts.ContractState) -&gt; Trying to build an object serializer for com.mycordapp.states.InvestorState, but it is not constructible from its public properties, and so requires a custom serialiser.

java.io.NotSerializableException: data(net.corda.core.contracts.ContractState) -&gt; Trying to build an object serializer for com.mycordapp.states.InvestorState, but it is not constructible from its public properties, and so requires a custom serialiser.

at net.corda.serialization.internal.amqp.ObjectSerializer$Companion.make(ObjectSerializer.kt:18)
at net.corda.serialization.internal.amqp.DefaultLocalSerializerFactory.makeNonCustomSerializer(LocalSerializerFactory.kt:240)
...
</code></pre>
</blockquote>
",https://stackoverflow.com/questions/55501303/how-to-resolve-a-notserializableexception-thrown-when-unit-testing-a-plain-imp,['corda'],819,True,0,2
How can I delete a document that I use for unit testing with Mongoose?,"<p>This is what I have in test_helper.js </p>

<pre><code>const mongoose =  require('mongoose');

mongoose.Promise = global.Promise;

before((done) =&gt; {
    mongoose.connect('mongodb+srv://Minh:111g@testschedulingdb-dt089t.mongodb.net/test?retryWrites=true', { useNewUrlParser: true });
    mongoose.connection
        .once('open', () =&gt; { done(); })
        .on('error', (error) =&gt; {
         console.warn('Warning', error);
    });
});

beforeEach((done) =&gt; {
    mongoose.connection.collections.requests.drop(() =&gt; {
        done();
    });
});
</code></pre>

<p>As you see, I drop an entire collection before starting a new test. How can I remove only a document used for testing? I tried this but it doesn't right</p>

<pre><code>beforeEach((done) =&gt; {
    mongoose.connection.collections.requests.remove((name: 'Minh') =&gt; {
        done();
    });
</code></pre>
",https://stackoverflow.com/questions/54849511/how-can-i-delete-a-document-that-i-use-for-unit-testing-with-mongoose,"['node.js', 'mongodb', 'mongoose']",653,True,0,1
How do I write a core location with MVVM architecture and perform unit testing?,"<p>I want to develop an app to get device location and search near by areas. I have a basic understanding of MVVM architecture but so far I could not find a way to separate core location logic into view models . I also want to write sample unit test cases for the same.</p>
",https://stackoverflow.com/questions/55685869/how-do-i-write-a-core-location-with-mvvm-architecture-and-perform-unit-testing,"['ios', 'swift', 'iphone', 'unit-testing', 'core-location']",941,True,-1,1
check that a function had been called with a certain parameter in unit testing,"<p>I'm working with BDDfy, AutoFixture and Moq for my testing.</p>

<p>I want to check that a function had been called with a certain parameter.</p>

<p>The function has a number of parameters which it gets.</p>

<p><strong>Updated</strong>
This is the given step</p>

<pre><code> ICollection&lt;string&gt; result = new List&lt;string&gt;();
    _objectMock = new Mock&lt;T&gt;();
    _objectMock.SetupSequence(objectMock =&gt;
     objectMock.Run(It.IsAny&lt;DataModel1&gt;(), It.IsAny&lt;Collection&lt;DataModel2&gt;&gt;())
     .Throws(_customException)
     .Returns(Task.FromResult(result));
</code></pre>

<p>On the [Then] part, I check that:</p>

<pre><code>    mock.Verify(mock =&gt; mock.verifyData(It.IsAny&lt;DataModel1&gt;(), It.IsAny&lt;IReadOnlyCollection&lt;DataModel2&gt;&gt;()));
</code></pre>

<p>I want to check that the 2nd parameter to the function verifyData was of a certain object.</p>
",https://stackoverflow.com/questions/59461176/check-that-a-function-had-been-called-with-a-certain-parameter-in-unit-testing,"['c#', 'moq', 'autofixture', 'teststack']",730,True,0,2
Angular Unit-testing with service layer HttpTestingController Error: Expected no open requests found GET,"<p>I'm trying to unit test my service layer within Angular, but when I try to mock the http requests for get, post and put, I get an Error saying it couldn't find an open request but found 1</p>

<p>I already tried to search multiple posts with this issue but none seem to have come to my rescue, but I seem to end up to no avail</p>

<pre><code>it('should be able load company data', inject([HttpClient], (http: HttpClient) =&gt; {
const companyList: CompanyVerificationResponseDto = {
  companyName: 'testcompany',
  kvkNumber: 12345678,
  companyPhone: '0612341234',
  email: 'testtest@email.com',
  accountStatus: 0,
  contactPhone: '0631313131'
};

managementService.loadData();

const headers = new HttpHeaders().set('Content-Type', 'application/json');
const param = new HttpParams().set('token', '1234-1234-1234').append('email', 'testtest@email.com');
const options = {params: param, headers: headers};


http.get('http://localhost:8080/adminpage', options).subscribe(() =&gt; {

});

const req = httpMock.expectOne('http://localhost:8080/adminpage?token=1234-1234-1234&amp;email=testtest@email.com');
expect(req.request.method).toEqual('GET');

req.flush(companyList);
}));

afterEach(() =&gt; {
   httpMock.verify();
});
</code></pre>

<p>and my actual service method goes like this:</p>

<pre><code>public loadData() {
this.restfulService.url = this.restfulService.getBaseUrl() + '/adminpage';
const param = new HttpParams().set('token', this.restfulService.getLocalStorageToken().token);
const options = {params: param, headers: this.headers};

return this.httpClient.get&lt;CompanyVerificationResponseDto[]&gt;(this.restfulService.url, options).subscribe(data =&gt; {
    this.companyList = data;
    this.onSuccesfulReceivedData(data);
  },
  error =&gt; this.restfulService.handleError(error));
}
</code></pre>

<p>But I get this error:</p>

<pre><code>PhantomJS 2.1.1 (Windows 8 0.0.0) ManagementService should be able to accept a company based on email FAILED
    Error: Expected no open requests, found 1: GET http://localhost:8080/adminpage in http://localhost:9876/_karma_webpack_/vendor.js (line 32166)
    verify@http://localhost:9876/_karma_webpack_/vendor.js:32166:97
    http://localhost:9876/_karma_webpack_/main.js:3356:24
    invoke@http://localhost:9876/_karma_webpack_/polyfills.js:6843:31
    onInvoke@http://localhost:9876/_karma_webpack_/vendor.js:156148:45
    invoke@http://localhost:9876/_karma_webpack_/polyfills.js:6842:40
    run@http://localhost:9876/_karma_webpack_/polyfills.js:6593:49
    runInTestZone@http://localhost:9876/_karma_webpack_/vendor.js:156369:37
    http://localhost:9876/_karma_webpack_/vendor.js:156384:33
    invoke@http://localhost:9876/_karma_webpack_/polyfills.js:6843:31
    run@http://localhost:9876/_karma_webpack_/polyfills.js:6593:49
    http://localhost:9876/_karma_webpack_/polyfills.js:7327:37
    invokeTask@http://localhost:9876/_karma_webpack_/polyfills.js:6876:36
    runTask@http://localhost:9876/_karma_webpack_/polyfills.js:6643:57
    drainMicroTaskQueue@http://localhost:9876/_karma_webpack_/polyfills.js:7050:42
</code></pre>

<p>I expect it to pass saying the request method is a get request, but the actual result is an error. </p>
",https://stackoverflow.com/questions/54194970/angular-unit-testing-with-service-layer-httptestingcontroller-error-expected-no,"['angular', 'typescript', 'unit-testing', 'web-services', 'karma-jasmine']",1271,False,0,0
Unable to set &#39;valid&#39; property of Formgroup for reactive form in Angular Unit testing,"<p>I am using reactive form. This property: <code>getattributeForm: FormGroup;</code>
is set invalid. So I am not able to cover all testcase.</p>

<pre><code>if (!this.getattributeForm.valid) {return}
</code></pre>

<p>This is always true. Can we make it true, so that I can cover other scenario? <code>this.getattributeForm.valid</code> to be set true in angular unit testing.</p>
",https://stackoverflow.com/questions/55869005/unable-to-set-valid-property-of-formgroup-for-reactive-form-in-angular-unit-te,['angular'],1661,False,0,1
Unit testing Python Google Cloud HTTP functions - need to pass in a request object,"<p>I'm getting started writing Google Cloud http Functions using Python and I would like to include unit tests. My function only responds to POST requests so the basic outline of my function is:</p>

<pre><code>def entry_point(request):
    if request.method == 'POST':
        # do something
    else:
        # throw error or similar
</code></pre>

<p>I want to write a simple unit test to ensure that if the function receives a GET request the response has a 405 status.</p>

<p>Hence in my unit test I need to pass in a value for the <code>request</code> parameter:</p>

<pre><code>def test_call(self):
    req = #need a way of constructing a request

    response = entry_point(req)
    assert response.status  == 405 # or something like this
</code></pre>

<p>Basically I need to construct a request then check that the response status is what I expect it to be. I've googled around and found loads of pages that talk about mocking and all sorts of stuff that I frankly don't understand (I'm not a crash hot developer) so I'm hoping someone can help me with an idiot's guide of doing what I need to do.</p>

<p>I did find this: <a href=""https://cloud.google.com/functions/docs/bestpractices/testing#unit_tests_2"" rel=""nofollow noreferrer"">https://cloud.google.com/functions/docs/bestpractices/testing#unit_tests_2</a>: </p>

<pre><code>from unittest.mock import Mock

import main


def test_print_name():
    name = 'test'
    data = {'name': name}
    req = Mock(get_json=Mock(return_value=data), args=data)

    # Call tested function
    assert main.hello_http(req) == 'Hello {}!'.format(name)


def test_print_hello_world():
    data = {}
    req = Mock(get_json=Mock(return_value=data), args=data)

    # Call tested function
    assert main.hello_http(req) == 'Hello World!'
</code></pre>

<p>which <em>kinda</em> helped but it doesn't explain how I can specify the request method (i.e. GET, POST etc...).</p>
",https://stackoverflow.com/questions/57005898/unit-testing-python-google-cloud-http-functions-need-to-pass-in-a-request-obje,"['python', 'google-cloud-functions']",1243,True,0,2
Unit testing: check values of the local variables within the private static void methods,"<p>I have a C# application that uses a lot of   </p>

<p>1 ) private   </p>

<p>2 ) static   </p>

<p>3) return type of void  </p>

<p>methods which is difficult to unit test.</p>

<p>I can use Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType objects, and then use the InvokeStatic to call the aforementioned methods.</p>

<p>However, could someone please tell me if there is way to check value of the local variables within the aforementioned private static void methods?</p>
",https://stackoverflow.com/questions/55102834/unit-testing-check-values-of-the-local-variables-within-the-private-static-void,"['.net', 'unit-testing', 'static', 'private', 'visualstudio.testtools']",52,False,0,0
Need Help Unit Testing with Rails 5 for Update Action Always Fail on assert_equals,"<p>i want to test an update action in my rails project. The function is running well, but when i try to unit-test it's always fail. Can you help this?</p>

<p>i'm new with ruby and unit-testing. i've tried with any documentation it still not solve this test.</p>

<p>this is my <code>Content Controller</code> function that i want to test, i use clearance for auth</p>

<pre><code>before_action :require_login
def update
   @content = Content.find(params[:id])
   if @content.update(content_params)
      flash[:notice] = 'success'
      redirect_back fallback_location: root_path
   else
      flash[:notice] = 'fail'
      redirect_back fallback_location: root_path
   end
end
</code></pre>

<p>this is my <code>Content Fixture</code> </p>

<pre><code>one: 
  id: '1'
  about: 'about content'
  privacy: 'privacy content'
  terms: 'terms content'
</code></pre>

<p>this is my <code>test_helper</code></p>

<pre><code>ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
require 'clearance/test_unit'

class ActiveSupport::TestCase
  fixtures :all
end

class ActionDispatch::IntegrationTest
  def sign_in_as_user
    user = User.create!(email: ""example@example.com"", password: ""letmein"")
    post session_url, params: {
      session: {
        email: user.email,
        password: user.password
      }
    }
  end
end
</code></pre>

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

<pre><code>test ""should update content"" do
    sign_in_as_user
    content = contents(:one)
    put content_url(content), params: { about: { syarat: ""updated about"", privacy: ""updated privacy"", terms: ""updated terms"" } }
    content.reload
    assert_equal ""updated about"", content.about
    assert_equal ""updated privacy"", content.privacy
    assert_equal ""updated terms"", content.terms
  end
</code></pre>

<p>Then i run the test <code>rake test</code>, this is the result</p>

<pre><code>Failure:
ContentControllerTest#test_should_update_content [/Users/abc/Documents/PROJECT/Apps/test-app/test/controllers/content_controller_test.rb:20]:
--- expected
+++ actual
@@ -1 +1 @@
-""updated about""
+""about content""
</code></pre>
",https://stackoverflow.com/questions/55947404/need-help-unit-testing-with-rails-5-for-update-action-always-fail-on-assert-equa,"['ruby', 'unit-testing', 'ruby-on-rails-5']",48,False,0,0
Is there a way to trigger a manually trigger events in Java Unit Testing,"<p>I need to trigger manual event for a ListSelectionListener within my unit test. Is there a way to do this or any workaround to test code inside triggered code?</p>

<pre><code>private ListSelectionListener getLeftListSelectionListner()
{
  return e -&gt; {
    if (!leftSelector.getSelectedValueList().isEmpty())
    {
      rightSelector.getSelectionModel().clearSelection();
      getAddBtn().setEnabled(true);
    }
    else
    {
      getAddBtn().setEnabled(false);
    }
  };
}
</code></pre>
",https://stackoverflow.com/questions/55528547/is-there-a-way-to-trigger-a-manually-trigger-events-in-java-unit-testing,"['java', 'swing', 'unit-testing']",527,True,0,1
How to find elementUi&#39;s componets during unit testing using vue-test-utils&#39;s with shallowMount?,"<p>After reading vue-test-utils's document, I am trying to hand on.</p>

<p>Hope someone can clear my confusion.</p>

<pre><code>import { mount, shallowMount } from '@vue/test-utils'
import Vue from 'vue'
import Form from '@/components/Form/index.vue'
import ElementUI from 'element-ui'

Vue.use(ElementUI)
describe('Form.vue', () =&gt; {

  //find it, pass
  it('mount', () =&gt; {
    const wrapper = mount(Form)
    const elButton = wrapper.find('.el-button')
    expect(elButton.isVueInstance()).toBe(true)
  })

  //can't find it, fail
  it('shallowMount', () =&gt; {
    const wrapper = shallowMount(Form)
    const elButton = wrapper.find('.el-button')
    expect(elButton.isVueInstance()).toBe(true)
  })
})
</code></pre>

<p>I can find the components given by elementui when I use 'mount'.</p>

<p>But maybe sometimes I'll need to use 'shallowMount'.</p>

<p>How can I find the components in this situation?</p>

<p>Thanks in advance.</p>

<hr>

<hr>

<hr>

<p>Thanks for the answer,
I found two approaches to fix it:</p>

<pre><code>it('shallowMount', () =&gt; {
      const wrapper = shallowMount(Form)
      const elButton = wrapper.find(ElementUI.Button)
      expect(elButton.isVueInstance()).toBe(true)
    })
</code></pre>

<pre><code>it('shallowMount', () =&gt; {
      const wrapper = shallowMount(Form)
      const elButton = wrapper.find({ name: 'ElButton' })
      expect(elButton.isVueInstance()).toBe(true)
    })
</code></pre>
",https://stackoverflow.com/questions/55676249/how-to-find-elementuis-componets-during-unit-testing-using-vue-test-utilss-wit,"['vue.js', 'jestjs', 'element-ui', 'vue-test-utils']",1754,True,0,1
How to test (Unit testing) reducer in React which filtered an array of objects,"<p>I have a problem can't write a correct test for one of my reducers.</p>

<p>My reducer look:</p>

<pre><code>export const initialState = {
  time: undefined,
  products: undefined,
  filteredProducts: [],
  search: """"
};

case ""FILTER_BY_VALUE"": {
      return {
        ...state,
        search: payload,
        filteredProducts: [
          ...state.products.filter(product =&gt;
            product.name.toLowerCase().startsWith(payload.toLowerCase())
          )
        ]
      };
    }

</code></pre>

<p>My reducer filter an array of objects by value (in my example it is payload)</p>

<p>My test look :</p>

<pre><code>it(""FILTER_BY_VALUE"", () =&gt; {
    const action = {
      type: ""FILTER_BY_VALUE"",
      payload: ""dsf""
    };
    expect(data(initialState, action)).toEqual({
      ...initialState,
      search: action.payload
      //   filteredProducts: Object
    });
  });
</code></pre>

<p>Error is in image:
<a href=""https://i.stack.imgur.com/AjPzy.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/AjPzy.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/57939644/how-to-test-unit-testing-reducer-in-react-which-filtered-an-array-of-objects,"['reactjs', 'testing', 'jestjs']",412,True,0,1
how to do unit testing for this type of code in windows form c#,"<pre><code>public int validation()
{
    int flag = 0;
    Regex Rx = new Regex(@""^[\p{L} \.'\-]{0,20}$"");
    Regex Rx1 = new Regex(@""^[\p{L} \.'\-]{0,20}$"");
    Regex Rx2 = new Regex(@""^[0-9]{10}$"");
    if (name.Text=="""")
    {
        name.Focus();
        errorProvider1.SetError(name, MessageBox.Show(""enter your name"", 
            ""error"", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
        flag = 1;
    }
    else if (fathername.Text == """")
    {
        fathername.Focus();
        errorProvider1.SetError(name, MessageBox.Show(""Enter your father name"", 
            ""error"", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
        flag = 1;
    }
}
</code></pre>

<p><strong>its public validation part code for windows form</strong></p>
",https://stackoverflow.com/questions/54273560/how-to-do-unit-testing-for-this-type-of-code-in-windows-form-c,"['c#', '.net', 'visual-studio', 'winforms', 'unit-testing']",64,True,0,2
Unit Testing w/ Sinon: How do I test a variable inside of a Callback?,"<p>I a doing unit test with Sinon to at least try to get something to pass and am out of luck. I wasn't able to find anything online.</p>

<p>I have 2 problems:</p>

<p>1) I am trying to get a simple response, but it fails saying <code>spy</code> is <code>false</code>. When I log it, it says it's <code>true</code>.</p>

<p>2) I want to test the template in the callback function is equal to 'New Title'. I am unable to figure how to pass req, res, and next into router.get</p>

<h3>router.js</h3>

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

router.get('/', (req, res, next) =&gt; {
var template = {
  title: req.title,
  item: req.item,
  description: 'N/A'
};
res.render('index', template);

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

<h3>router.spec.js</h3>

<pre><code>const router = require('./router');
var res = {};
var req = {
  title: 'New Title',
  item: 'Blank Item'
};
var template = {
  title: req.title,
  item: req.item,
  description: 'N/A'
};


it('1) should call the response', ()=&gt;{
 var spy = sinon.spy(route, 'get');
 route.get('/', ()=&gt;{});
 console.log(spy.calledOnce); // equals true
 assert(spy.calledOnce).toBeTruthy();
 spy.restore();
});

it('2) should return a status 200', ()=&gt;{
 var stub = sinon.stub().yield([req, res, next]);
 route.get('/', stub); // main problem
 assert.equal(200, res.statusCode);
 stub.restore();
});

</code></pre>

<p>I want to access the route handler so I can do further testing. Where and how can I implement route handling in this situation?</p>
",https://stackoverflow.com/questions/55990928/unit-testing-w-sinon-how-do-i-test-a-variable-inside-of-a-callback,"['javascript', 'unit-testing', 'mocha.js', 'sinon']",461,True,0,1
Structuring SWI-Prolog Code into Modules for Unit Testing of Multiple Algorithms and Data Sets,"<p>To elaborate on a discussion in the comments below <a href=""https://stackoverflow.com/questions/57263196"">my last question</a>: I am looking for suggestions on techniques or best practices for structuring SWI-Prolog code in order to be able to use and test alternative, interchangeable implementations of algorithms and their supporting modules.</p>

<p>The current situation can be illustrated using the following small, ficticous example: The user provides some input data (file <code>data.pl</code>) and loads a module with an algorithm to be applied (file <code>graph.pl</code>). The algorithm module itself uses helper predicates from another module (file <code>path.pl</code>) which in turn requires access to the user-provided data:</p>

<p>File '<strong><code>data.pl</code></strong>' (input data set):</p>

<pre><code>:- use_module(graph).

edge(a,b).
edge(b,c).
edge(c,d).
</code></pre>

<p>File '<strong><code>graph.pl</code></strong>' (algorithm):</p>

<pre><code>:- module(graph, [reachable/2]).
:- use_module(path).

reachable(X,Y) :-
    path(X,Y), !.
reachable(X,Y) :-
    path(Y,X), !.
</code></pre>

<p>File '<strong><code>path.pl</code></strong>' (module with helper predicates, notice it accessing the data in <code>user</code>):</p>

<pre><code>:- module(path, [path/2]).

path(X,X).
path(X,Y) :-
    user:edge(X,Z),
    path(Z,Y).
</code></pre>

<p>For the use case of applying the algorithm to a single input data set and the single implementation of the algorithm, this is perfectly fine:</p>

<pre><code>?- [data].
true.

?- reachable(a,a).
true.

?- reachable(a,d).
true.

?- reachable(d,a).
true.
</code></pre>

<p>Now suppose that I have a larger number of data sets, and multiple alternative implementations of the <code>graph</code> and <code>path</code> modules (with the same interface, i.e., exported predicates). For the sake of the (small) example, let us assume we files data files <strong><code>data1.pl</code></strong>, <strong><code>data2.pl</code></strong>, helper predicate modules <strong><code>path1.pl</code></strong>, <strong><code>path2.pl</code></strong>, and algorithm modules <strong><code>graph1</code></strong>, <strong><code>graph2.pl</code></strong>.</p>

<p>I want to automate testing these using <a href=""https://www.swi-prolog.org/pldoc/doc_for?object=section(%27packages/plunit.html%27)"" rel=""nofollow noreferrer"">SWI-Prolog unit tests</a>, and preferably be able to write a test suite that supports both the differing data sets and the different module implementations, without the need to restart Prolog in between. That is to say I want to be able test all combinations in the Cartesian product</p>

<blockquote>
  <p><code>{data1.pl, data2.pl} x {path1.pl, path2.pl} x {graph1.pl, graph2.pl}</code></p>
</blockquote>

<p>without copy-pasting/duplicating code.</p>

<p>My question is: How would I go about this in SWI-Prolog? Are there best practices, design patterns or the like on how to structure code into modules for this purpose? Should I perhaps make use of <a href=""https://www.swi-prolog.org/pldoc/man?section=importmodule"" rel=""nofollow noreferrer"">dynamic importing</a> for switching between alternative algorithm modules, and simply use <code>setup</code> and <code>cleanup</code> in unit tests for the data?</p>
",https://stackoverflow.com/questions/57341339/structuring-swi-prolog-code-into-modules-for-unit-testing-of-multiple-algorithms,"['unit-testing', 'module', 'prolog', 'composition', 'swi-prolog']",700,True,5,3
Unit Testing in VS / Can&#39;t see the full error message for a failed test,"<p>I am currently working on a Unit Test for a function that returns an SQL Expression for merge command.
I need to see the full error message simply because I need to see the return value of the actual function.</p>

<p>Instead i get only the half of that result.Here is the error message ;</p>

<pre><code>Test Name:  deneme1
Test FullName:  'test name'
Test Source:     : line -1
Test Outcome:   Failed
Test Duration:  0:00:00

Test Name:  deneme1
Test Outcome:   Failed
Result StackTrace:  
at NUnit.Framework.Internal.Commands.TestMethodCommand.Execute(TestExecutionContext context)
   at NUnit.Framework.Internal.Execution.SimpleWorkItem.PerformWork()

Result Message: 
Expected string length 182 but was 366. Strings differ at index 12.
  Expected: ""MERGE INTO [intoTable] USING [sourceTable] ON [merge_conditio...""
  But was:  ""MERGE INTO [tsttargetTable] USING (SELECT [tstsourceTable].[i...""
  -----------------------^

</code></pre>

<p>See the result message is cut in half. Is there anyway to fix this ?</p>
",https://stackoverflow.com/questions/58801485/unit-testing-in-vs-cant-see-the-full-error-message-for-a-failed-test,"['c#', 'sql', 'visual-studio', 'unit-testing']",952,True,0,1
How to call a method(service) which inside some method using jasmine unit testing,"<p>In the controller</p>

<pre><code>$scope.checkDuplicatePatients = function () {
            var systemIdentier = ''; // FIXME
            var givenName = $scope.patient.givenName || '';
            var familyName = $scope.patient.familyName || '';
            var gender = $scope.patient.gender || '';
            var birthDate = $scope.patient.birthdate || '';
            var phoneNumber = $scope.patient.PERSON_ATTRIBUTE_TYPE_PHONE_NUMBER || '';
            if ($scope.patient.address) {
                var subDivision = $scope.patient.address.address3 || '';
            }

            if ((givenName || familyName) &amp;&amp; gender &amp;&amp; birthDate) {
                patientService.searchDuplicatePatients(
                    systemIdentier,
                    givenName,
                    familyName,
                    birthDate,
                    gender,
                    phoneNumber,
                    subDivision
                ).then(function (response) {
                    $rootScope.numberOfDuplicatedPatients = response.length;
                    $rootScope.duplicatedPatients = response;
                });
            }
        };
</code></pre>

<p>Declared In the unit test</p>

<pre><code>var patientService = jasmine.createSpyObj('patientService', ['searchDuplicatePatients']); 
</code></pre>

<p>Inside before each function</p>

<pre><code>describe('PatientCommonController', function () {

var $aController, $httpBackend, scope, appService, rootScope, patientAttributeService, $state;
var spinner = jasmine.createSpyObj('spinner', ['forPromise']);
var patientService = jasmine.createSpyObj('patientService', ['searchDuplicatePatients']); 
var $compile;

beforeEach(module('bahmni.registration', 'ngDialog'));

beforeEach(module(function ($provide) {
    $provide.value('patientAttributeService', {});
}));

beforeEach(
    inject(function ($controller, _$httpBackend_, $rootScope, _$compile_, _$state_) {
        $aController = $controller;
        $httpBackend = _$httpBackend_;
        scope = $rootScope.$new();
        $state = _$state_;
        rootScope = $rootScope;
        $compile = _$compile_;
    })
);


beforeEach(function () {
    appService = jasmine.createSpyObj('appService', ['getAppDescriptor']);
    rootScope.genderMap = {};

    scope.patient = {};

    appService.getAppDescriptor = function () {
        return {
            getConfigValue: function (config) {
                return true;
            },
            getExtensions: function() {
                return [];
            }

        };
    };

    $aController('PatientCommonController', {
        $scope: scope,
        $rootScope: rootScope,
        appService: appService,
        patientService: patientService
    });

    $httpBackend.whenGET(Bahmni.Common.Constants.globalPropertyUrl + '?property=concept.reasonForDeath').respond({});
    $httpBackend.when('GET', Bahmni.Common.Constants.conceptUrl).respond({});
    $httpBackend.flush();

});
</code></pre>

<p>The unit test </p>

<pre><code>describe(""Patient duplicate check"", function () {
    it(""should call patientService.searchDuplicatePatients when givenName, gender and birthDate are populated"", function() {
        scope.patient.systemIdentier = 'BAH203007';
        scope.patient.givenName = 'Dhruv';
        scope.patient.familyName = 'Bhardwaj';
        scope.patient.gender = 'M';
        scope.patient.birthDate = '1993-12-18T00:00:00.000Z';
        scope.patient.PERSON_ATTRIBUTE_TYPE_PHONE_NUMBER = '987654321';
        scope.patient.address = 'BAYA HADJIDA';
        scope.checkDuplicatePatients = jasmine.createSpy(""checkDuplicatePatients"");
        scope.checkDuplicatePatients();
        expect(scope.checkDuplicatePatients).toHaveBeenCalled();
        expect(patientService.searchDuplicatePatients).toHaveBeenCalledWith('BAH203006', 'Kartik', 'Seth', '1993-03-18T00:00:00.000Z', 'M', '123456789', 'NGAOUNDAL');
    });

    it(""should not call patientService.searchDuplicatePatients when givenName, gender or birthDate is not populated"", function() {
        scope.patient.givenName = 'Dhruv';
        scope.checkDuplicatePatients = jasmine.createSpy(""checkDuplicatePatients"");
        scope.checkDuplicatePatients();
        expect(scope.checkDuplicatePatients).toHaveBeenCalled();
        expect(patientService.searchDuplicatePatients).not.toHaveBeenCalled(); /*Here is I want to unit test*/
   });
}) What is wrong here in the unit test
</code></pre>
",https://stackoverflow.com/questions/55646733/how-to-call-a-methodservice-which-inside-some-method-using-jasmine-unit-testin,"['angularjs', 'unit-testing', 'jasmine']",31,False,0,1
How to patch Python&#39;s raise (or return) keyword for the purpose of unit testing?,"<p>What is the namespace for Python keywords that mock.patch is able to catch?</p>

<p>When someone wants to patch open or print then <code>mock.patch(""builtins.open"")</code> or <code>mock.patch(""mymodule.open"")</code> can be used, but that doesn't works, for example, with <code>raise</code>.</p>

<p>If I have <code>raise somemodule.SomeException</code> statement then I could easily test if the exception is raised, but how I can assert that actually raise keyword has been invoked. Like (with the help of <code>pytest</code> and <code>pytest-mock</code>):</p>

<pre><code>def test_myfunction_calls_raise(self, mocker):
    mocked = mocker.patch(""mymodule.raise"")
    mymodule.myfunction()
    mocked.assert_called_once()
</code></pre>

<hr>

<p>EDIT: I've got <a href=""https://stackoverflow.com/a/56841434/11703358"">a very nice answer</a> and so mock.patch isn't applicable. Beside that and beside obvious solution - testing the outcome - is there some other meaningful technique to test if Python keyword (<code>raise</code>, <code>return</code>, ...) has been called in a code?</p>

<p>EDIT 2:
Actual code I want to test (pynput's Listener stop() doesn't work well in Xfce, so I have to raise the exception to stop the Listener thread):</p>

<pre><code>import pynput
# ...

def stop(self):
    """"""Stops listener by raising an exception.""""""
    try:
        raise pynput.mouse.Listener.StopException
    except pynput.mouse.Listener.StopException:
        return False
</code></pre>

<p>EDIT 3: The method from above is unittested with the following two test methods:</p>

<pre><code>def test_stop_stops_listener(self, mocker):
    """"""StopException is raised if MagicMock has got StopException attribute.""""""
    mocked = mocker.patch(""pynput.mouse.Listener"")
    with pytest.raises(TypeError):  # catching classes that do not inherit from BaseException is not allowed
        base.BaseMouse().stop()
    assert hasattr(mocked, ""StopException"")

def test_stop_returns_False(self, mocker):
    assert base.BaseMouse().stop() is False
</code></pre>
",https://stackoverflow.com/questions/56839000/how-to-patch-pythons-raise-or-return-keyword-for-the-purpose-of-unit-testing,"['python', 'unit-testing', 'mocking', 'pytest', 'pytest-mock']",339,True,0,1
Hit with Unimplemented method StatusRuntimeException when unit testing generated grpc code in Android project,"<p>I have an Android project that generates gRPC classes from the proto file upon building, which is from here under the helloworld example:
<a href=""https://github.com/grpc/grpc-java/tree/master/examples/src"" rel=""nofollow noreferrer"">https://github.com/grpc/grpc-java/tree/master/examples/src</a></p>

<p>My JUnit test follows to that of the test written for HelloWorldClient (<a href=""https://github.com/grpc/grpc-java/blob/master/examples/example-kotlin/src/test/kotlin/io/grpc/examples/helloworld/HelloWorldClientTest.kt"" rel=""nofollow noreferrer"">https://github.com/grpc/grpc-java/blob/master/examples/example-kotlin/src/test/kotlin/io/grpc/examples/helloworld/HelloWorldClientTest.kt</a>), and I thought it theoretically would work</p>

<p>However, when I run the test, I was hit with an exception error as follows:</p>

<pre><code>io.grpc.StatusRuntimeException: UNIMPLEMENTED: Method helloworld.Greeter/SayHello is unimplemented
    at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:235)
    at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:216)
    at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:141)
    at io.grpc.examples.helloworld.GreeterGrpc$GreeterBlockingStub.sayHello(GreeterGrpc.java:177)
    at com.android.grpcmvvm.data.GreeterRemoteDataSource.sayHello(GreeterRemoteDataSource.kt:49)
    at com.android.grpcmvvm.view.GreeterViewModelUnitTest.testTestFunction(GreeterViewModelUnitTest.kt:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.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 io.grpc.testing.GrpcCleanupRule$1.evaluate(GrpcCleanupRule.java:125)
    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.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)


Wanted but not invoked:
serviceImpl.sayHello(
    &lt;Capturing argument&gt;,
    &lt;any&gt;
);
-&gt; at io.grpc.examples.helloworld.GreeterGrpc$GreeterImplBase.sayHello(GreeterGrpc.java:101)

However, there was exactly 1 interaction with this mock:
serviceImpl.bindService();
-&gt; at io.grpc.internal.AbstractServerImplBuilder.addService(AbstractServerImplBuilder.java:114)


Wanted but not invoked:
serviceImpl.sayHello(
    &lt;Capturing argument&gt;,
    &lt;any&gt;
);
-&gt; at io.grpc.examples.helloworld.GreeterGrpc$GreeterImplBase.sayHello(GreeterGrpc.java:101)

However, there was exactly 1 interaction with this mock:
serviceImpl.bindService();
-&gt; at io.grpc.internal.AbstractServerImplBuilder.addService(AbstractServerImplBuilder.java:114)


    at io.grpc.examples.helloworld.GreeterGrpc$GreeterImplBase.sayHello(GreeterGrpc.java:101)
    at com.android.grpcmvvm.view.GreeterViewModelUnitTest.testTestFunction(GreeterViewModelUnitTest.kt: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.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 io.grpc.testing.GrpcCleanupRule$1.evaluate(GrpcCleanupRule.java:125)
    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.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>The following is the test and the relevant code
(Please mind the ViewModel name. I removed anything about ViewModel from the test for the purpose of this question)</p>

<p><strong>GreeterViewModelUnitTest.kt</strong></p>

<pre><code>import com.android.grpcmvvm.data.GreeterRemoteDataSource
import com.android.grpcmvvm.grpc.GrpcService
import io.grpc.ManagedChannel
import io.grpc.examples.helloworld.GreeterGrpc
import io.grpc.examples.helloworld.HelloReply
import io.grpc.examples.helloworld.HelloRequest
import io.grpc.inprocess.InProcessChannelBuilder
import io.grpc.inprocess.InProcessServerBuilder
import io.grpc.stub.StreamObserver
import io.grpc.testing.GrpcCleanupRule
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.*
import org.mockito.AdditionalAnswers.delegatesTo
import org.mockito.internal.matchers.Any

@RunWith(JUnit4::class)
class GreeterViewModelUnitTest {
    // region JUnit test rules
    @get:Rule
    val grpcCleanupRule = GrpcCleanupRule()

    private val serviceImpl = Mockito.mock(GreeterGrpc.GreeterImplBase::class.java, delegatesTo&lt;Any&gt;(object: GreeterGrpc.GreeterImplBase(){}))
    // endregion

    // region Private properties
    @Mock
    private lateinit var grpcService: GrpcService

    private lateinit var managedChannel: ManagedChannel

    private lateinit var greeterRemoteDataSource: GreeterRemoteDataSource
    // endregion

    @Before
    @Throws(Exception::class)
    fun setUp() {
        MockitoAnnotations.initMocks(this)

        val serverName = InProcessServerBuilder.generateName()

        grpcCleanupRule.register(InProcessServerBuilder
            .forName(serverName)
            .directExecutor()
            .addService(serviceImpl)
            .build()
            .start())

        managedChannel = grpcCleanupRule.register(InProcessChannelBuilder
            .forName(serverName)
            .directExecutor()
            .build())

        Mockito.`when`(grpcService.createManagedChannel()).thenReturn(managedChannel)
        greeterRemoteDataSource = GreeterRemoteDataSource(grpcService)
    }

    @Test
    fun testTestFunction() {
        val requestCaptor = ArgumentCaptor.forClass(HelloRequest::class.java)

        greeterRemoteDataSource.sayHello(""once again"")

        Mockito.verify&lt;GreeterGrpc.GreeterImplBase&gt;(serviceImpl)
            .sayHello(requestCaptor.capture(), ArgumentMatchers.any&lt;StreamObserver&lt;HelloReply&gt;&gt;())

        assertEquals(""once again"", requestCaptor.value.name)
    }
</code></pre>

<p><strong>GrpcService.kt</strong></p>

<pre><code>import io.grpc.ManagedChannel
import io.grpc.ManagedChannelBuilder
import java.util.concurrent.Executors

class GrpcService(private val host: String, private val port: Int) {

    fun createManagedChannel(): ManagedChannel {
        return ManagedChannelBuilder
            .forAddress(host, port)
            .executor(Executors.newSingleThreadExecutor())
            .usePlaintext()
            .build()
    }
}
</code></pre>

<p><strong>GreeterRemoteDataSource.kt</strong></p>

<pre><code>import com.android.grpcmvvm.grpc.GrpcService
import io.grpc.ManagedChannel
import io.grpc.StatusRuntimeException
import io.grpc.examples.helloworld.GreeterGrpc
import io.grpc.examples.helloworld.HelloReply
import io.grpc.examples.helloworld.HelloRequest

class GreeterRemoteDataSource constructor(private val grpcService: GrpcService) {

    private lateinit var channel: ManagedChannel

    fun sayHello(message: String): String {
        channel = grpcService.createManagedChannel()

        val stub = GreeterGrpc.newBlockingStub(channel)
        val request = HelloRequest.newBuilder().setName(message).build()

        val reply: HelloReply = try {
            stub.sayHello(request)
        } catch (e: StatusRuntimeException) {
            e.printStackTrace()
            return String.format(""{0}"", e.status)
        } finally {
            channel.shutdown()
        }

        return reply.message
    }
}
</code></pre>

<p><strong>build.gradle (app)</strong></p>

<pre><code>apply plugin: 'com.android.application'

apply plugin: 'com.google.protobuf'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId ""com.android.grpcmvvm""
        minSdkVersion 15
        targetSdkVersion 28
        multiDexEnabled true
        versionCode 1
        versionName ""1.0""
        testInstrumentationRunner ""androidx.test.runner.AndroidJUnitRunner""
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    def grpc_version = ""1.22.1""
    def lifecycle_version = ""2.2.0-alpha04""
    def mockito_kotlin_version = ""2.1.0""
    def mockito_version = ""3.0.0""
    def multidex_version = ""2.0.1""
    def truth_version = ""0.45""

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation ""org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version""

    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation ""androidx.multidex:multidex:$multidex_version""
    implementation 'com.google.android.material:material:1.0.0'

    // gRPC
    implementation 'javax.annotation:javax.annotation-api:1.3.2'
    implementation ""io.grpc:grpc-okhttp:$grpc_version""
    implementation ""io.grpc:grpc-protobuf-lite:$grpc_version""
    implementation ""io.grpc:grpc-stub:$grpc_version""

    // Lifecycle
    implementation ""androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version""

    // Instrumented tests
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    androidTestImplementation 'androidx.test:runner:1.2.0'

    // Unit tests
    testImplementation ""androidx.arch.core:core-testing:2.1.0""
    testImplementation ""com.google.truth:truth:$truth_version""
    testImplementation ""io.grpc:grpc-testing:$grpc_version""
    testImplementation ""com.nhaarman.mockitokotlin2:mockito-kotlin:$mockito_kotlin_version""
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-debug:1.3.1'
    testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.1'
    testImplementation ""org.mockito:mockito-inline:$mockito_version""
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.9.0'
    }
    plugins {
        grpc {
            artifact = ""io.grpc:protoc-gen-grpc-java:1.22.1""
        }
        javalite {
            artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
        }
    }
    generateProtoTasks {
        all()*.plugins {
            javalite {}
        }
        ofNonTest()*.plugins {
            grpc {
                // Options added to --grpc_out
                option 'lite'
            }
        }
    }
}
</code></pre>

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

<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.10'
        classpath ""org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version""
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code></pre>

<p>I'm currently unable to find what exactly would cause such an error. I've also looked around for answers/insights to no avail.</p>

<p>Any input is appreciated.</p>
",https://stackoverflow.com/questions/57990053/hit-with-unimplemented-method-statusruntimeexception-when-unit-testing-generated,"['android', 'unit-testing', 'kotlin', 'mockito', 'grpc']",4006,True,0,2
Do I need a unit-testing framework if I&#39;m already using Cypress in a Vue.js app?,"<p>When scaffolding a new project with the Vue.js CLI, it offers a choice of both unit-testing and E2E-testing frameworks. </p>

<p>Unit-testing functionality is perfectly adequate in Cypress. My question, then: is there an advantage to using a distinct unit-testing framework if I'm already using Cypress?</p>
",https://stackoverflow.com/questions/54764650/do-i-need-a-unit-testing-framework-if-im-already-using-cypress-in-a-vue-js-app,"['unit-testing', 'vue.js', 'cypress', 'end-to-end']",1535,True,8,1
Method in base class does not exist during unit testing with mocha of Vue component,"<p>When I have a component in Vue that extends from a base class, it works in run time in the browser, as expected. But when unit testing with mocha, the method on the base class disappears. In the simple example below this results in the error <code>TypeError: this.methodInBaseClass is not a function</code>. But in runtime it works, then the message <code>Some other data</code> is shown, as I would expect.</p>

<p>What is going wrong? And more importantly, how to fix it?</p>

<p>Consider this simple Vue component:</p>

<pre><code>&lt;template&gt;
    &lt;div&gt;{{ myData }}&lt;/div&gt;
&lt;/template&gt;

&lt;script lang=""ts""&gt;
import { Component, Prop, Vue } from 'vue-property-decorator';
import BaseClass from '@/components/BaseClass.vue';

@Component
export default class HelloWorld extends BaseClass {
    @Prop() private msg!: string;

    private created(): void {
        this.methodInBaseClass();
    }
}
&lt;/script&gt;
</code></pre>

<p>and the base class</p>

<pre><code>&lt;script lang=""ts""&gt;
import { Component, Prop, Vue } from 'vue-property-decorator';
export default class BaseClass extends Vue {
    protected myData: string = 'Some data';

    protected methodInBaseClass(): void {
        this.myData = 'Some other data';
    }
}
&lt;/script&gt;
</code></pre>

<p>and the unit test</p>

<pre><code>import { expect } from 'chai';
import { shallowMount } from '@vue/test-utils';
import HelloWorld from '@/components/HelloWorld.vue';

describe('HelloWorld.vue', () =&gt; {
    it('Data is mutated', () =&gt; {
        const wrapper = shallowMount(HelloWorld);
        expect(wrapper.html()).to.include('Some other data');
    });
});
</code></pre>
",https://stackoverflow.com/questions/55429318/method-in-base-class-does-not-exist-during-unit-testing-with-mocha-of-vue-compon,"['typescript', 'unit-testing', 'inheritance', 'vue.js', 'mocha.js']",638,True,2,2
"Unit testing React stateless component wrapped with withRouter() in Enzyme, how to pass match parameter","<p>I'm trying to test a React functional component that I've wrapped in withRouter from react-router-dom. The component structure is as below.</p>

<pre><code>import * as React from 'react';
import { Switch, Route, withRouter, RouteComponentProps } from 'react-router-dom';


export interface Props extends RouteComponentProps {
    closeModalLinkPath: string;
    closeModalFunction: any;
}

const RouterWrappedComponent= withRouter(({ match, history, closeModalLinkPath, closeModalFunction }: Props) =&gt; {

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

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

<p>This structure works perfectly in the browser, however I am having difficulty writing unit tests. Due to the nature of the component I need an accurate match object but I can't find any way of passing this through on generation.</p>

<pre><code>var routerWrappedComponent= Enzyme.mount(&lt;MemoryRouter initialEntries={[`/studio/00000000-0000-0000-0000-000000000000/manage`]}&gt;
    &lt;RouterWrappedComponent closeModalFunction={() =&gt; { }} closeModalLinkPath={`/studio/00000000-0000-0000-0000-000000000000`} /&gt;
&lt;/MemoryRouter&gt;);
</code></pre>

<p>Despite the component's props inheriting from <code>RouteComponentProps</code> I can't add this to the components props and I can't find any variation of <code>MemoryRouter</code> that will let me pass match in through props, can anyone help?</p>

<p>EDIT: The withRouter wrapping came from <a href=""https://stackoverflow.com/questions/45244413/passing-props-to-a-react-component-wrapped-in-withrouter-function"" >here</a></p>
",https://stackoverflow.com/questions/54221448/unit-testing-react-stateless-component-wrapped-with-withrouter-in-enzyme-how,"['reactjs', 'typescript', 'react-router', 'react-router-v4']",1512,True,2,1
"Vue Unit Testing: How to test complex components with props, vuex store, watchers, getters etc","<p>I have a question about unit testing (Jest) within a vue app - I guess it is rather an architectural question, but maybe specific code examples could also help me out.</p>

<p>I have sketched out a more or less complex setup of vue components from my app. They are still simplified but I guess they should help to describe the situation.</p>

<p><a href=""https://i.stack.imgur.com/Tt21v.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Tt21v.png"" alt=""Vue Parent and Children components""></a>
<a href=""https://gofile.io/?c=jvtx0f"" rel=""nofollow noreferrer"">(PDF Attachment for those preferring non-pixel data :)</a></p>

<p>I have a <strong>Wrapper</strong> which has three child components:</p>

<ul>
<li><strong>Search</strong> (Input field to search on Map)   </li>
<li><strong>List</strong> (List of stores, represented also as markers on map)</li>
<li><strong>Map</strong> (Google Map itself)</li>
</ul>

<p>I would really like to write some unit tests for this, but it seems so super tedious to setup those tests, so that I doubt that this is the way to do it.</p>

<p>It starts with the way I load the google maps API: The wrapper loads it asynchronously, sets API key etc. As soon as the google map API is loaded it passes it down to the children.</p>

<p>Of course the map only really starts to load, create and display markers, as soon as <code>google</code> is present and I can use <code>new this.google.maps.Map()</code> for example.</p>

<p>Even if I would like to test some methods of the <strong>Map</strong> component, I have to provide an actual google object, because otherwise the whole init process in <code>mount()</code> fails. It can't make a map. </p>

<p><em>So do I have to load the actual google's map API in my tests? Or could I somehow skip mounting the map but still test a few isolated methods?</em></p>

<p>Further you can see that my <strong>Map</strong> watches a getter from the vuex store: Whenever the <code>searchCoordinates</code> set by <strong>Search</strong> change in my vuex store, I want to execute some functions (for example center my map to the new search coordinates or remove a current location marker if the search did not return valid searchCoordinates).</p>

<p><em>How could I somehow break down the interlinking between these components, but still write good and helpful tests, which help me to guarantee that the app does what it is supposed to do?</em></p>

<p>I know that I can use a vuex store within my tests (<a href=""https://medium.com/@lachlanmiller_52885/mocking-vuex-in-vue-unit-tests-b6eda1c4d301"" rel=""nofollow noreferrer"">Medium article about vuex testing</a>).
But still I feel like the whole app is so much inter-connected that doing actual <em>unit testing</em> – testing one small piece at a time – is impossible.
It seems like that I would have to mount not only <strong>Map</strong> alone, but also the other components and a vuex store with actual data, to really write bulletproof tests.</p>

<p><em>A few other examples, where I struggle:</em></p>

<ul>
<li>In my <code>mounted()</code> I subscribe to an action with <code>this.$store.subscribeAction((action) =&gt; {...</code> - of course $store is undefined in my tests. <a href=""https://lmiller1990.github.io/vue-testing-handbook/vuex-in-components.html#using-a-mock-store"" rel=""nofollow noreferrer"">Should I mock it</a>?</li>
<li>As I said I am watching a getter: This throws errors like <code>TypeError: Cannot use 'in' operator to search for 'searchCoordinates' in undefined</code>. Would I have to mock all the getters as well? If so: what remains to be tested? If I mock (~=leave away) all the vuex stuff, it seems to me, that testing becomes useless...</li>
</ul>

<p>But maybe I am mistaken here. Also I am quite new to unit testing, so any hints are very welcome.
Thank you very much in advance. I hope somebody has some valuable input.
All those examples (even in books like <a href=""https://www.oreilly.com/library/view/vuejs-up-and/9781491997239/"" rel=""nofollow noreferrer"">Vue.js - up and running</a>) are always broken down to very simple and understandable examples, but on the other hand don't really reflect real-life apps...</p>

<p>Cheers</p>

<p>----- Edit:</p>

<p>I got a <code>needs more focus</code> vote by someone.
So I try to sum up simple and small questions:</p>

<p><strong>Summary of Questions</strong></p>

<ol>
<li>Does somebody have a general input on how to test larger and more complex vue applications?</li>
<li>Is there a way to test a component with a google map (or a component that is relying heavily on any third party code)</li>
<li>Is mocking getters, store and actions a good idea in this case? (I have my doubts there).</li>
<li>For testing watched properties from the vuex store, I read <a href=""https://stackoverflow.com/questions/49431735/how-to-test-vue-watcher-that-watches-a-computed-property-from-vuex"">in this thread</a> that <code>mapState</code> should be mocked. (in my case probably my getters). Does this make sense to mocke those getters in my case?</li>
<li>Is it best practice to simplify as many things as possible in an tested component (for example, I started to override some methods, which failed (the one including google map initiation) to just get my test up and running:</li>
</ol>

<pre><code>const initMapMock = jest.fn();
const initMarkersMock = jest.fn();
...
const wrapper = shallowMount(Map, {
    methods: {
        initMap: initMapMock, // replace initMap(), which needs google map API
        initMarkers: initMarkersMock,
      },
    ...

</code></pre>

<p>Does that make sense?</p>
",https://stackoverflow.com/questions/58922748/vue-unit-testing-how-to-test-complex-components-with-props-vuex-store-watcher,"['unit-testing', 'vue.js', 'jestjs', 'vuex', 'vue-test-utils']",997,True,2,1
How to write the unit testing for the file upload method in the Angular 7 (or 2+),"<p>I'm trying to write the unit testing for the file upload method in the angular 7. Getting the below error in the testing window. I'm new for angular unit testing. Could someone help, How to add mock files to get the full code coverage? </p>

<blockquote>
  <p>TypeError: Cannot set property 'value' of undefined</p>
</blockquote>

<p>Here is my unit test code (spec file),</p>

<pre><code>describe('ImportComponent', () =&gt; {
    let component: ImportComponent;
    let fixture: ComponentFixture&lt;ImportComponent&gt;;
    let element;

    beforeEach(
        async(() =&gt; {
            TestBed.configureTestingModule({
                imports: [ HttpClientModule, RouterTestingModule ],
                declarations: [ ImportComponent ]
            }).compileComponents();
        })
    );

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

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

    it('should upload the file', () =&gt; {
        component.importFile();
        const inputEl = element.querySelector('#postal_file');
        const fileList = { 0: { name: 'foo', size: 500001 } };
        inputEl.value = {
            target: {
                files: fileList
            }
        };
        inputEl.dispatchEvent(new Event('change'));     
    });
});
</code></pre>

<p>Method in the component</p>

<pre><code>importFile() {
        const inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#postal_file');
        const fileCount: number = inputEl.files.length;
        const formData = new FormData();
        if (fileCount &gt; 0) {
            formData.append(this.postalFileName, inputEl.files.item(0));
            this.postalService.importPostalCodes(formData).subscribe((data) =&gt; {
                this.result = data;
            });
        }
    }
</code></pre>

<p>and the HTML,</p>

<pre><code>&lt;div class=""file-import""&gt;
        &lt;form action="""" method=""post"" encType=""multipart/form-data""&gt;
            &lt;label for=""postal_file""&gt;Choose File&lt;/label&gt;
            &lt;input type=""file"" name=""postal_file"" id=""postal_file""&gt;
            &lt;button type=""button"" (click)=""importFile()""&gt;Import&lt;/button&gt;
        &lt;/form&gt;
    &lt;/div&gt;
</code></pre>

<p>The unit test is not covered all the code as shown in the below image, please help , how to ge the 100% code coverage.</p>

<p><a href=""https://i.stack.imgur.com/79N1b.png"" rel=""noreferrer"">Code coverage image</a></p>
",https://stackoverflow.com/questions/55356093/how-to-write-the-unit-testing-for-the-file-upload-method-in-the-angular-7-or-2,"['angular', 'karma-jasmine', 'angular-test']",22175,True,12,2
How to share data between parent and child components in Angular for easier unit testing,"<p>I have a main component which is a matrix full of information. Selections can be made across the header items as well as the left rows(first column items). When selections are made both right and left sidebars have different options and statistics that can be worked with.</p>

<pre><code>class ParentComponent { } 
class SelectedCategoryComponent { } 
class SelectedRoleComponent { } 
class OtherComponent { } 
</code></pre>

<p>Given that the sidebars use related data to the selections, what would be the best way to share the information? </p>

<p>One way would be to use named router-outlets for the side bars. This would be mean that any requests would be made on component loading and in fact reusing the layout can become complicated without using named router-outlets in this scenario. This would allow for navigating back to previous states and may make unit testing a little easier to manage with fewer data dependencies. The downside seems that the routing will be more challenging. </p>

<pre><code>class ParentComponent { } 

// id is passed to the components via named router-outlets
class SelectedCategoryComponent { } 
class SelectedRoleComponent { } 
class OtherComponent { } 
</code></pre>

<p>Now, if I take the path of using parent-component/child-component relationship I think it may be harder to test since there are data dependencies. The back and forth communication may be a little trickier to implement as well as the layout having to be hard-coded into the parent view. </p>

<pre><code>// All hosted on the same page
class ParentComponent { } 
class SelectedCategoryComponent { } 
class SelectedRoleComponent { } 
class OtherComponent { } 

@Injectable({...})
class SharedDataService 
{ 
   sharedState: T;
}
</code></pre>

<p>What is the best way to connect these components as the user interface increases in complexity to ensure easiest possible unit-testing experience? </p>
",https://stackoverflow.com/questions/55034108/how-to-share-data-between-parent-and-child-components-in-angular-for-easier-unit,"['angular', 'unit-testing', 'angular-ui-router', 'components']",58,False,1,0
How do I test did a message box shows up or not in unit testing?,"<p>I wanted to test, will the message box show up when my code request it. But I am not so sure what to assert or am I even doing the right thing. </p>

<pre><code>public void btnSave_Click(object sender, EventArgs e)
        {
            if(txtFirstName.Text.Trim() != """" &amp;&amp; txtLastName.Text.Trim() != """" &amp;&amp; txtContact.Text.Trim() != """")
            {
                Regex reg = new Regex(@""^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$""); // Only accepting proper email
                Match match = reg.Match(txtEmail.Text.Trim());
                if (match.Success)
                { using (SqlConnection sqlCon = new SqlConnection(connectionString)) // Connecting info to database
                    {
                        sqlCon.Open();
                        SqlCommand sqlCmd = new SqlCommand(""ContactAddorEdit"", sqlCon);
                        sqlCmd.CommandType = CommandType.StoredProcedure;
                        sqlCmd.Parameters.AddWithValue(""@PhoneBookID"", PhoneBookID); //connecting each value to database
                        sqlCmd.Parameters.AddWithValue(""@FirstName"", txtFirstName.Text.Trim());
                        sqlCmd.Parameters.AddWithValue(""@LastName"", txtLastName.Text.Trim());
                        sqlCmd.Parameters.AddWithValue(""@Contact"", txtContact.Text.Trim());
                        sqlCmd.Parameters.AddWithValue(""@Email"", txtEmail.Text.Trim());
                        sqlCmd.Parameters.AddWithValue(""@Address"", txtAddress.Text.Trim());
                        sqlCmd.ExecuteNonQuery(); // Executing the query in database
                        MessageBox.Show(""Submitted successfully""); // Showing message when success
                        Clear(); // Clearing the form
                        GridFill();// Refreshing the table
                    }
                }
                else
                {
                    MessageBox.Show("" Please enter a valid Email""); // Showing message when email is not valid
                }
            }
            else
            {
                MessageBox.Show(""Please fill Mandatory fields""); // If no input this message will show
            }

        }
</code></pre>

<p>So if the text box got a empty string there will be an message box pops up and say ""Please fill Mandatory fields""</p>

<p>and here is the test that I am trying write</p>

<pre><code>        [TestMethod]
        public void TestMethod1()
        {
            Form1 form1 = new Form1();
            form1.txtFirstName.Text = """";
            Assert.IsTrue(MessageBox.Show(""Please fill Mandatory fields"") ;
        }
</code></pre>

<p>What kind of assert should and use and how do I write it? Can I test it like this? Thank you</p>
",https://stackoverflow.com/questions/56403767/how-do-i-test-did-a-message-box-shows-up-or-not-in-unit-testing,"['c#', 'winforms', 'unit-testing', 'mstest', 'messagebox']",718,True,2,1
Unit Testing Express with mocha/chai/sinon - how do I test my res.send object shape?,"<p>I am unit testing the individual components that lead up to an API response, in other words, I'm testing it independently of a route since every route runs through this component</p>

<p>I need to test that the function responsible for sending my express response is the correct shape, but without sending an actual HTTP request I can't figure out how to test it.</p>

<p>Here is my component</p>

<pre><code>'use strict'

const moment = require('moment')
module.exports = (req, res, payload) =&gt; {
  try {
    let data = []
    if (payload.token) data.push({ token: payload.token })
    data.push({ [payload.resource]: payload.data })
    res.send({
      status: 'OK',
      recordCount: payload.data.length,
      startTimestamp: req.start.toDate(),
      endTimestamp: moment().toDate(),
      timeTaken: moment().toDate().getTime() - req.start.toDate().getTime(),
      data: data
    })
  } catch (error) {
    return res.status(500).json({
      errors: [{
        location: 'n/a',
        param: 'n/a',
        msg: 'something happened when generating the response'
      }]
    })
  }
}
</code></pre>

<p>here is my current test ...</p>

<pre><code>const chai = require('chai')
const sinonChai = require('sinon-chai')
const { mockReq, mockRes } = require('sinon-express-mock')
const moment = require('moment')
const present = require('../../src/lib/present')

chai.use(sinonChai)

describe('unit test the present lib method', () =&gt; {
  it('should return the expected shape', (done) =&gt; {
    const req = mockReq({
      start: moment().toDate(),
      body: {}
    })
    const res = mockRes()
    const shape = present(req, res, {
      resource: 'empty_array',
      data: []
    })
    shape.should.have.own.property('data') // doesnt work
    // AssertionError: expected { Object (append, attachement, ...) } to have own property 'data'
    done()
  })
})
</code></pre>
",https://stackoverflow.com/questions/56471968/unit-testing-express-with-mocha-chai-sinon-how-do-i-test-my-res-send-object-sh,"['node.js', 'express', 'mocha.js', 'chai', 'sinon']",813,False,1,1
How to utilize a variable from a different class in a unit testing in Scala?,"<p>I want to utilize the variable <code>numberOwned</code> from a different class in my test file in Scala. How do I do that?</p>

<p>Here is what I attempted.</p>

<p>TestEquipment.scala:</p>

<pre><code>package tests
import clicker.equipment._
import org.scalatest._

class TestEquipment extends FunSuite {
    numberOwned = 0
        test(""first test""){
    }
}
</code></pre>

<p>Equipment.scala</p>

<pre><code>package clicker.equipment

abstract class Equipment{

var numberOwned = 0
var name: String = """"

def goldPerSecond(): Double

}
</code></pre>

<p>File Directory </p>

<pre><code>src
 |_clicker
 |     |_ equipment
 |           |_Equipment.scala
 |_ tests
      |_ TestEquipment.scala
</code></pre>
",https://stackoverflow.com/questions/54934726/how-to-utilize-a-variable-from-a-different-class-in-a-unit-testing-in-scala,"['java', 'scala', 'unit-testing', 'class', 'methods']",329,False,1,2
Spring Boot - use H2 for unit testing AND for quick development (with a Spring profile),"<p>How can I use H2 both for the normal Unit Testing AND during (the first part of) development? I could start the application with a specific Spring Profile so that the application-h2.properties would be selected. </p>

<p>I have two projects: for simplicity I used exactly the same POM files. </p>

<p>When I create a simple Spring Boot Application -- immediately inserting/reading db stuff, then all works fine. </p>

<p>Important dependencies are: </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;
&lt;dependency&gt;
  &lt;groupId&gt;com.h2database&lt;/groupId&gt;
  &lt;artifactId&gt;h2&lt;/artifactId&gt;
  &lt;scope&gt;runtime&lt;/scope&gt;
  &lt;!--&lt;scope&gt;test&lt;/scope&gt;--&gt;
&lt;/dependency&gt;
</code></pre>

<p>When I have an Angular / Spring Boot application, again with the same Maven dependencies, thus with much web stuff, then I keep on getting this error: </p>

<blockquote>
  <p>IllegalStateException: Cannot load driver class: org.h2.Driver</p>
</blockquote>

<p><strong>UPDATE</strong>: When looking for the maven dependency tree, in both projects I get the dependency: </p>

<pre><code>[INFO] +- com.h2database:h2:jar:1.4.197:compile
</code></pre>

<p><strong>UPDATE</strong>: Even when I put the h2 dependency with scope 'runtime', unit testing still works with h2 AND the driver is not found</p>

<pre><code>[INFO] +- com.h2database:h2:jar:1.4.197:runtime
</code></pre>
",https://stackoverflow.com/questions/54468274/spring-boot-use-h2-for-unit-testing-and-for-quick-development-with-a-spring-p,"['spring-boot', 'maven-3', 'spring-test']",610,False,1,0
How to do Django unit testing - to reuse data from 1 Database via 1 class,"<p>As you can see in the setUpClass we define user and profile.</p>

<p>When you look at the method:</p>

<pre><code>test_create_project
</code></pre>

<p>All is working fine and the test passes. Idea is since the Project and Position was created via that method, I would like to use it from DB in the method:</p>

<pre><code>test_homepage
</code></pre>

<p>Problem is when you try to read them from DB they do not exist anymore. My question is why. I know if I create project in the </p>

<pre><code>setUpClass
</code></pre>

<p>then it would be in the DB. My point is not to create extra Project and Position if I can create it via that method 1st - test it and then reuse it in the next one - but not via using (self) but by reading from DB.</p>

<p>Question1:</p>

<pre><code>Is that possible?
</code></pre>

<p>Question2:</p>

<pre><code>Are methods in this class using separated DBes?
</code></pre>

<p>Question3:</p>

<pre><code>What is the most efficient - and proper approach to this - my point is not to create extra records and reuse data as we go.
</code></pre>

<p>These coming out empty in the test_homepage method:</p>

<pre><code>    print(project)
    print(positions)
</code></pre>

<p>Django 2.2 Tests:</p>

<pre><code>from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone

from stb.core.models import Profile, Skill, Project, Position

class EntireAppTest(TestCase):

    """"""Updating Profile""""""

    @classmethod
    def setUpClass(cls):
        """"""Creating User""""""
        super().setUpClass()
        cls.user = User.objects.create_user(
            username='johnconnor',
            email='dude@nasa.gov',
            password='terminator'
        )
        cls.profile = Profile.objects.get(user=cls.user)
        skill = Skill()
        skill.save()
        skill.profile.add(cls.profile.id)
        skill.title='python'
        skill.save()

    def setUp(self):
        self.client.login(username='johnconnor', password='terminator')


    def test_create_account(self):
        self.user = User.objects.get(email='dude@nasa.gov')
        self.assertEqual(User.objects.count(), 1)
        self.assertEqual(self.user.username, 'johnconnor')
        self.assertEqual(self.user.email, 'dude@nasa.gov')


    def test_create_profile(self):
        self.profile = Profile.objects.get(user=self.user)
        now = timezone.now()
        self.assertLess(self.profile.pub_date, now)

    def test_create_project(self):
        url = '/project/new/'
        response = self.client.post(
            url,
            data={
                'profile': self.profile,
                'title': 'NASA JPL',
                'position_formset-TOTAL_FORMS': 1,
                'position_formset-INITIAL_FORMS': 0,
                'position_formset-0-title': 'Python Developer',
                'position_formset-0-description': 'description',
            },
        )
        project = Project.objects.get(id=1)
        position = Position.objects.get(project=project)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(project.title, 'NASA JPL')
        self.assertEqual(position.title, 'Python Developer')

    def test_homepage(self):
        url = '/'
        response = self.client.get(
            url,
            data={},
        )
        positions = Position.objects.all()
        project = Project.objects.all()
        print(project)
        print(positions)
        # print(response.context)
        self.assertEqual(response.status_code, 200)
</code></pre>
",https://stackoverflow.com/questions/55876541/how-to-do-django-unit-testing-to-reuse-data-from-1-database-via-1-class,"['django', 'database', 'unit-testing', 'django-testing', 'django-tests']",260,False,1,0
What are best practices for unit testing multiple functions that have very similar test scenarios?,"<p>Let's say I have two pure functions, <code>pureFn1</code> and <code>pureFn2</code>. These functions must pass similar tests.</p>

<pre><code>describe(""generic function"", () =&gt; {
  it(""should fulfill condition 1"", testCondition1);

  it(""should fulfill condition 2"", testCondition2);

  it(""should fulfill condition 3"", testCondition3);

  it(""should fulfill condition 4"", testCondition4);
});
</code></pre>

<p>How would the similar tests be written for these functions? Should the test suite be reusable?</p>

<p>For example, if we reused the test suite, it will end up looking like this:</p>

<pre><code>const reusableTestSuite = (codeUnderTest) =&gt; {
  describe(`${codeUnderTest.name}`, () =&gt; {
    it(""should fulfill condition 1"", testCondition1(codeUnderTest));

    it(""should fulfill condition 2"", testCondition2(codeUnderTest));

    it(""should fulfill condition 3"", testCondition3(codeUnderTest));

    it(""should fulfill condition 4"", testCondition4(codeUnderTest));
  });
};

reusableTestSuite(pureFn1);
reusableTestSuite(pureFn2);
</code></pre>

<p>This is pretty DRY, but the problem is there is an abstraction which might make the tests harder to read and modify, and thus possibly discourage devs from writing more tests in the name of speed and ease. This is discussed in point 8 of <a href=""https://medium.com/@me_37286/yoni-goldberg-javascript-nodejs-testing-best-practices-2b98924c9347"" rel=""nofollow noreferrer"">this article</a>. When these abstracted tests break, the next developer might hate to read it.</p>

<p>The other option is to copy-paste the tests:</p>

<pre><code>describe(""pureFn1"", () =&gt; {
  it(""should fulfill condition 1"", testCondition1Fn1);

  it(""should fulfill condition 2"", testCondition2Fn1);

  it(""should fulfill condition 3"", testCondition3Fn1);

  it(""should fulfill condition 4"", testCondition4Fn1);
});

describe(""pureFn2"", () =&gt; {
  it(""should fulfill condition 1"", testCondition1Fn2);

  it(""should fulfill condition 2"", testCondition2Fn2);

  it(""should fulfill condition 3"", testCondition3Fn2);

  it(""should fulfill condition 4"", testCondition4Fn2);
});
</code></pre>

<p>This is full-on code duplication. There is no abstraction. If we had two functions with 20 common properties between them, we would have to copy and paste 20 tests and remember to update all the similar tests when one changes, forever.</p>

<p>So between these approaches, which is the better method? Or is there a third method, a best practice in writing unit tests in a way that we get the benefits of abstraction while not making it hard for the next developer to immediately learn what went wrong, and thus <em>not</em> discourage them from writing more of these tests?</p>
",https://stackoverflow.com/questions/56664159/what-are-best-practices-for-unit-testing-multiple-functions-that-have-very-simil,"['javascript', 'node.js', 'unit-testing', 'testing', 'mocha.js']",190,False,1,0
Unit testing Vuejs JSX components with composition api with jest. Issues with mounting and assertions,"<p>I am trying to test a jsx component by passing props to it and asserting that it renders them correctly. This fails though for a reason I cannot understand. Here's the component</p>

<pre class=""lang-js prettyprint-override""><code>// components/toast.tsx

import { createComponent } from ""@vue/composition-api"";
import style from ""./toast.module.scss"";
export default createComponent({
  name: ""Toast"",
  props: {
    message: String
  },
  setup(props) {
    return () =&gt; (
      &lt;div class={style.toast}&gt;
        &lt;p&gt;{props.message}&lt;/p&gt;
      &lt;/div&gt;
    );
  }
});
</code></pre>

<p>Here's the snippet of the unit test that is failing:</p>

<pre class=""lang-js prettyprint-override""><code>// tests/unit/components/toast.spec.ts

import Toast from ""@/components/toast"";
import { shallowMount } from ""@vue/test-utils"";

// ... a describe block

  it(""should render props correctly"", () =&gt; {
    const msg = ""hello"";
    const wrapper = shallowMount(Toast, {
      propsData: {
        message: msg
      }
    });
    expect(wrapper.isVueInstance()).toBeTruthy();
    expect(wrapper.text()).toMatch(msg);
  });
</code></pre>

<p>And the output from the failing test is here:</p>

<pre><code>Expected substring: ""hello""
    Received string:    ""function (el) {
          var obj;·
          var args = [], len = arguments.length - 1;
          while ( len-- &gt; 0 ) args[ len ] = arguments[ len + 1 ];
          if (shouldNotBeStubbed(el, stubs, modifiedComponents)) {
            return originalCreateElement.apply(void 0, [ el ].concat( args ))
          }·
          if (isConstructor(el) || isComponentOptions(el)) {
            if (stubAllComponents) {
              var stub = createStubFromComponent(el, el.name || 'anonymous', _Vue);
              return originalCreateElement.apply(void 0, [ stub ].concat( args ))
            }
            var Constructor = shouldExtend(el, _Vue) ? extend(el, _Vue) : el;·
            return originalCreateElement.apply(void 0, [ Constructor ].concat( args ))
          }·
          if (typeof el === 'string') {
            var original = resolveComponent(el, originalComponents);·
            if (!original) {
              return originalCreateElement.apply(void 0, [ el ].concat( args ))
            }·
            if (isDynamicComponent(original)) {
              return originalCreateElement.apply(void 0, [ el ].concat( args ))
            }·
            var stub$1 = createStubIfNeeded(stubAllComponents, original, _Vue, el);·
            if (stub$1) {
              Object.assign(vm.$options.components, ( obj = {}, obj[el] = stub$1, obj));
              modifiedComponents.add(el);
            }
          }·
          return originalCreateElement.apply(void 0, [ el ].concat( args ))
        }""

      16 |     });
      17 |     expect(wrapper.isVueInstance()).toBeTruthy();
    &gt; 18 |     expect(wrapper.text()).toMatch(msg);
         |                            ^
      19 |   });
      20 | });
      21 | 

      at Object.it (tests/unit/components/toast.spec.ts:18:28)
</code></pre>

<p>Everything works! except for this one part. If I use a single file component (<code>.vue</code>) the component mounts and the test passes with no problem.</p>
",https://stackoverflow.com/questions/59227808/unit-testing-vuejs-jsx-components-with-composition-api-with-jest-issues-with-mo,"['typescript', 'unit-testing', 'vue.js', 'jsx', 'vue-composition-api']",406,False,1,0
Laravel unit testing if an event is triggered when an eloquent model event is triggered,"<p>I am developing a Laravel application and writing tests as I go along the way. Now, I am having a problem writing a test that is asserting if an event is triggered when an eloquent model event is triggered. This is what I am doing.</p>

<p>This is my ItemObserver's created function</p>

<pre><code>public function created(Item $item)
{
    event(new NewItemCreated($item));
}
</code></pre>

<p>As you can see I am firing an event inside the created event of the eloquent model observer.</p>

<p>If I want to assert if an event is triggered in the test, I have to fake the event and then assert something like this.</p>

<pre><code>Event::fake();
factory(Item::class)-&gt;create(); //created function of observer should be triggered but it will not be
Event::assertDispatched(NewItemCreated::class);
</code></pre>

<p>As you can see in the test code I am trying to assert that if an event is triggered when an item is created. But the test will never pass because the created function of the observer class is never called because the Event is faked in the test. How can I test this scenario? </p>
",https://stackoverflow.com/questions/57964068/laravel-unit-testing-if-an-event-is-triggered-when-an-eloquent-model-event-is-tr,"['laravel', 'laravel-testing', 'laravel-events']",2091,True,1,1
What is the point of mocking the method of an external library when unit testing?,"<p>What is the point of mocking the method of an external library when unit testing?</p>

<p>Let's say that I have a function that uses XYZ library to get the current user using a given authorization token, and then if it finds the user, it returns a valid AWS policy:</p>

<pre><code>export const getUser = async token =&gt; {
  const user = await XYZ.getUser(token)
  return {
    // valid policy
    context: user,
  }
}
</code></pre>

<p>If an invalid token is given, the <code>getUser</code> should throw an error.</p>

<ul>
<li>What is the point of testing this function if the <code>XYZ.getUser</code> is already well tested? </li>
<li>Why mock the <code>getUser</code> instead of using the real one?</li>
</ul>
",https://stackoverflow.com/questions/56678063/what-is-the-point-of-mocking-the-method-of-an-external-library-when-unit-testing,"['javascript', 'node.js', 'unit-testing', 'testing']",313,False,0,2
Xcode Unit Testing with C++: candidate found by name lookup is and reference is ambiguous,"<p>I am trying to move a few tests into the XCTest target of my application in Xcode. The library I am testing functionalities for is large, and I include its header files inside my tests.mm file (my Obj-C++ testing file where all unit test cases are). </p>

<p>For one specific ""Size"" type, Compiler reports a series of ambiguous clashes with the Size type already defined as part of the SDK for MacOS10.13 (in /usr/include). Here is how the #include set for my testing file looks like:</p>

<pre><code>#import &lt;XCTest/XCTest.h&gt;

#include &lt;ql/quantlib.hpp&gt;.   &lt;---- defines Size, which clashes with MacTypes.h definition
#include &lt;Analytics/all.hpp&gt;
#include &lt;boost/timer.hpp&gt;
#include &lt;utility&gt;
#include &lt;typeinfo&gt;
#include &lt;thread&gt;
#include &lt;atomic&gt;
#include &lt;mutex&gt;
#include &lt;random&gt;
#include &lt;condition_variable&gt;
#include &lt;future&gt;

using namespace src::Utilities;
using namespace src::Simulation;
using namespace src::MarketData;
using namespace src::detail;
using namespace std::placeholders;

//...More code down here, but not problematic
</code></pre>

<p> is the file which contains the definition for Size. Can someone please help spot where I may have gone wrong, especially that when I run the tests as part of a giant Main() function, it all works fine.</p>

<p>Thanks,
Amine</p>
",https://stackoverflow.com/questions/58099543/xcode-unit-testing-with-c-candidate-found-by-name-lookup-is-and-reference-is,"['c++', 'xcode', 'objective-c++']",1424,False,0,1
"In Android projects, what&#39;s the reasonable code coverage that can be achieved by Unit Testing?","<p>In my recent Android project I am asked to set a goal for Unit Test Coverage. I want to know what's the reasonable amount of coverage achievable, 30%, 50% or 70%?</p>
",https://stackoverflow.com/questions/55704618/in-android-projects-whats-the-reasonable-code-coverage-that-can-be-achieved-by,"['android', 'unit-testing']",143,True,0,1
Unit testing an Angular service with Router dependency: &quot;TypeError: Cannot read property &#39;navigate&#39; of undefined&quot;,"<p>I am trying to test a simple service that uses the Router as a dependency and writes all routes to a history array. I am more or less using the service described on <a href=""https://blog.hackages.io/our-solution-to-get-a-previous-route-with-angular-5-601c16621cf0"" rel=""nofollow noreferrer"">this tutorial</a>.</p>

<p>I have tried all the solutions I could find in the Angular.io documentation. I have tried several solutions here on StackOverflow. I even tried adding routes to mock components, declaring them, and adding those to <code>RouterTestingModule.withRoutes()</code>. For some reason, <code>router</code> is <code>undefined</code> in all cases.</p>

<pre><code>describe('Route State service', () =&gt; {
    let routeStateService: RouteStateService;
    let router: Router;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [RouterTestingModule],
            providers: [RouteStateService]
        });

        router = TestBed.get(Router);
        routeStateService = TestBed.get(RouteStateService);
        router.initialNavigation();
    });

    describe('should add each route to history', () =&gt; {
        router.navigate(['/test']);
        expect(routeStateService.history.length).toBeGreaterThan(0);
    });

});
</code></pre>

<p>The error is fairly straight forward, but for some reason I am unable to get ""router"" to be defined by normal means. What am I missing?</p>
",https://stackoverflow.com/questions/58454028/unit-testing-an-angular-service-with-router-dependency-typeerror-cannot-read,"['angular', 'typescript', 'unit-testing']",884,True,0,1
React (Unit &amp; Integration): Which framework to use for react unit testing and Integration testing,"<p>I have just started with development in Reactjs. I am looking for testing framework(Javascript). Which can be used to do both ""Unit Testing"", ""Integration Testing"" and ""e2e testing"". </p>

<p>Please, help me if we can do the the required testing using Javascript.</p>
",https://stackoverflow.com/questions/57039857/react-unit-integration-which-framework-to-use-for-react-unit-testing-and-in,"['javascript', 'reactjs', 'unit-testing', 'integration-testing']",204,True,0,3
Dart Unit Testing: how to specify that I does not care about a certain value?,"<p>Imagine I have a stream that emits strings. I care about only second emission's value for a certain unit test and the first one isn't important.</p>

<p>I came up with</p>

<pre><code>expect(stream.skip(1).first, completion(""Value I care about""));
</code></pre>

<p>But is there a matcher for <code>emits*</code> method that actually says that any value is OK?</p>

<p>I want to write something like that:</p>

<pre><code>expect(stream, emitsInOrder([any, ""Value I care about""]));
</code></pre>

<p>But it fails with <code>any</code>.</p>
",https://stackoverflow.com/questions/56115990/dart-unit-testing-how-to-specify-that-i-does-not-care-about-a-certain-value,"['unit-testing', 'dart', 'stream']",43,False,0,1
Cakephp 3.5 : How to test login functionality without using Fixture for unit testing in phpunit?,"<p>I am using Cakephp-3.5 Auth Component in my application to verify user's credential. Now I have to write down unit test cases for login form. I have to write test cases not using Fixtures but only just in phpunit. I am unable to figure out how to solve this ?</p>
",https://stackoverflow.com/questions/58836615/cakephp-3-5-how-to-test-login-functionality-without-using-fixture-for-unit-tes,"['cakephp', 'cakephp-3.x', 'phpunit', 'cakephp-3.5']",65,False,0,0
How to make unit testing when the returned value of method is a mock expectation,"<p>Return of method ""ContractService"" is a return value of method ""checkPgwContract"". I'm already mock the ContractService class and ContractServiceManager class, but method of checkPgwContract always passed in my unit test.</p>

<p><strong>ContractServiceImpl</strong></p>

<pre><code>@Override
public List getListOfContractBy(String contractNo) {
List&lt;OasysContract&gt; oasysContractList = oasysContractRepository.findByContractNumber(contractNo);
if (!oasysContractList.isEmpty()) {
        return oasysContractList;
    } else {
        List&lt;Contract&gt; pgwContractList = contractRepository.findContractsByContractNumber(contractNo);
        if (!pgwContractList.isEmpty()) {
            return contractServiceManager.checkPgwContract(pgwContractList);
        }
    }
    return new ArrayList();
}
</code></pre>

<p><strong>ContractServiceManagerImpl</strong></p>

<pre><code>private boolean checkHCP(String contractNumber) {
    return contractRepository.findContractByExpiredDate(contractNumber) != null ? true : false;
}

private String checkIsFullyPaid(String contractNumber) {
    return contractRepository.getFullyPaid(contractNumber);
}

@Override
public List&lt;Contract&gt; checkPgwContract(List&lt;Contract&gt; contractList) {
    for (Contract contract : contractList) {
        //check paymentType
        if (contract.getPaymentType() != null &amp;&amp;
                contract.getPaymentType().equals(PAYMENT_TYPE_HCP)) {
            if (checkHCP(contract.getContractNumber())) {
                //check isFullyPaid
                if (checkIsFullyPaid(contract.getContractNumber()).equals(FLAG_YES)) {
                    return new ArrayList&lt;&gt;();
                }
            } else {
                return new ArrayList&lt;&gt;();
            }
        }
    }
    return contractList;
}
</code></pre>

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

<pre><code>@InjectMocks
@Spy
private ContractServiceImpl service;

@Mock
ContractRepository contractRepository;

@Mock
OasysContractRepository oasysContractRepository;

@Mock
ContractServiceManager serviceManager;


public static final String contractNumber = ""3900006835"";

@Test
public void getListOfContractBy_hcp_success() {
    List&lt;OasysContract&gt; oasysContractList = new ArrayList&lt;&gt;();
    oasysContractList.isEmpty();

    List&lt;Contract&gt; contractList = new ArrayList&lt;&gt;();
    contractList.add(BuildUtil.buildContract());

    //mock
    Mockito.doReturn(oasysContractList).when(oasysContractRepository).findByContractNumber(contractNumber);
    Mockito.doReturn(BuildUtil.buildContractList()).when(contractRepository).findContractsByContractNumber(contractNumber);
    Mockito.doReturn(contractList).when(serviceManager).checkPgwContract(contractList);
    Mockito.doReturn(BuildUtil.buildContract()).when(contractRepository).findContractByExpiredDate(contractNumber);
    Mockito.doReturn(""N"").when(contractRepository).getFullyPaid(contractNumber);


    //test
    List&lt;Contract&gt; contracts = service.getListOfContractBy(contractNumber);

    System.out.println(contracts);

    assert(!contracts.isEmpty());
}
</code></pre>

<p>Now, the value of contracts parameter is empty. It should be return contractList. I think because mock of method checkPgwContract is ignored.</p>

<p>My test will still pass, which is obviously wrong, so how should I test this?</p>
",https://stackoverflow.com/questions/58546479/how-to-make-unit-testing-when-the-returned-value-of-method-is-a-mock-expectation,"['java', 'unit-testing', 'mockito', 'spring-boot-test', 'spy']",99,True,0,1
Error as Cannot read property &#39;subscribe&#39; . for activated route in angular 7 while unit testing,"<p>I am getting error as Cannot read property 'subscribe' of undefined for activated route in angular 7 while unit testing .I have tried it in multiple way kindly help . </p>

<p>Observer.of is not working for me as i have rx.js version 6.3.3</p>

<p>here is my compnent file ChildComponent.ts</p>

<pre><code>import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
    selector: 'app-child',
    template: `
        &lt;h1&gt;Enter your name&lt;/h1&gt;
        &lt;form
              [formGroup]=""nameForm""
              (ngSubmit)=""submitForm(nameForm)""
        &gt;
            &lt;input
                   type=""text""
                   formControlName=""firstName""
                   placeholder=""first""
            &gt;
            &lt;input
                   type=""text""
                   formControlName=""lastName""
                   placeholder=""last""
            &gt;
            &lt;button type=""submit""&gt;launch to space&lt;/button&gt;
        &lt;/form&gt;
    `,
    styleUrls: ['./child.component.css']
})
export class ChildComponent {
    @Input() nameForm: FormGroup;
    private abc: number;
    constructor(
        public route: ActivatedRoute,
       ) {

        this.route.queryParams.subscribe(params =&gt; {
          this.abc = params['abc'];
        });

      }

    submitForm(form: FormGroup) {
        console.log(form);
        // really you would be using an event emitter
    }
}
</code></pre>

<p>here is my unit test file for child component unit test case</p>

<pre><code>
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormBuilder } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router, Data, Params } from '@angular/router';
import { Observable, of } from 'rxjs';
import { BehaviorSubject } from 'rxjs';


export class MockActivatedRoute {
    private paramsSubject = new BehaviorSubject(this.testParams);
    private _testParams: {};

    params  = this.paramsSubject.asObservable();

    get testParams() {
        return this._testParams;
    }
    set testParams(newParams: any) {
        this._testParams = newParams;
        this.paramsSubject.next(newParams);
    }
}


import { ChildComponent } from './child.component';


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

    class MockActivatedRoute1 extends ActivatedRoute {
    constructor() {
        super();
        this.params = of({id: ""5""});
    }
  }

    // create new instance of FormBuilder
    const formBuilder: FormBuilder = new FormBuilder();
    let activeRoute: MockActivatedRoute;  


    beforeEach(() =&gt; {
        activeRoute = new MockActivatedRoute();
    });


    beforeEach(
        async(() =&gt; {
            TestBed.configureTestingModule({
                declarations: [
                    ChildComponent
                ],
                imports: [
                    CommonModule,
                    ReactiveFormsModule,
                    //AppModule
                ],
                providers: [
                    // reference the new instance of formBuilder from above
                    { provide: FormBuilder, useValue: formBuilder },
                    {
                        provide: ActivatedRoute,
                        useValue: {
                            params: {
                                subscribe: (fn: (value: Data) =&gt; void) =&gt; fn({
                                    abc: 1
                                })
                            }
                        }
                    }
                ]
            }).compileComponents();
        })
    );

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(ChildComponent);
        component = fixture.componentInstance;

        // pass in the form dynamically
        component.nameForm = formBuilder.group({
            firstName: null,
            lastName: null
        });
        fixture.detectChanges();
    });

    it('should be created', () =&gt; {
        expect(component).toBeTruthy();
    });
});
</code></pre>
",https://stackoverflow.com/questions/55514167/error-as-cannot-read-property-subscribe-for-activated-route-in-angular-7-whi,"['angular', 'typescript', 'angular-unit-test', 'angular-activatedroute']",3483,True,0,1
How to mock objects in C# using Visual Studio Unit Testing framework or NUnit framework?,"<p>I have moved to developing applications in C# from Java. I came across the Visual Studio unit testing framework provided by Visual Studio, and another framework called NUnit. </p>

<ol>
<li>Which of these frameworks support mocking objects, or something similar to returning specific response to a method in another project whose source code is not available?</li>
</ol>

<p>I'm using Visual Studio Pro, so Microsoft Fakes is not applicable to me. Also, I came across moq, and rhinomocks but I'm not sure about these. </p>

<ol start=""2"">
<li>I was wondering if I can use a unit testing framework like the one provided by Visual Studio or NUnit without having to add additional dependency.</li>
</ol>
",https://stackoverflow.com/questions/59014713/how-to-mock-objects-in-c-using-visual-studio-unit-testing-framework-or-nunit-fr,"['c#', 'visual-studio', 'unit-testing', 'mocking', 'nunit']",3447,True,-1,1
Angular Unit testing on a component using Material Dialog for alerts is not getting initialized,"<p>After going through many topics in StackOverflow and other forums, i am giving up to try and willing to post my issue as a question.</p>

<p>I have a component that uses Material Dialog to show alerts like Confirmation popups or Information popups for my app. I created a component called AlertsComponent and using that in my parent components wherever i want to show the alerts. I have my own model to handle the information. All of it is working fine but the spec.ts (test case) is failing even on the create/initialize event. </p>

<p>My AlertsComponent.ts:</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import { Component, OnInit, Optional, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { AlertInfo } from 'src/Model/common/alert-info.model';

@Component({
  selector: 'app-alerts',
  templateUrl: './alerts.component.html',
  styleUrls: ['./alerts.component.css']
})
export class AlertsComponent implements OnInit {

  constructor(
    private dialogRef: MatDialogRef&lt;AlertsComponent&gt;,
    @Optional() @Inject(MAT_DIALOG_DATA) public alertInfo?: AlertInfo
  ) {
    console.log('Alert Data: ' + JSON.stringify(alertInfo));
    if (alertInfo.ConfirmPopup) {
      alertInfo.Header = 'Confirm ?';
    } else { alertInfo.Header = 'Alert'; }
    this.dialogRef.disableClose = true;
  }

  ngOnInit() {
  }

  ConfirmResponse(response: boolean): void {
    this.dialogRef.close(response);
  }

  CloseAlert() {
    this.dialogRef.close();
  }

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

<p>My HTML looks like:</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;div&gt;
  &lt;h2 mat-dialog-title&gt;{{alertInfo.Header}}&lt;/h2&gt;
  &lt;hr/&gt;
  &lt;mat-dialog-content&gt;
      &lt;strong&gt;{{alertInfo.Body}}&lt;/strong&gt;
      &lt;br&gt;
      &lt;br&gt;
      &lt;!-- &lt;strong&gt;{{data}}&lt;/strong&gt; --&gt;
    &lt;/mat-dialog-content&gt;
    &lt;hr&gt;
    &lt;mat-dialog-actions&gt;
      &lt;div&gt;
        &lt;ng-container *ngIf=""alertInfo.ConfirmPopup; else alertOnly""&gt;
            &lt;button mat-button class=""align-self-center"" color=""primary"" class=""button-space"" (click)=""ConfirmResponse(true);""&gt;YES&lt;/button&gt;
            &lt;button mat-button class=""align-self-center"" color=""primary"" class=""button-space"" (click)=""ConfirmResponse(false);""&gt;NO&lt;/button&gt;
        &lt;/ng-container&gt;
        &lt;ng-template #alertOnly&gt;
            &lt;button mat-button color=""primary"" class=""button-space"" (click)=""CloseAlert();""&gt;OK&lt;/button&gt;
        &lt;/ng-template&gt;
      &lt;/div&gt;
    &lt;/mat-dialog-actions&gt;
&lt;/div&gt;</code></pre>
</div>
</div>
</p>

<p>And my spec.ts is:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { AlertsComponent } from './alerts.component';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogModule } from '@angular/material';
import { AlertInfo } from 'src/Model/common/alert-info.model';
import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing';

describe('AlertsComponent', () =&gt; {
  let component: AlertsComponent;
  let fixture: ComponentFixture&lt;AlertsComponent&gt;;
  let mockDialogRef: MatDialogRef&lt;AlertsComponent&gt;;
  let mockAlertInfoObj: AlertInfo;
  // const MY_MAT_MOCK_TOKEN = new InjectionToken&lt;AlertInfo&gt;('Mock Injection Token', {
  //   providedIn: 'root',
  //   factory: () =&gt; new AlertInfo()
  // });

  @Component({
    selector: 'app-alerts',
    template: '&lt;div&gt;&lt;mat-dialog-content&gt;&lt;/mat-dialog-content&gt;&lt;/div&gt;'
  })

  class MockAlertsComponent { }

  mockDialogRef = TestBed.get(MatDialogRef);
  mockAlertInfoObj = new AlertInfo();
  mockAlertInfoObj.ConfirmPopup = false;
  mockAlertInfoObj.Body = 'test alert';

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ AlertsComponent, MockAlertsComponent ],
      imports: [MatDialogModule],
      providers: [
        {provide: MatDialogRef, useValue: mockDialogRef},
        {provide: MAT_DIALOG_DATA, useValue: mockAlertInfoObj},
      ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    })
    .compileComponents();
  }));

  TestBed.overrideModule(BrowserDynamicTestingModule, {
    set: {
      entryComponents: [AlertsComponent]
    }
  })

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>When i run ""ng test"", this component test case fails with error saying:</p>

<pre><code>AlertsComponent encountered a declaration exception
Error: Cannot call Promise.then from within a sync test.
Error: Cannot call Promise.then from within a sync test.
    at SyncTestZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.SyncTestZoneSpec.onScheduleTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:366:1)
    at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:404:1)
    at Zone../node_modules/zone.js/dist/zone.js.Zone.scheduleTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:238:1)
    at Zone../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:258:1)
    at scheduleResolveOrReject (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:879:1)
    at ZoneAwarePromise.then (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:1012:1)
    at ApplicationInitStatus.push../node_modules/@angular/core/fesm5/core.js.ApplicationInitStatus.runInitializers (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/core.js:15618:1)
    at TestBedViewEngine.push../node_modules/@angular/core/fesm5/testing.js.TestBedViewEngine._initIfNeeded (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/testing.js:1702:59)
    at TestBedViewEngine.push../node_modules/@angular/core/fesm5/testing.js.TestBedViewEngine.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/testing.js:1766:1)
    at Function.push../node_modules/@angular/core/fesm5/testing.js.TestBedViewEngine.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm5/testing.js:1551:1)
</code></pre>

<p>I dont know or could figure out, where i am doing something wrong, or where? Can someone please help me?</p>
",https://stackoverflow.com/questions/55083747/angular-unit-testing-on-a-component-using-material-dialog-for-alerts-is-not-gett,"['angular', 'jasmine', 'angular-material']",3316,True,0,2
How to do angular unit testing for a customize component (implement ControlValueAccessor and inherited parent form control),"<p>I created a customized searchable dropdown. For this angular component, it implemented ControlValueAccessor and also got NG_VALUE_ACCESSOR, ControlContainer provider. Hence, this component could be part of parent form.</p>

<p>For testing, I already mocked the provider for ControlContainer. I had also searched how to mock NG_VALUE_ACCESSOR online, but not finding anything could work.</p>

<p><code>searchable-dropdown.component.ts</code>:</p>

<pre class=""lang-js prettyprint-override""><code>import {
  Component,
  OnInit,
  ViewChild,
  HostListener,
  ElementRef,
  Input,
  forwardRef,
  SkipSelf,
  OnChanges,
  SimpleChanges
} from '@angular/core';
import { ControlContainer, ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

import { controlContainerFactory } from './helper';

@Component({
  selector: 'app-searchable-dropdown',
  templateUrl: './searchable-dropdown.component.html',
  styleUrls: ['./searchable-dropdown.component.css'],
  providers: [{ provide: NG_VALUE_ACCESSOR, multi: true, useExisting: forwardRef(() =&gt; SearchableDropdownComponent) }],
  viewProviders: [
    { provide: ControlContainer, useFactory: controlContainerFactory, deps: [[new SkipSelf(), ControlContainer]] }
  ]
})
export class SearchableDropdownComponent implements OnInit, ControlValueAccessor, OnChanges {
  @Input() formControlName: string;
  @Input() label: string;
  @Input() placeholder: string;
  @Input() options: string[];

  SearchText = '';
  filterOptions: string[];
  propagateChange: any;
  propagateTouch: any;

  dropDownDirection = 'down';
  preventDropdown = false;
  canShowDropdown = false;
  @ViewChild('container') container: ElementRef;
  @ViewChild('input') input: ElementRef;

  constructor() {}

  get searchText(): string {
    return this.SearchText;
  }

  set searchText(value: string) {
    this.SearchText = value;
    this.propagateChange(value);
  }

  ngOnInit() {
    this.filterOptions = this.options;
  }

  ngOnChanges(changes: SimpleChanges): void {
    const { options } = changes;
    if (options) {
      this.options = options.currentValue;
      this.filterOptions = this.options;
    }
  }

  writeValue(obj: any): void {
    if (obj) {
      this.searchText = obj;
      this.filterOptions = this.options;
      this.preventDropdown = true;
      setTimeout(() =&gt; {
        this.preventDropdown = false;
      }, 0);
    }
  }

  registerOnChange(fn: any): void {
    this.propagateChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.propagateTouch = fn;
  }

  @HostListener('document:keydown.escape', ['$event']) hideDropdown(): void {
    this.canShowDropdown = false;
  }

  @HostListener('document:click', ['$event.target']) onClick(targetElement: HTMLElement): void {
    if (this.input.nativeElement.contains(targetElement)) {
      this.showDropdown();
    } else {
      this.hideDropdown();
    }
  }

  @HostListener('window:scroll', []) onScroll(): void {
    if (window.innerHeight &lt; this.container.nativeElement.getBoundingClientRect().top + 280) {
      this.dropDownDirection = 'up';
    } else {
      this.dropDownDirection = 'down';
    }
  }

  showDropdown() {
    this.canShowDropdown = !this.preventDropdown;
  }

  onKeyDown(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      const result = this.filter(this.options, this.searchText);
      this.searchText = result.length ? result[0] : '';
      this.filterOptions = this.options;
      this.canShowDropdown = false;
    }
  }

  onSearch(value: string): void {
    this.searchText = value;
    this.filterOptions = this.filter(this.options, value);
  }

  filter = (array: string[], text: string) =&gt; {
    return array.filter(option =&gt;
      option.match(
        new RegExp(
          `.*${text
            .replace(/[\W\s]/gi, '')
            .split('')
            .join('.*')}.*`,
          'i'
        )
      )
    );
  }

  pickOption(option: string) {
    this.searchText = option;
    this.filterOptions = this.options;
    setTimeout(() =&gt; {
      this.hideDropdown();
    }, 0);
  }
}
</code></pre>

<p><code>searchable-dropdown.component.html</code>:</p>

<pre class=""lang-html prettyprint-override""><code>&lt;div class=""search""&gt;
  &lt;label&gt;
    {{ label }}:
    &lt;div #container&gt;
      &lt;div class=""input""&gt;
        &lt;input
          #input
          type=""text""
          [placeholder]=""placeholder""
          [value]=""searchText""
          [formControlName]=""formControlName""
          (focus)=""showDropdown()""
          (keydown)=""onKeyDown($event)""
          (ngModelChange)=""onSearch($event)""
        /&gt;
        &lt;i
          class=""anticon""
          [ngClass]=""canShowDropdown ? 'anticon-up' : 'anticon-down'""
          (click)=""canShowDropdown = !canShowDropdown""
        &gt;&lt;/i&gt;
      &lt;/div&gt;
      &lt;ul *ngIf=""canShowDropdown"" [ngClass]=""dropDownDirection""&gt;
        &lt;li *ngFor=""let option of filterOptions"" (click)=""pickOption(option)""&gt;
          {{ option }}
        &lt;/li&gt;
      &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/label&gt;
&lt;/div&gt;
</code></pre>

<p><code>searchable-dropdown.component.spec.ts</code></p>

<pre class=""lang-js prettyprint-override""><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA, forwardRef } from '@angular/core';
import {
  FormsModule,
  ReactiveFormsModule,
  ControlContainer,
  FormGroupDirective,
  FormGroup,
  FormControl,
  NG_VALUE_ACCESSOR
} from '@angular/forms';
// import { By } from '@angular/platform-browser';

import { SearchableDropdownComponent } from './searchable-dropdown.component';

fdescribe('SearchableDropdownComponent', () =&gt; {
  let component: SearchableDropdownComponent;
  let fixture: ComponentFixture&lt;SearchableDropdownComponent&gt;;
  let element: HTMLElement;

  const formGroup = new FormGroup({ test: new FormControl('') });
  const formGroupDirective = new FormGroupDirective([], []);
  formGroupDirective.form = formGroup;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [FormsModule, ReactiveFormsModule],
      declarations: [SearchableDropdownComponent],
      providers: [
        {
          provide: ControlContainer,
          useValue: formGroupDirective
        }
        // ,
        // { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: forwardRef(() =&gt; SearchableDropdownComponent) }
      ],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(SearchableDropdownComponent);
    component = fixture.componentInstance;
    component.formControlName = 'test';
    fixture.detectChanges();

    element = fixture.debugElement.nativeElement;
  });

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

  it('label innerText should match', () =&gt; {
    component.label = 'test label name';
    fixture.detectChanges();
    let label = element.querySelector('label');
    expect(label.innerText).toContain('test label name');

    component.label = 'new test label name';
    fixture.detectChanges();
    label = element.querySelector('label');
    expect(label.innerText).toContain('new test label name');
  });

  it('input placeholder should match', () =&gt; {
    component.placeholder = 'test placeholder';
    fixture.detectChanges();
    let input = element.querySelector('input');
    expect(input.getAttribute('placeholder')).toBe('test placeholder');

    component.placeholder = 'new test placeholder';
    fixture.detectChanges();
    input = element.querySelector('input');
    expect(input.getAttribute('placeholder')).toBe('new test placeholder');
  });

  it('dropdown should match with options', () =&gt; {
    component.options = ['1', '2', '3'];
    component.canShowDropdown = true;
    component.ngOnInit();
    fixture.detectChanges();
    let ul = element.querySelector('ul');
    expect(ul.children.length).toBe(3);

    component.options = ['1', '2'];
    // component.onSearch('');
    fixture.detectChanges();
    ul = element.querySelector('ul');
    console.log(ul.children);
  });

  it('input change should trigger back to form control', () =&gt; {
    // component.searchText = 'new search';
    console.log(formGroup.value);
  });
});
</code></pre>

<p>What is the right way to test for component provided with <code>NG_VALUE_ACCESSOR</code>? </p>

<p>How should I mock the provider for <code>NG_VALUE_ACCESSOR</code>? In this way, when component's <code>searchText</code> changed, it will trigger change on provided mocked ControlContainer?</p>
",https://stackoverflow.com/questions/57732352/how-to-do-angular-unit-testing-for-a-customize-component-implement-controlvalue,"['angular', 'unit-testing', 'karma-jasmine', 'form-control']",7351,True,7,1
"Unit testing Paging jetpack library used with PagedList.BoundaryCallback&lt;T&gt;() with PagedList&lt;T&gt; and DataSource.Factory&lt;Int, T&gt;","<p><strong>Issue:</strong> </p>

<p>I am working with <a href=""https://developer.android.com/topic/libraries/architecture/paging"" rel=""nofollow noreferrer""><code>Paging</code></a> library provided by <a href=""https://developer.android.com/jetpack"" rel=""nofollow noreferrer"">Android Jetpack</a> and I am not able to test the <code>PagedList&lt;T&gt;</code> and <code>DataSource.Factory&lt;Int, T&gt;</code> data used with <code>PagedList.BoundaryCallback&lt;T&gt;()</code> in my <code>ViewModel</code> 
<Br><Br>
My code for receiving <code>PagedList</code> data using <code>PagedList.BoundaryCallback&lt;T&gt;()</code> and <code>PagedList.Config.Builder()</code> ::</p>

<pre><code>final var boundaryCallback = MyBoundaryCallback(
        webServiceApi, mainRepository, PAGE_SIZE, appExecutors)

private final val pagedListConfig = PagedList.Config.Builder()
        .setEnablePlaceholders(false)
        .setPrefetchDistance(PREFETCH_DISTANCE)
        .setPageSize(PAGE_SIZE)
        .build()

var pagedListData: LiveData&lt;PagedList&lt;MyData&gt;&gt; =
        LivePagedListBuilder(dbDAO.loadAllPagedData(), pagedListConfig)
                .setBoundaryCallback(boundaryCallback)
                .build()
</code></pre>

<p><Br><Br>
And my class MyBoundaryCallback :</p>

<pre><code>class MyBoundaryCallback (private val webServiceApi: ApiService,
                               private val mainRepository: MainRepository,
                               private val networkPageLimit: Int,
                               private val appExecutors: AppExecutors) : PagedList.BoundaryCallback&lt;MyData&gt;() {

override fun onZeroItemsLoaded() {
    webServiceApi.getData(0, networkPageLimit).enqueue(WebserviceCallback())
}

override fun onItemAtEndLoaded(itemAtEnd: MyData) {
    webServiceApi.getData((itemAtEnd.id!! + 1), networkPageLimit).enqueue(WebserviceCallback())
}

private fun handleResponse(response: Response&lt;List&lt;MyData&gt;&gt;) {
    appExecutors.diskIO().execute {
        mainRepository.insertResultIntoDb(response.body())
    }
}

inner class WebserviceCallback : Callback&lt;List&lt;MyData&gt;&gt; {
    override fun onFailure(call: Call&lt;List&lt;MyData&gt;&gt;, t: Throwable) {

    }

    override fun onResponse(call: Call&lt;List&lt;MyData&gt;&gt;, response: Response&lt;List&lt;MyData&gt;&gt;) {
        handleResponse(response)
    }
}
}
</code></pre>

<p><Br><Br>
Since the class <code>MyBoundaryCallback</code> is pushing the data as you can see the code in my <code>ViewModel</code> above, the <code>LiveData</code> object is fetching the data from my room Db since it gives out <code>DataSource.Factory&lt;Int, T&gt;</code>, find the code below :</p>

<pre><code>@Query(""SELECT * FROM mydata"")
fun loadAllPagedData(): DataSource.Factory&lt;Int, MyData&gt;
</code></pre>

<p>I am not sure how to mock the <code>PagedData</code> so if anyone has any idea how to approach this please share </p>

<p>For Simple List of data I am able to test it with something like the code below :</p>

<pre><code>@Test
fun testBasicData() {
    val dbMyData = MutableLiveData&lt;List&lt;MyData&gt;&gt;()
    val observer = mock&lt;Observer&lt;List&lt;MyData&gt;&gt;&gt;()
    Mockito.`when`(deliveriesDAO.loadAllData()).thenReturn(dbDeliveriesData)
    val list = MyMockDataGenerator.createList(4)
    dbDeliveriesData.observeForever(observer)
    dbDeliveriesData.value = list
    Mockito.verify(observer).onChanged(list)
}
</code></pre>
",https://stackoverflow.com/questions/57685405/unit-testing-paging-jetpack-library-used-with-pagedlist-boundarycallbackt-wi,"['android', 'unit-testing', 'android-jetpack', 'android-paging']",3070,False,2,0
Unit testing: How do I mock the innerWidth property on the window object with Angular + Jasmine?,"<p>I want to write a unit test which expects a variable to contain a specific value depending on the <code>innerWidth</code> of the window.</p>

<p>In my unit test, I use <code>window.innerWidth = 1000;</code>. However, I receive an error which says <code>Cannot assign to 'innerWidth' because it is a read-only property.</code>.</p>

<p>Code (home.component.spec.ts):</p>

<pre><code>  xit('should order the cards in the appropriate order on desktop', () =&gt; {
    spyOn(component, 'reOrderCards');
    window.innerWidth = 1000;
  })
</code></pre>

<p>Is there any way to mock the <code>innerWidth</code> property?</p>
",https://stackoverflow.com/questions/56596372/unit-testing-how-do-i-mock-the-innerwidth-property-on-the-window-object-with-an,"['angular', 'unit-testing', 'testing', 'jasmine', 'angular8']",1463,False,2,3
Is it possible to host a windows console in a headless unit testing runner like resharper?,"<p>I have a software library which targets console applications. I would like to run a slim set of integration tests that use the windows Console in a headless runner that would ideally be run on our build server and in the resharper test runner. </p>

<p>To make this work, I need the actual <code>System.Console</code> calls to be executed in the test (so they can't be conditionally commented out.)</p>

<p>When the tests call something that the requires the stdout handle, e.g. <code>Console.SetCursorPosition</code>, an exception is generated: <code>System.IO.IOException: 'The handle is invalid'</code></p>

<p>I assumed I could just do a pinvoke and call <code>FreeConsole</code> and <code>AllocConsole</code> and this would allow me to call the relevant methods. Unfortunately this doesn't appear to be the case. </p>

<p>At the moment I can successfully Free, Alloc, and redirect console output back to STDOUT but this doesn't change the exception behaviour. Any ideas?</p>

<p>I'm redirecting STDOUT back to CONOUT using the following:-</p>

<pre><code>var stdoutFile = ExternalMethods.CreateFile(""CONOUT$"", FileAccess.Read, FileShare.Read, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero);
var handle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdoutFile, true);
if (handle.IsInvalid)
{
    throw new Win32Exception(Marshal.GetLastWin32Error());
}

if (!ExternalMethods.SetStdHandle(-11, handle))
{
    throw new Win32Exception(Marshal.GetLastWin32Error());
}
</code></pre>
",https://stackoverflow.com/questions/58087131/is-it-possible-to-host-a-windows-console-in-a-headless-unit-testing-runner-like,"['c#', '.net-core', 'console-application', 'integration-testing', 'pinvoke']",271,True,2,1
"In unit testing, how to compare two objects without using operator== which may miss new members?","<p>In unit testing code, which is the best way to test the <code>operator==</code> comparison operator in the hypothesis that new members may have been added to the class? </p>

<p>E.g.:</p>

<pre><code>struct A {
   int a, b;
   bool operator==( const A&amp; other ) const { return( a == other.a &amp;&amp; b == other.b ); }
};

int Test() {
   A a1, a2;
   EXPECT_TRUE( a1 == a2 );
}
</code></pre>

<p>then we change A, adding a new member variable <code>c</code>.
With the current test/comparison operator, we will get false negatives when <code>c</code> differs.</p>

<p>Is there an alternative/low level way to compare two objects?</p>
",https://stackoverflow.com/questions/59093114/in-unit-testing-how-to-compare-two-objects-without-using-operator-which-may-m,"['c++', 'unit-testing', 'comparison-operators']",775,True,1,1
How to call custom methods of React component while doing unit testing. I am using typescript,"<p>I am using react with typescript. Can anyone tell me how to call the custom methods which is written in component inside unit testing.</p>

<p>I tried <code>shallow</code> and <code>mount</code> but I am not able to call custom methods.</p>

<pre><code>import React  from 'react';
import {
  Theme,
  withStyles,
  createStyles,
} from '@material-ui/core';

export interface IFileUploadProps{}
export interface IFileUploadState {}

const styles = (theme: Theme) =&gt; {
  return createStyles({
    root: {
      paddingTop: theme.spacing(2),
      paddingBottom: theme.spacing(2),
      width: '100%',
      backgroundColor: 'inherit',
    },
    input: {
      display: 'none',
    },
    padding24: {
      paddingLeft: theme.spacing(3),
      paddingRight: theme.spacing(3),
    },
  });
};

class FileUpload extends React.Component&lt;IFileUploadProps, IFileUploadState&gt; {

    validateImage = () =&gt; {
      console.log('validate image');
    }

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

export default withStyles(styles)(FileUpload);
</code></pre>

<p>I need to do something like this.</p>

<pre><code>import React from 'react';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16'
import FileUpload from './FileUpload';

configure({ adapter: new Adapter() });   
describe('FileUpload', () =&gt; {
  test('should call validateImage method correctly', () =&gt; {
    const wrapper = shallow(&lt;FileUpload &gt;&lt;/FileUpload&gt;);
    wrapper.instance()['validateImage']();
  });
});
</code></pre>

<p>Here I am getting error. </p>

<blockquote>
  <p>TypeError: Cannot read property 'validateImage' of null</p>
</blockquote>

<p><strong>This error occurs when i export file using ""export default withStyles(styles)(FileUpload);"" 
When i use export default FileUpload it is working fine.</strong></p>
",https://stackoverflow.com/questions/58642342/how-to-call-custom-methods-of-react-component-while-doing-unit-testing-i-am-usi,"['reactjs', 'typescript', 'unit-testing', 'jestjs', 'enzyme']",933,True,1,1
Unit Testing - Controller not picking up value from mocked IConfiguration in ASP.NET Core Web API Project,"<p>I am trying to Unit Test my Login Action in ASP.NET Core Web API with mock services, all the mocking works fine but when I try to Mock my <code>IConfiguration</code> file the controller does not pick up the value from it.</p>

<p>Here's my Unit testing code that calls my controller action:</p>

<pre><code>[Fact]
public async Task SignInTest()
{
    // Arrange
    var requestVM = new CustomerSignInRequestVM
    {
        EmailPhone = ""03026993900"",
        RegNum = ""Abc123""
    };

    var config = new Mock&lt;IConfiguration&gt;();
    //HERE I AM SETTING ALL MY CONFIGURATION VALUES TO RETURN SOME FAKE VALUES

    //config.Setup(cf =&gt; cf.GetSection(""Jwt:Encryptionkey"").Value).Returns(""01 02 03"");    
    config.Setup(x =&gt; x.GetSection(""Jwt:Encryptionkey"").Value).Returns(""abc"");
    config.Setup(x =&gt; x.GetSection(""Jwt:Issuer"").Value).Returns(""test.com"");
    config.Setup(x =&gt; x.GetSection(""Jwt:ExpiryTimeInMinutes"").Value).Returns(""Jwt:ExpiryTimeInMinutes"");   

    //THIS MOCKING WORK FINE IN CONTROLLER ACTION
    var customerApplication = new Mock&lt;ICustomerApplication&gt;();
    customerApplication.Setup(app =&gt; app.GetCustomer(It.IsAny&lt;SignIn&gt;())).ReturnsAsync(GetCustomerMockData);

    var claimApplication = new Mock&lt;IClaimApplication&gt;();
    claimApplication.Setup(app =&gt; app.GetListByRole(It.IsAny&lt;ApplicationRole&gt;())).ReturnsAsync(new List&lt;ApplicationClaim&gt; { new ApplicationClaim { Active = true, ClaimCode = ""AUC_GA"", ClaimLabel = ""Auction.GetAll"" } });

    //I'm also injecting my IConfiguration object here in my controller setup

    var controller = new CustomerController(customerApplication.Object, null, claimApplication.Object, null, null, config.Object, null);

    // Act
    var response = await controller.SignIn(requestVM, new CancellationToken());
    var okObjectResult = response as OkObjectResult;

    // Assert
    Assert.Equal(200, okObjectResult.StatusCode);
}
</code></pre>

<p>but when I try to retrieve values from <strong>injected</strong> <code>IConfiguration</code> service inside my controller action like this:</p>

<p><code>var Issuer = Configuration[""Jwt:Issuer""],</code></p>

<p>this returns <code>null</code> to me, I am not sure what I am doing wrong here.</p>
",https://stackoverflow.com/questions/55418563/unit-testing-controller-not-picking-up-value-from-mocked-iconfiguration-in-asp,"['c#', 'unit-testing', 'asp.net-core', 'asp.net-core-webapi']",390,True,1,1
Angular Unit Testing - How to fix &#39;Cannot read property &quot;middle_name&quot; of undefined&#39; when initializing a component,"<p>I am trying to create a simple 'it should create' unit test for one of my Angular components (the test generated by Angular CLI when generating the component). However, when running the test, I receive a <code>TypeError: Cannot read property 'middle_name' of undefined</code>. I didn't expect this error because the HTML is surrounded in an *ngIf.</p>

<p>I tried to follow this question on stackoverflow: <a href=""https://stackoverflow.com/questions/53086352/angular-testing-cannot-read-property-name-of-undefined"">Angular testing Cannot read property &#39;name&#39; of undefined</a></p>

<p>However the OP resolved the problem by surrounding his HTML in an *ngIf, which is what my code currently does. I suspect the problem is occurring because this is a child component and is conditionally rendered.</p>

<p>form-submit-individual-success-component.ts:</p>

<pre><code>it('should create', () =&gt; {
    expect(component).toBeTruthy();
});
</code></pre>

<p>add-entity.ts:</p>

<pre><code>onIndividualSubmit(clonedIndividualValues: Individual): void {
  this.entityService.addIndividual(clonedIndividualValues)
.subscribe(individual =&gt; {
      this.formIsSubmitted = true;
      this.individualFormIsSubmitted = true;
      this.individualId = individual.id;
      this.individualFormData = individual;
    })
}
</code></pre>

<p>add-entity.html:</p>

<pre><code>&lt;app-add-individual-form *ngIf=""selectedOption == 'Individual' &amp;&amp; !individualFormIsSubmitted"" (individualServiceEmitter)=""onIndividualSubmit($event)"" [individualId]=""individualId""&gt;&lt;/app-add-individual-form&gt;
</code></pre>

<p>add-individual-form.ts:</p>

<pre><code>@Output() individualServiceEmitter = new EventEmitter();
onIndividualSubmit(value: any): void {

  value.eod_screening === 'Yes' ? value.eod_screnning = 1 : value.eod_screening = 0;

  const clonedIndividualValues = Object.assign({ type: 'Individual', screening_status: 'Awaiting Submission' }, value)

  this.individualServiceEmitter.emit(clonedIndividualValues);
}
</code></pre>

<p>add-individual-form.html:</p>

<p></p>

<pre><code>&lt;div class=""form-group""&gt;
  &lt;label for=""middle_name""&gt;Middle Name(s)&lt;/label&gt;
  &lt;input type=""text"" class=""form-control"" id=""middle_name"" name=""middle_name"" formControlName=""middle_name""
  #middle_name&gt;
  &lt;div *ngFor=""let validation of validation_messages.middle_name""&gt;
    &lt;div *ngIf=""individualForm.middle_name.hasError(validation.type) &amp;&amp; (individualForm.middle_name.dirty || individualForm.middle_name.touched)""
    class=""alert alert-danger""&gt;
    {{validation.message}}
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;div class=""form-group""&gt;
  &lt;label for=""last_name""&gt;Last Name&lt;/label&gt;
  &lt;input type=""text"" class=""form-control"" id=""last_name"" name=""last_name"" formControlName=""last_name"" #last_name
  required&gt;
  &lt;div *ngFor=""let validation of validation_messages.last_name""&gt;
    &lt;div *ngIf=""individualForm.last_name.hasError(validation.type) &amp;&amp; (individualForm.last_name.dirty || individualForm.last_name.touched)""
    class=""alert alert-danger""&gt;
    {{validation.message}}
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;button type=""submit"" class=""btn btn-success"" [disabled]=""!addIndividualForm.valid""&gt;Submit&lt;/button&gt;
</code></pre>

<p></p>

<p>form-submit-individual-success.ts:</p>

<pre><code>@Input() formData: Individual;
public individualFormData: Individual;
@Input() id: number;
public individualId: number;
public editIndividualBase = ""/entity/edit"";

constructor() { }

ngOnInit() {
  this.individualFormData = this.formData;
}
</code></pre>

<p>form-submit-individual-success.html:</p>

<pre><code> &lt;p&gt;First name: &lt;span&gt;{{individualFormData.first_name}}&lt;/span&gt;&lt;/p&gt;
 &lt;p *ngIf=""individualFormData.middle_name""&gt;Middle name(s): &lt;span&gt;{{individualFormData.middle_name}}&lt;/span&gt;&lt;/p&gt;
 &lt;p&gt;Last name: &lt;span&gt;{{individualFormData.last_name}}&lt;/span&gt;&lt;/p&gt;
</code></pre>

<p>As described in the problem summary, I expect the <code>component</code> toBeTruthy (i.e. create successfully).</p>
",https://stackoverflow.com/questions/54253898/angular-unit-testing-how-to-fix-cannot-read-property-middle-name-of-undefin,"['javascript', 'angular', 'unit-testing', 'testing', 'jasmine']",2622,False,1,0
How to check whether for assistance of element based on element name in angular unit testing?,"<p>I have a side navbar as follows,</p>

<pre><code>      &lt;kendo-sidenav *ngFor=""let nav of navOptions"" [title]=""nav.title""&gt;
      &lt;kendo-sidenav&gt;
</code></pre>

<p>My ts,</p>

<pre><code>       ""navOptions"" = [{'title':'profile'},{'title':'friends'}];
</code></pre>

<p>My spec,</p>

<pre><code>     it('should render title in a h1 tag', async(() =&gt; {
        const fixture = TestBed.createComponent(AppComponent);
        fixture.detectChanges();
        const compiled = fixture.debugElement.nativeElement;
       expect(compiled.querySelector('kendo-sidenav')).toBeTruthy()
      }));
</code></pre>

<p>But here I want to check 2 conditions,</p>

<p>1) Check side navbar is displayed if navOptions is not empty</p>

<p>2_ Check side navbar is not displayed if navOptions is empty.</p>

<p>I am new to unit testing,can anyone please suggest me help.Thanks.</p>
",https://stackoverflow.com/questions/57583290/how-to-check-whether-for-assistance-of-element-based-on-element-name-in-angular,"['javascript', 'angular', 'typescript', 'jasmine', 'angular-unit-test']",20,False,1,0
unit testing a MixIn class which is accessing another class method in one of its methods,"<p>I have two Mixin classes. One of the methods in a Mixin class is calling a method from another class. Everything works fine when I create a subclass by inheriting from these two Mixins. </p>

<pre><code>class FirstMixin(object):
    def method(self):
         some logic here  
         self.method_of_sub_class()

class SecondMixin(object):
    def method_of_sub_class()
        pass

class BaseClass(SecondMixin, FirstMixin):
    pass
</code></pre>

<p>When I write unit test cases for FirstMixin class, its getting failed because of the <code>method_of_sub_class</code> call. How can I write unit test cases for the first MixIn class which is calling a method from another class?</p>
",https://stackoverflow.com/questions/54726709/unit-testing-a-mixin-class-which-is-accessing-another-class-method-in-one-of-its,"['python', 'design-patterns']",748,True,1,1
"How to make a set up for unit testing with the bot framework (Echobot, using ITurnContext)","<p>I'm trying to make unit tests for an Echobot (just to understand how it works so I can use it for my actual bot), but there is one problem I'm unable to fix. The problem that I'm facing is that I'm using ITurnContext and every example I've come across is using DialogContext (with IWaitable to send the message).<br/>
ITurnContext is only readable so I can't set anything into it, unless I do it in the SetUp class which isn't that pretty - but it worked so I continued just to see what would happen and I got an error:<br/></p>

<pre><code>Message: Moq.MockException : 
Expected invocation on the mock at least once, but was never performed: c =&gt; c.PostAsync(Mock&lt;Microsoft.Bot.Builder.ITurnContext:00000001&gt;.Object, ""You sent 'test'"")
No setups configured.
No invocations performed.
</code></pre>

<p>To begin I used this guide to start: <a href=""https://medium.com/@createdincode/simple-unit-testing-in-microsofts-c-bot-framework-with-nunit-and-moq-345b805ecd1b"" rel=""nofollow noreferrer"">https://medium.com/@createdincode/simple-unit-testing-in-microsofts-c-bot-framework-with-nunit-and-moq-345b805ecd1b</a><br />
After I ran into some problems I tried searching online and came across this thread: <a href=""https://stackoverflow.com/questions/41348791/auto-testing-for-microsoft-bot-framework"">Auto testing for Microsoft Bot Framework</a> => but the links provided in the top answer all give me a 404..<br/>
Same goes for this one <a href=""https://stackoverflow.com/questions/50358031/unit-testing-bot-framework"">Unit Testing Bot Framework</a>, sadly :(<br/></p>

<p>The Test class is currently this:</p>

<pre><code>namespace EchoBot.UnitTest
{
    [TestFixture]
    class EchoTest
    {
        private Mock&lt;IChatHelper&gt; _chat;
        private EchoBotBot _echobot;
        private Mock&lt;ITurnContext&gt; _context;

        [SetUp]
        public void SetUp()
        {
            _chat = new Mock&lt;IChatHelper&gt;();
            _echobot = new EchoBotBot(_chat.Object);

            var activity = new Activity(ActivityTypes.Message);
            activity.Text = ""test"";

            _context = new Mock&lt;ITurnContext&gt;();

            _context.Setup(c =&gt; c.Activity).Returns(activity);
        }

        [Test]
        public async Task echoBackTest()
        {

            await _echobot.OnTurnAsync(_context.Object);

            _chat.Verify(c =&gt; c.PostAsync(_context.Object, ""You sent 'test'""));

        }

    }
}
</code></pre>

<p>And the Helper class is the same as the guide I send, except that I changed DialogContext to ITurnContext.
I don't know how to fix this error and I'm afraid of trapping myself inside a Moq hole (if you get what I mean).</p>

<p>I hope I described everything good enough and that somebody can help me! Thanks in advance (:</p>

<p><strong>EDIT: the code of the EchoBot</strong> </p>

<pre><code>public class EchoBotBot : IBot
    {
        private readonly EchoBotAccessors _accessors;
        private readonly ILogger _logger;

        private IChatHelper _chat;

        public EchoBotBot(IChatHelper chat)
        {
            _chat = chat;
        }

        public EchoBotBot(ConversationState conversationState)
        {
            if (conversationState == null)
            {
                throw new System.ArgumentNullException(nameof(conversationState));
            }

        }


        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {

                var responseMessage = $""You sent '{turnContext.Activity.Text}'\n"";
                await turnContext.SendActivityAsync(responseMessage);
            }
            else
            {
                await turnContext.SendActivityAsync($""{turnContext.Activity.Type} event detected"");
            }
        }
    }
</code></pre>
",https://stackoverflow.com/questions/55807092/how-to-make-a-set-up-for-unit-testing-with-the-bot-framework-echobot-using-itu,"['c#', 'unit-testing', 'botframework', 'moq']",1254,True,1,1
Angular Unit Testing: How to check if the spied upon method is getting the correct argument?,"<p>Let's say we have  a method called <code>Method1</code> which accepts and object
 <code>obj={ name: 'jack', phone: '123' }</code></p>

<p>as you can see there are two properties here, name and phone. </p>

<p>Method1 internally calls Method2 with <code>obj.phone</code> as argument. </p>

<p><a href=""https://stackblitz.com/edit/angular-testing-with-jasmine-fkwvmg?file=app/app.component.spec.ts"" rel=""nofollow noreferrer"">FIDDLE</a></p>

<pre><code>export class AppComponent {  
  method1(obj: any) {
    this.method2(obj.phone);
  }
  method2(val) {

  }
}
</code></pre>

<p>I would like to check if method2 was called and also if the correct argument was passed to it. Which in this case will always be phone property of obj. </p>

<p>Is callFake() the solution? How do I do it?</p>

<p><strong>Code that doesn't work:</strong></p>

<pre><code>it('should do something', () =&gt; {
    let obj = { name: 'jack', phone: '123' }
    let passedarg;
    let spy = spyOn(subject, 'method2').and.callFake(function (arg) {
      passedarg = arg;
    });
    expect(obj).toHaveBeenCalledWith(obj.phone);
  });
</code></pre>
",https://stackoverflow.com/questions/56908129/angular-unit-testing-how-to-check-if-the-spied-upon-method-is-getting-the-corre,"['javascript', 'angular', 'typescript', 'jasmine', 'karma-jasmine']",1081,True,0,1
How to do unit testing of function which is depends on another function using karma jasmine,"<p>I want to test getTokenExpirationDate() method which uses other method jwt_decode and it is imported from jwt-decode. How I can do unit testing for this method?. How This jwt_decode method can be mocked.</p>

<pre><code>import { Injectable } from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import * as jwt_decode from 'jwt-decode';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) { }

  canActivate(): boolean {
    const token = localStorage.getItem(('loginToken'));
    if (this.isTokenExpired(token)) {
      localStorage.removeItem('loginToken');
      this.router.navigate(['/login']);
      return false;
    } else {
      return true;
    }
  }

  isTokenExpired(token: string): boolean {
    if (!token) { return true;
    } else {
      const date = this.getTokenExpirationDate(token);
      if (date === undefined) {
        return false;
      } else {
        return !(date.valueOf() &gt; new Date().valueOf());
      }
    }
  }

  getTokenExpirationDate(token: string): Date {
    const decoded = jwt_decode(token);
    if (decoded.exp === undefined) {
      return null;
    } else {
      const date = new Date(0);
      date.setUTCSeconds(decoded.exp);
      return date;
    }
  }

}
</code></pre>
",https://stackoverflow.com/questions/57521773/how-to-do-unit-testing-of-function-which-is-depends-on-another-function-using-ka,"['angular', 'unit-testing', 'karma-jasmine']",699,False,0,1
How do I replace a function by a mock implementation when unit-testing a shared library?,"<p>I am having the opposite problem that <a href=""https://stackoverflow.com/questions/39477163/can-you-compile-a-shared-object-to-prefer-local-symbols-even-if-its-being-loade"">Can you compile a shared object to prefer local symbols even if it&#39;s being loaded by a program compiled with -rdynamic?</a> is solving.</p>

<p>Using the naming from the linked question, I have a dynamic library where <code>baz</code> calls <code>bar</code>, and I have a test binary exercising the library, which substitutes its own fake implementation of <code>bar</code> for test purposes. This works fine on Linux, because <code>-rdynamic</code> is used to link.</p>

<p>The source of the test is <a href=""https://github.com/apache/qpid-dispatch/blob/b172f501028b36d786b4c83bcee1e195cd17fcf2/tests/timer_test.c"" rel=""nofollow noreferrer"">https://github.com/apache/qpid-dispatch/blob/b172f501028b36d786b4c83bcee1e195cd17fcf2/tests/timer_test.c</a>. The functions being mocked are, among others <code>qd_server_timeout</code> and <code>qd_timer_now</code> (that is the inlined one, see comments).</p>

<p>I am at a loss how to achieve the same on macOS. What are the correct linker options there?</p>
",https://stackoverflow.com/questions/56711149/how-do-i-replace-a-function-by-a-mock-implementation-when-unit-testing-a-shared,"['c', 'macos', 'unit-testing', 'mocking', 'dynamic-linking']",310,False,0,1
"Setting up Frontend best practices for icons, webpack configs and unit testing in SAP Spartucus Storefront","<p>Could you please help me with my below questions:
1. How can I include a framework for handling icons (custom icons, icomoons, etc)
2. How can I use the unit testing framework to achieve specific code coverage and How to use protactor e2e testcases?
3. How can I modify the webpack settings (let say I want to divide one more chunk from vendor.js file)</p>
",https://stackoverflow.com/questions/58508792/setting-up-frontend-best-practices-for-icons-webpack-configs-and-unit-testing-i,"['user-interface', 'icons', 'karma-jasmine', 'angular8', 'spartacus-storefront']",92,False,0,1
How can I ensure that a cloned HTML node has a specific property (when Unit Testing)?,"<p>I am creating an HTML clone using </p>

<p><code>var clone = document.getElementById('tempID').cloneNode(true);</code></p>

<p>Then, I want to edit the id, using <code>clone['id'] = newUniqueID;</code> (I'm creating multiple clones, so each one will have its own id)</p>

<p>This works when running the app, but the Unit Tests won't allow it, it is giving this error:</p>

<p><code>Property 'id' does not exist on type 'Node'</code></p>

<p>I tried putting these two lines inside this if statement, to guarantee the element exists, but I'm still getting the same error in the Unit Test:</p>

<pre><code>if(document.getElementById('tempID') !== null){
  var clone = document.getElementById('tempID').cloneNode(true);
  clone['id'] = newUniqueID;
}
</code></pre>

<p>In this scenario, the id is guaranteed to exist when using <code>clone['id']</code>, so why does the Unit Test claim it doesn't exist? What is the workaround for this?</p>

<p>Note: The entire test suite fails to run due to this error, so it isn't a problem with a specific test.</p>
",https://stackoverflow.com/questions/59035922/how-can-i-ensure-that-a-cloned-html-node-has-a-specific-property-when-unit-test,"['html', 'typescript', 'unit-testing', 'clone']",69,True,0,1
Problem unit testing functions that contain file I/O using Visual Studio Native cpp Unite Testing,"<p>I have this piece of code that counts the amount of instances a phrase exists within a text file. When I call this from a main() function, it works as expected. </p>

<p>When I try to write a Unit Test for it, it fails upon opening the file, returning -1 (see code below).</p>

<p>Here is the code for my countInstances function:</p>

<pre><code>int countInstances(string phrase, string filename) {
    ifstream file;
    file.open(filename);
    if (file.is_open) {
        stringstream buffer;
        buffer &lt;&lt; file.rdbuf();
        file.close();
        string contents = buffer.str();

        int fileLength = contents.length();
        int phraseLength = phrase.length();
        int instances = 0;

        // Goes through entire contents
        for(int i = 0; i &lt; fileLength - phraseLength; i++){
            int j;

            // Now checks to see if the phrase is in contents
            for (j = 0; j &lt; phraseLength; j++) {
                if (contents[i + j] != phrase[j])
                    break;
            }

            // Checks to see if the entire phrase existed
            if (j == phraseLength) {
                instances++;
                j = 0;
            }
        }

        return instances;
    }
    else {
        return -1;
    }
}

</code></pre>

<p>My Unit Test looks like:</p>

<pre><code>
namespace Tests
{       
    TEST_CLASS(UnitTests)
    {
    public:
        TEST_METHOD(CountInstances) {
            /*
                countInstances(string, string) :
                countInstances should simply check the amount of times that
                the passed phrase / word appears within the given filename
            */
            int expected = 3;
            int actual = countInstances(""word"", ""../smudger/test.txt"");
            Assert::AreEqual(expected, actual);
        }
        };
}
</code></pre>

<p>For the CountInstance Test I get the following message:</p>

<p>Message: Assert failed. Expected:&lt;3> Actual:&lt;-1></p>

<p>Any ideas on where my issue comes from and how I could go about fixing it?
Thanks.</p>
",https://stackoverflow.com/questions/55638449/problem-unit-testing-functions-that-contain-file-i-o-using-visual-studio-native,"['c++', 'visual-studio', 'unit-testing', 'microsoft-cpp-unit-test']",358,False,0,2
how to run test on img tag while doing unit testing with enzyme on react component,"<p>i am doing unit testing with enzyme, and i am not able to select the image tag into the find()....so i am getting this error
""TypeError: Cannot read property 'have' of undefined</p>

<pre><code>  34 |         //const sb = shallow(&lt;sliderBanner store={store} /&gt;);
  35 |         //expect(Wrapper.find(&lt;img /&gt;)).to.have.property(""img"");
&gt; 36 |         expect(Wrapper.getElement(""img"")).to.have.property(""src"");
     |         ^
  37 |     });
  38 | });""
</code></pre>

<p>i have written this test case....</p>

<pre><code>test(""imgage source is valid"", () =&gt; {
        const Wrapper = shallow(&lt;MainBanner store={store} /&gt;);
        //const sb = shallow(&lt;sliderBanner store={store} /&gt;);
        //expect(Wrapper.find(&lt;img /&gt;)).to.have.property(""img"");
        expect(Wrapper.getElement(""img"")).to.have.property(""src"");
</code></pre>
",https://stackoverflow.com/questions/57003574/how-to-run-test-on-img-tag-while-doing-unit-testing-with-enzyme-on-react-compone,"['reactjs', 'jestjs', 'enzyme']",98,False,0,1
"In React JS, how to do unit testing on a function which is in a container?","<p>I am trying to simulate on click of a button and test what's happening based on that click. I tried mocking function. But didn't work. How do we test the statements inside of a function?</p>

<p>I tried mocking a function to see if it has been called. But i always get mock function not called</p>

<pre><code>updateSelect =(e, model) =&gt; {
    window.alert('test');
    const value = e.type === ""keyup"" ? 
    e.target.parentNode.childNodes[2].innerText : e.target.innerText;
    if(!isEmpty(value)){
      this.setState({text: value});
      this.props.returnedValue({name : model, value});
    }
}

&lt;button className=""test"" onClick={(e)=&gt;this.updateSelect(e, model)}&gt;Click&lt;/button&gt;
</code></pre>

<p>I expect either the function should be called or at least few statements in the function has to be executed</p>
",https://stackoverflow.com/questions/58236123/in-react-js-how-to-do-unit-testing-on-a-function-which-is-in-a-container,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",167,False,0,1
Expected undefined to be defined error in Karma unit testing while testing a function using .toBeTruthy(),"<p>In the below spec file am covering test case for saveAdmin function but am getting below mentioned error</p>

<p><strong>Expected undefined to be defined</strong> error in Karma unit testing while testing a function using .toBeTruthy() i had given the ts file and spec file also mentioned the error from karma. Thanks in advance </p>

<p><strong>Ts file</strong>  </p>

<pre><code>  import {Component, Inject, OnInit} from ""@angular/core"";
    import {MAT_DIALOG_DATA, MatDialogRef} from ""@angular/material"";
    import {DataService} from ""../../../services/data.service"";
    @Component({
      selector: 'admin-dialog',
      templateUrl: './admin-dialog.component.html',
      styleUrls: ['./admin-dialog.component.scss']
    })
    export class AdminDialogComponent implements OnInit {
      public accessHasSelected : any ='';
      public errorObj : any = {};
      public checkBoxSelected : boolean;
      public adminObj: any = {
        active:true,
        firstName:"""",
        lastName:"""",
       // emailId:"""",
        access:[]
      };
      /***
       *
       * @param dialogRef
       * @param data
       * @param fromGroup
       * @param dataService
       */
      constructor(
        public dialogRef: MatDialogRef&lt;AdminDialogComponent&gt;,
        @Inject(MAT_DIALOG_DATA) public data: any,
        private dataService: DataService) {

        if (this.data.isNew){
          this.newAdmin();
        }
        else {
          this.editAdmin(this.data.adminObj);
        }
      }
      /*
      * This method will get called while loading new admin modal.
      * */
      newAdmin() {
        this.dataService.getAllAdminAccess().subscribe(
          response =&gt; {
            this.adminObj.access = response.access;
          },
          error =&gt; { });
      }
      /***
       * This method will get called while loading edit existing admin modal.
       * @param response
       */
      editAdmin(response){
        console.log(response);
        this.dataService.getAdminDetails(response.emailId).subscribe(
          response =&gt; {
            //component related success actions
            this.adminObj = response;
          },
          error =&gt; {});
      }
      /**
       * This method will run will save is clicked.
       * */
      saveAdmin(){
        this.checkBoxSelected = true;
        this.accessHasSelected = this.adminObj.access.filter(t=&gt;{
          if(this.checkBoxSelected){
            if(t.selected){this.checkBoxSelected = false;}
            else if(t.access !== null){
              t.access.filter(x=&gt;{
                if(x.selected) {this.checkBoxSelected = false;}
              })
            }
          }
        });
        if(!this.checkBoxSelected) {
          this.dataService.saveAdmin(this.adminObj, this.data.isNew).subscribe(
            response =&gt; {
              //component related success actions
              this.dialogRef.addPanelClass('close-modal');
              setTimeout(() =&gt; {
                this.dialogRef.close({
                  data: response
                });
              }, 500);
            },
            error =&gt; {
              this.errorObj = {};
              //component related error actions
              for (var v in error.error.errors) {
                this.errorObj[error.error.errors[v].field] = error.error.errors[v].messageId;
              }
            });
        }else{
            this.errorObj.access = ""requiredAccessError"";
          }
      }
      /**
       *
       */
      ngOnInit() {}
      onModalCancel(): void {
        this.dialogRef.addPanelClass('close-modal');
        setTimeout(()=&gt;{
          this.dialogRef.close();
        },500);
      }
    }
</code></pre>

<p><strong>Spec file:</strong></p>

<pre><code>import { AdminDialogComponent } from ""./admin-dialog.component"";
import { TestBed, ComponentFixture,async,inject  } from '@angular/core/testing';
import { FormsModule } from ""@angular/forms"";
import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing';
import {TranslateModule,TranslateService} from ""@ngx-translate/core"";
import {Inject, NO_ERRORS_SCHEMA} from ""@angular/core"";
import {MAT_DIALOG_DATA, MatDialog, MatDialogModule, MatDialogRef} from '@angular/material/dialog';
import { OverlayContainer } from '@angular/cdk/overlay';
import {HttpClientModule} from ""@angular/common/http"";
import {RouterTestingModule} from ""@angular/router/testing"";
import {DataService} from ""../../../services/data.service"";
import {of} from ""rxjs/internal/observable/of"";

describe('Component: admin-dialog', () =&gt; {

  let component: AdminDialogComponent;
  let fixture: ComponentFixture&lt;AdminDialogComponent&gt;;
  let translate: TranslateService;
  let dialog: MatDialog;
  let overlayContainer: OverlayContainer;
  let dataService: DataService;
  beforeEach(() =&gt; {


    TestBed.configureTestingModule({
      imports: [FormsModule, MatDialogModule, HttpClientModule,RouterTestingModule,TranslateModule.forRoot()],
      declarations: [AdminDialogComponent],
      providers: [TranslateService,
        { provide: MatDialogRef, useValue: {} },
        {
          provide: MAT_DIALOG_DATA, useValue: {
            isNew: false, // I guess it's boolean
            adminObj: {firstName: ""AAAAAA"", lastName: ""AA"", password: null, emailId: ""test@test.com"",
              access : [
                {
                  accessCode: 1,
                  accessName: 'test',
                  path: '/admin/tests',
                  orderBy: 5,
                  access: []
                },
                {
                  accessCode: 3,
                  accessName: 'view-aep-org',
                  path: '/admin/testing',
                  orderBy: 1,
                  access: []
                }]
            }
          }
        },
        {provide: dataService, useValue: {}}
      ],
      schemas: [NO_ERRORS_SCHEMA]
  });
    TestBed.overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [AdminDialogComponent]
      }
    });

    TestBed.compileComponents();

    // create component and test fixture
    fixture = TestBed.createComponent(AdminDialogComponent);

    // get test component from the fixture
    component = fixture.componentInstance;
   // component.ngOnInit();
  });
  beforeEach(inject([MatDialog, OverlayContainer],
    (d: MatDialog, oc: OverlayContainer) =&gt; {
      dialog = d;
      overlayContainer = oc;
    })
  );
  afterEach(() =&gt; {
    overlayContainer.ngOnDestroy();
  });
  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
  it('saveAdmin for requiredAccessError ', () =&gt; {
    component.adminObj = {firstName: ""AAAAAA"", lastName: ""AA"", password: null, emailId: ""test@test.com"",
      access : [
        {
          access: null,
          accessCode: 1,
          accessName: ""test"",
          active: true,
          orderBy: 1,
          parentAccessCode: null,
          path: ""/test/test"",
          selected: false,
          showCheckbox: true
        }]
    };
    expect(component.saveAdmin()).toBeTruthy();
  });

});
</code></pre>

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

<pre><code>Component: admin-dialog &gt; saveAdmin for requiredAccessError
Expected undefined to be defined.
Error: Expected undefined to be defined.
    at &lt;Jasmine&gt;
    at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/webpack:/src/app/dashboard/manage-admin/admin-dialog/admin-dialog.component.spec.ts:150:35)
</code></pre>
",https://stackoverflow.com/questions/57309151/expected-undefined-to-be-defined-error-in-karma-unit-testing-while-testing-a-fun,"['angular', 'typescript', 'unit-testing', 'karma-jasmine']",4632,False,0,1
Jest/Enzyme Unit Testing: How to pass store to shallow component that uses redux 4 and react-redux 6 connect function,"<p>I'm doing as usual some unit tests with jest and enzyme for one new project. I used to test components that were connected to redux in this way:</p>

<p>a) a store generator</p>

<pre><code>import { createStore } from 'redux';

import rootReducer from '../src/reducers';

export const storeFactory = (initialState) =&gt; {
   return createStore(rootReducer, initialState);
}
</code></pre>

<p>which is consumed by the Input.test.js file</p>

<pre><code>import React from 'react';
import { shallow } from 'enzyme';

import { findByTestAttr,storeFactory } from '../../../test/testUtils';
import Input from './Input';



const setup = (initialState={}) =&gt; {
    const store = storeFactory(initialState);
    const wrapper = shallow(
        &lt;Input store={store} /&gt;
        ).dive();
    console.log(wrapper.debug());

}
</code></pre>

<p>being the example component Input.js: </p>

<pre><code>import React, { Component } from 'react';
import { connect } from 'react-redux';

class Input extends Component {
    render(){
        return &lt;div /&gt;;
    }
}

const mapStateToProps = (state) =&gt; {
    return {};
}

export default connect(mapStateToProps)(Input);
</code></pre>

<p>My npm package versions are: </p>

<pre><code> ""dependencies"": {
    ""ajv"": ""^6.6.2"",
    ""react"": ""^16.7.0"",
    ""react-dom"": ""^16.7.0"",
    ""react-redux"": ""^6.0.0"",
    ""react-scripts"": ""2.1.3"",
    ""redux"": ""^4.0.1""
  }

  ""devDependencies"": {
    ""check-prop-types"": ""^1.1.2"",
    ""enzyme"": ""^3.8.0"",
    ""enzyme-adapter-react-16"": ""^1.7.1"",
    ""jest"": ""^23.6.0"",
    ""jest-enzyme"": ""^7.0.1"",
    ""prop-types"": ""^15.6.2""
  }
</code></pre>

<p>And that used to work, but I'm getting this message when running the tests on the tests execution report: </p>

<blockquote>
  <p>Invariant Violation: Passing redux store in props has been removed
  and does not do anything. To use a custom Redux store for specific
  components,  create a custom React context with React.createContext(),
  and pass the context object to React-Redux's Provider and specific
  components like:  . You may also pass a {context :
  MyContext} option to connect</p>
</blockquote>

<p>I tried to pass the context as a parameter of shallow</p>

<pre><code>const setup = (initialState={}) =&gt; {
    const store = storeFactory(initialState);
    const wrapper = shallow(
        &lt;Input  /&gt;, { store }
        );
    console.log(wrapper.debug());

}
</code></pre>

<p>But then I get this logged to console</p>

<pre><code>&lt;ContextConsumer&gt;
        [function bound renderWrappedComponent]
      &lt;/ContextConsumer&gt;
</code></pre>

<p>and if I try to use then enzyme dive() method I get:</p>

<pre><code>const setup = (initialState={}) =&gt; {
    const store = storeFactory(initialState);
    const wrapper = shallow(
        &lt;Input  /&gt;, { store }
        ).dive();
    console.log(wrapper.debug());

}
</code></pre>

<blockquote>
  <p>Test suite failed to run</p>

<pre><code>TypeError: ShallowWrapper::dive() can only be called on components
</code></pre>
</blockquote>

<p>Which is the suggested way of doing it now? I know what the message says but before there was no need of wrapping the element into a Provider for jest/enzyme unit tests. Thank you very much!</p>
",https://stackoverflow.com/questions/54069493/jest-enzyme-unit-testing-how-to-pass-store-to-shallow-component-that-uses-redux,"['reactjs', 'unit-testing', 'redux', 'jestjs', 'enzyme']",20175,True,20,1
How to access and test private widgets of a Qt window from Qt Test unit testing class?,"<p>I am trying to unit test (using Qt Test) the individual widgets in a Qt Widgets application, like menuBar, pushButton, etc. The project has been set up as a Subdirs project, where the both the Qt application and GUI test sub projects have their own directory and .pro file. The problem is that I cannot access any widget residing in MainWindow from the test class (MainWindowTest), as the compiler says:</p>

<ul>
<li>error: cannot cast 'MainWindow' to its private base class 'Ui_MainWindow'</li>
<li>'pushButton' is a private member of 'Ui_MainWindow'</li>
<li>constrained by private inheritance here</li>
</ul>

<p>I tried to declare the MainWindowTest a friend in MainWindow, but it didn't help.
I also tried to forward declare MainWindowTest in a separate header and then include it in mainwindow.h (a still declare MainWindowTest as friend), but that didn't help either.</p>

<p>Just creating a default subdir Widget application and a GuiTest AutoTest subdir project in Creator will produce all necessary code for this.</p>

<p>What I'm actually trying to achieve here, is to make a MainWindow instance in the private area of MainWindowTest and then write a couple of unit tests to check for the existence of the widgets and then do some keyboard and mouse event based testing. But, because I cannot even have access to the widgets, it would be terribly hard to do so.</p>

<p>I already looked through a couple of ""solutions"" over the net, but none of them seem to be clean solutions. I'd like to be able to execute QVERIFY2(win.pushButton, ""pushButton wasn't created."") sort of thing right now, but as I have said, pushButton is inaccessible.</p>
",https://stackoverflow.com/questions/56551921/how-to-access-and-test-private-widgets-of-a-qt-window-from-qt-test-unit-testing,"['c++', 'qt', 'unit-testing', 'user-interface', 'qttest']",682,False,1,0
Wait for element to be appeared in the dom and then execute code angular 6 unit testing,"<p>I need to wait for element to be loaded in the dom, so that I need to check the text string it contains.</p>

<p>I tried so far, <code>fixture.whenStable().then</code> but didn't work. How can I wait for the element until it loads in the dom.</p>

<pre><code>it( 'should change the text value for the element', function() {
    let testDropdown : HTMLElement;
    const debugElement : DebugElement = fixture.debugElement;
    fixture.detectChanges();
    testDropdown = debugElement.queryAll( By.css( 'mat-select' ) )[ 0 ].nativeElement;
    testDropdown.click();
    fixture.detectChanges();
    debugElement.queryAll( By.css( 'mat-option' ) )[ 1 ].nativeElement.click();
    fixture.detectChanges();
    expect( testDropdown.getAttribute( 'ng-reflect-value' ) ).toEqual( 'Text 2' );
    fixture.detectChanges();
    const elementTitle = debugElement.queryAll( By.css( '.legend' ) );
    console.log( elementTitle );
} );
</code></pre>

<p>Once I change the select option, the same select option text, I am setting to legend element. I need to wait for that legend item to be loaded. That element will be loaded asynchronously.</p>

<p>Any suggestions? How can I proceed?</p>
",https://stackoverflow.com/questions/57471211/wait-for-element-to-be-appeared-in-the-dom-and-then-execute-code-angular-6-unit,"['angular', 'unit-testing', 'karma-jasmine', 'typescript2.0']",520,False,1,0
With unit testing how to test a switchMap in viewModel calls the proper method from repository class,"<p>In my ViewModel i have used swithcMap with a liveData varaible  as parameter. When the liveData variable gets set/changed then the switchMap calls a method from my Repository. My viewModel code:</p>

<pre><code>class MainViewModel @Inject constructor(val mainRepository: MainRepository) : ViewModel() {

    var searchQuery:MutableLiveData&lt;SearchQuery&gt; = MutableLiveData()
    var liveResult:MediatorLiveData&lt;My_Result&gt; = MediatorLiveData()


    var apiData:LiveData&lt;My_Result&gt; = Transformations
    .switchMap(searchQuery){query -&gt;
        query?.let {
        val source: LiveData&lt;My_Result&gt; = mainRepository.fetchApiresultFromClient(it.filter_search , it.filter_topics, it.filter_language , it.page_number)

        liveResult.addSource(source){ item-&gt;
            liveResult.value = item
            liveResult.removeSource(source)
        }

        source

        }
    }

}
</code></pre>

<p>Now I want to test that if searchQuery is set then:</p>

<ul>
<li>switchMap is triggered</li>
<li>and when switchMap is triggered then mainRepository.fetchApiresultFromClient(..) is called</li>
<li>also if mainRepository.fetchApiresultFromClient(..) is called then the returned type is of LiveData</li>
</ul>

<p>How do I do this? All I have managed to do is :</p>

<pre><code>@ExtendWith(InstantExecutorExtension::class)
class MainViewModelTest {

    lateinit var  mainViewModel: MainViewModel

    @Mock
     lateinit var  mainRepository: MainRepository


    @BeforeEach
    fun init()  {
    MockitoAnnotations.initMocks(this)
    mainViewModel = MainViewModel(mainRepository)
    }


    @Test
    @Throws(Exception::class)
    fun setSearchQuery_callsRepositoryMethod() {
    var filter_search: SearchQuery = SearchQuery(""java"", """","""",1)

    }

}
</code></pre>
",https://stackoverflow.com/questions/59461795/with-unit-testing-how-to-test-a-switchmap-in-viewmodel-calls-the-proper-method-f,"['android', 'unit-testing']",447,True,1,1
How to fix error &quot;could not find store in context connect(App)&quot; when unit testing connected components?,"<p><strong>EDIT: Instead of deleting, I revised my question. Sorry about that</strong></p>

<p>I am trying to get rid of an error which I originally thought was me not ""properly"" connecting my component to the store. I would appreciate it if someone can provide a fix for this as I am now beginning to suspect that it is a bug.</p>

<p>So as it turns out, testing components that are 'connected' to Redux store takes a little more effort to set up.</p>

<p>Following the official docs from <a href=""https://redux.js.org/recipes/writing-tests#connected-components"" rel=""nofollow noreferrer"">https://redux.js.org/recipes/writing-tests#connected-components</a>, I now have this:</p>

<p><strong>In my App.js</strong></p>

<pre><code>export class App extends Component{
           ....
}

......

export default connect(mapStateToProps, mapDispatchToProps)(App);
</code></pre>

<p><strong>and inside the default App.test.js provided by create-react-app :</strong></p>

<p>I import the ""unconnected"" component, by importing the named import like so:</p>

<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
//import unconnected component
import { App } from './App';


 it('renders without crashing', () =&gt; {
   const div = document.createElement('div');
   ReactDOM.render(&lt;App /&gt;, div); // where i get the persistent error
   ReactDOM.unmountComponentAtNode(div);
 });


</code></pre>

<p>However, the problem ""could not find store in the connect(app)"" still persists. What am I doing wrong? </p>

<p>I am using VSCode with Jest extension installed, anyone replicate the same behavior?</p>
",https://stackoverflow.com/questions/57038996/how-to-fix-error-could-not-find-store-in-context-connectapp-when-unit-testin,"['reactjs', 'react-redux', 'react-router']",731,True,1,3
Unable to find svg element for unit-testing of d3 component in React using enzyme and cheerio,"<p>I have a React component that renders a div element, d3 in another class is used to append a svg element to the above div element.</p>

<p>While unit-testing with enzyme, the find() method is unable to detect the svg element inside the div. This svg element doesn't have any <code>id</code> as it was created through d3. I referred this <a href=""https://github.com/airbnb/enzyme/issues/1510"" rel=""nofollow noreferrer"">https://github.com/airbnb/enzyme/issues/1510</a> but it didn't help.</p>

<p>I referred to another example which uses cheerio to detect html elements but that didn't work either. <a href=""https://medium.com/successivetech/unit-testing-react-d3-with-enzyme-and-jest-108735046535"" rel=""nofollow noreferrer"">https://medium.com/successivetech/unit-testing-react-d3-with-enzyme-and-jest-108735046535</a></p>

<p>Below is the code from the test file. The first test passes i.e the div element is rendered but the second test fails.</p>

<pre><code>import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import { configure, mount } from 'enzyme';
import { expect } from 'chai';
import MostConvProds from './MostConvProds'; 
import { MockedProvider } from ""@apollo/react-testing"";
import { getDataAndConfig, getHtml, checkSvg } from './Helper';

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

const setUp = (props={}) =&gt; {
const component = mount(&lt;MockedProvider&gt;&lt;MostConvProds {...props}/&gt; 
&lt;/MockedProvider&gt;);

return component;
};

describe('The component should render according to props', () =&gt; {
    let component;
    beforeEach(() =&gt; {
        const props = {

        count:1,
        loading: false,
        products: [{productName: 'a', productId: '1', count:10},
                   {productName: 'b', productId: '2', count:9},
                   {productName: 'c', productId: '3', count:8},
                   {productName: 'd', productId: '4', count:7},
                   {productName: 'e', productId: '5', count:6}
                  ],
    }
    component = setUp(props);
 });


 it('Should render the div without any errors', () =&gt; {
    const wrapper = component.find('#mostConvProds');
    expect(wrapper).to.have.length(1);
    // const svg = Icons.IconWrapper(props, children);
    // const wrapper1 = wrapper.find('svg').html();
    //expect(wrapper1.find(&lt;rect&gt; &lt;/rect&gt;)).to.have.length(1);
})

it('Should render svg element without any errors', () =&gt; {
   const wrapper = component.find('#mostConvProds');
   expect(getHtml(wrapper, ""svg"")).to.have.length(1); 
   //expect(component.find(`svg[viewBox=""0 0 440 
   //150""]`)).to.have.length(1);  //didn't work
})
})
</code></pre>

<p>The Helper.js file is as follows</p>

<pre><code>const cheerio = require('cheerio');

export const checkSvg = (component) =&gt; {
const $ = getHtml(component, 'svg');
const svgHeight = $('svg').attr('height');
const svgWidth = $('svg').attr('width');
return svgHeight == '150' &amp;&amp; svgWidth == '440';
}

export const getHtml = (component, tag) =&gt; {
const cheerioData = cheerio.load(component.find(tag).html());
return cheerioData;
}
</code></pre>

<p>The error message </p>

<pre><code>Method “html” is meant to be run on 1 node. 0 found instead.

   9 | 
  10 | export const getHtml = (component, tag) =&gt; {
&gt; 11 | const cheerioData = cheerio.load(component.find(tag).html());
     |                                                      ^
  12 | return cheerioData;
  13 | }
</code></pre>

<p>Below is the component that renders the div </p>

<pre><code>class d3Component extends Component {

componentDidMount(){
    new d3class(this.refs.mostConChart, this.props.products)
}

render() {
    return (
        &lt;div id={'mostConvProds'} className={style.container} 
             ref='mostConChart'&gt; &lt;/div&gt;
     )
   }
}
</code></pre>

<p>the <code>d3Class</code> is where all the d3 code is present. </p>

<pre><code>import * as d3 from 'd3'

const HEIGHT = 150;
const WIDTH = 350;

export default class d3Class {
constructor(element, product) {
    const svg = d3.select(element)
        .append(""svg"")
        .attr(""width"", WIDTH + 90)
        .attr(""height"", HEIGHT)
        .attr(""x"",0)
        .attr(""y"",0)


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

<p>Any help will be appreciated.</p>
",https://stackoverflow.com/questions/58057684/unable-to-find-svg-element-for-unit-testing-of-d3-component-in-react-using-enzym,"['reactjs', 'd3.js', 'svg', 'jestjs', 'enzyme']",3974,True,0,2
How to pass test-case forcibly in Async await Node.js Unit Testing code using Chai and mocha,"<p>I am using below test-case for testing an service in Mocha and Chai and it is working fine.</p>

<pre><code>describe('Google ', () =&gt; {
  it('POST: Google.', async () =&gt; {
    const results = await readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${results.toString()}`);
  });
});
</code></pre>

<p>There is one scenario which i need to handle with respect to above code. Actually I am getting this exception from service class readGoogle.execute method sometimes.</p>

<pre><code> TypeError: Cannot read property 'status' of undefined
</code></pre>

<p>And this is expected from readGoogle.execute method perspective. But my requirement is I need to pass the above test case even though I get the error from readGoogle.execute await method.</p>

<p>1) I do not have access to readGoogle.execute method, so I can't handle the undefined check there. Anything to be done in my test case only.</p>

<p>2) I tried to <code>return true,</code> in above <code>'it'</code> but still, test case is failing.</p>

<p>3) I also tried, assert(true); in above <code>it</code>, but still, test case is failing.</p>

<p>Can anyone suggest to me some idea where I could pass the above test_case always (even in success and failure scenario)?</p>

<p>Thanks in advance.  </p>
",https://stackoverflow.com/questions/58988968/how-to-pass-test-case-forcibly-in-async-await-node-js-unit-testing-code-using-ch,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'chai']",58,True,-1,1
Is there a way in angular (unit testing) to find a component by its @Input() property values?,"<p>This question refers to angular unit tests. I'm searching for a short way to find components by the values, which they receive through their <code>@Input()</code> data binding.</p>

<p>I have the following child component <code>MyComponent</code>. Which has an <code>@Input() property called</code>id`:</p>

<pre><code>@Component({
    selector: 'my-component,
    template: `... something ...`
})
class MyComponent {
    @Input() id: string;
}
</code></pre>

<p>I use this component inside a <code>ParentComponent</code> and pass different <code>ids</code> through the <code>@Input()</code> property:</p>

<pre><code>...
&lt;my-component [id]=""first-comp""&gt;&lt;/my-component&gt;
&lt;my-component [id]=""second-comp""&gt;&lt;/my-component&gt;
...
</code></pre>

<p>Now I have a unit test for the <code>ParentComponent</code>. If I want to find the two components by their <code>id</code> I'm doing this:</p>

<pre><code>let firstComponent: MyComponent;
let secondComponent: MyComponent;

const myComponents = debugElement.query(By.css('my-component'));
for (const myComponent of myComponents) {
    if (myComponent.componentInstance.id === 'first-comp') {
        firstComponent = myComponent.componentInstance;
    } else if (myComponent.componentInstance.id === 'second-comp') {
        secondComponent = myComponent.componentInstance;
    }
}
</code></pre>

<p>This code is not very easy to write. Does angular provide a function like, to do this in an easier way without the for-loop? Something like this:</p>

<pre><code>const firstComponent = debugElement.query(By.css('my-component[id=""first-component""]'));
const secondComponent = debugElement.query(By.css('my-component[id=""second-component""]'));
</code></pre>

<p>Thank you for your help.</p>
",https://stackoverflow.com/questions/56440351/is-there-a-way-in-angular-unit-testing-to-find-a-component-by-its-input-pro,"['angular', 'typescript', 'unit-testing', 'jasmine']",761,False,0,2
How to set up Mongo DB in Go for a rest service that allows for unit testing?,"<p>I am setting up a rest service in go using MongoDB and mux routers. I am running into issues on how to best set this up to allow for unit/integration testing in a separate database.</p>

<p>I have tried setting up the database in the Init() function but this is giving me issues when trying to set up unit tests using a test DB.</p>

<p>Here are some examples of where I am at right now. I am trying to use a method to connect to the database before posting so in my test I can connect to a different testing database.</p>

<pre class=""lang-golang prettyprint-override""><code>type user struct {
    name string `json:""name""`
    age  int    `json:""age""`
}

type database struct {
    db *mongo.Database
}

func ConnectToDB() (*database, error) {
    client, err := mongo.NewClient(options.Client().ApplyURI(""mongodb://localhost:27017""))
    if err != nil {
        return nil, err
    }

    if err := client.Connect(context.Background()); err != nil {
        return nil, err
    }

    database := &amp;database{
        db: client.Database(""PMBaseGo""),
    }

    return database, nil
}

func PostUser(w http.ResponseWriter, r *http.Request) {
    w.Header().Set(""Content-Type"", ""application/json"")
    //Retrieving request body
    var user user
    _ = json.NewDecoder(r.Body).Decode(&amp;user)
    //Posting Company.
    err := PostUserToDB(user)
    //Error Handling
    if err != nil {
        fmt.Println(err)
        w.WriteHeader(500)
    }
}

func (d *database) connPostUserToDB(user user) error {
    _, err := d.db.Collection(""companies"").InsertOne(context.Background(), user)
    if err != nil {
        return err
    }
    return nil
}

func main() {
    _, _ = ConnectToDB()
    r := mux.NewRouter()

    r.HandleFunc(""/user"", PostUser).Methods(""POST"")

    fmt.Println(""Application Running..."")
    log.Fatal(http.ListenAndServe(""localhost:8081"", r))
}
</code></pre>

<p>The issue I am at right now is trying to call the <code>PostUserToDB</code> method in the <code>PostUser</code> function.</p>

<p>I'm starting to think the issue lies prior to this in how I am going about connecting to the DB.</p>
",https://stackoverflow.com/questions/56189532/how-to-set-up-mongo-db-in-go-for-a-rest-service-that-allows-for-unit-testing,"['rest', 'unit-testing', 'go', 'mux']",237,True,-1,1
Is there a way to set the configuration settings for a class that you are unit testing?,"<p>I've written all of the logic for my test project but I'm running into the problem of trying to set configuration variables in the class that I want to run. The class requires a <code>workingDirectory</code> variable to be set to a file path depending on what environment the program is being run in (for example production or test) and right now the variable is null. How do I get the configuration settings to run as if the class was being run normally (since the configuration settings are set when the class is run on its own or when it's not being tested)? </p>

<p>I've tried adding the app.config file that is used in the class being tested to the test project but that still won't set the configuration variables for me. </p>

<pre><code>private static readonly string WorkingDir = ConfigurationManager.AppSettings[""WorkingDirectory""];

var files = Directory.GetFiles($@""{WorkingDir}\in""); //this results in the 
//filepath being ""C:\in"" when testing since the WorkingDir configuration 
//variable doesn't get set when the class is called from the test project

&lt;add key=""WorkingDirectory"" value=""\\Test"" xdt:Transform=""Insert""/&gt;
</code></pre>

<p>The configuration variable should be ""\Test"" when the class is run from the test project but instead is null or whitespace. This ends up being an error because there is not a directory that matches the string given to the <code>Directory.GetFiles()</code> line of code, and thus it won't find the files that I want it to find.</p>
",https://stackoverflow.com/questions/58240329/is-there-a-way-to-set-the-configuration-settings-for-a-class-that-you-are-unit-t,"['c#', 'unit-testing', 'configurationmanager']",238,True,0,1
How can I properly get the errors in unit testing laravel as well as disable csrf checks?,"<p>I'm trying to test my <code>post</code> method in the controller. The method definition is something like :</p>

<pre><code>    public function store(Request $request)
    {
        $article = new Article;

        $article-&gt;id = $request-&gt;input('article_id');
        $article-&gt;title = $request-&gt;input('title');
        $article-&gt;body = $request-&gt;input('body');
        return response([""success""], 200);
    }
</code></pre>

<p>I've created a test which just stores the data and checks if the response is 200.
Please also show me how can I make this test better new to testing. But I'm getting <code>404 error</code> I don't know what is the error. How can I display the errors what are the setting I need to configure?
<strong>Test:</strong></p>

<pre><code>public function test_post_new_article(){
        $article = factory(Article::class)-&gt;make();
        $this-&gt;call('POST', 'article', [
            '_token' =&gt; csrf_token(),
            'article_id' =&gt; 6,
            'title'=&gt;""hey"",
            'body' =&gt; ""this is a body""
        ])-&gt;assertStatus(200);
    }
</code></pre>

<p><strong>phpunit error:</strong></p>

<pre><code>There was 1 failure:

1) Tests\Unit\ExampleTest::test_post_new_article
Expected status code 200 but received 404.
Failed asserting that false is true.
</code></pre>
",https://stackoverflow.com/questions/55095682/how-can-i-properly-get-the-errors-in-unit-testing-laravel-as-well-as-disable-csr,"['unit-testing', 'laravel-5', 'phpunit']",123,True,0,1
Best practice to tackle flyway migrations where statements are not understood in H2 database for unit testing,"<p>I have a flyway migration file which has among others the following command: </p>

<pre><code>grant all privileges on schema public to ${admin_user} with grant option;`
</code></pre>

<p>Now I also want to unit test the sql files using an H2 database. But even with turned on <code>MODE=PostgreSQL</code> the grant statement is problematic as it is not understood by the H2 database. So what is the best practice here to tackle this kind of dialect problems?</p>
",https://stackoverflow.com/questions/55021199/best-practice-to-tackle-flyway-migrations-where-statements-are-not-understood-in,"['unit-testing', 'flyway']",160,True,0,1
"VueJs TestUtil: In jest unit testing, html is not reactive when data is modified in mounted hook","<p>While jest unit testing for a component, if the component has mounted hook to update the data, after that the html is no longer reactive. It's stuck with the data before the modification by mounted hook.<br>
The <strong>testutil</strong> version is: <strong>1.0.0-beta.29</strong></p>

<p>component: count.ts</p>

<pre class=""lang-typescript prettyprint-override""><code>import { Component, Vue } from 'vue-property-decorator';

@Component({
  template: `
  &lt;div&gt;
    count:{{ count }}
    &lt;button @click=""increment""&gt;Increment&lt;/button&gt;
  &lt;/div&gt;
  `,
})
export default class Count extends Vue {
  count = 0;
  mounted() {
    // comment following line, everything works fine.
    this.count = 10;
  }

  increment() {
    this.count++;
  }
}

</code></pre>

<p>testing spec: count.spec.ts</p>

<pre class=""lang-typescript prettyprint-override""><code>import { mount } from '@vue/test-utils';
import Counter from './counter';

it('button click should increment the count', () =&gt; {
  const wrapper = mount(Counter);
  const button = wrapper.find('button');
  button.trigger('click');
  console.log(`wrapper.vm.count=${wrapper.vm.count}`);
  console.log(`html=${wrapper.html()}`);
});

</code></pre>

<p>If I comment out the line in <code>mounted()</code>, everything works fine.   Otherwise, the output will be </p>

<pre><code>wrapper.vm.count=11
html=&lt;div&gt;
  count:0
  &lt;button&gt;Increment&lt;/button&gt;&lt;/div&gt;
</code></pre>

<p>The html is supposed to print <code>count:11</code> instead of <code>count:0</code>.</p>
",https://stackoverflow.com/questions/58385255/vuejs-testutil-in-jest-unit-testing-html-is-not-reactive-when-data-is-modified,"['typescript', 'vue.js', 'jestjs']",327,False,0,0
Why Unit Testing Assert.AreEqual() method does NOT pick up my own Equals() method in the customized class,"<p>I am trying to build a Unit Test project for a.Net Framework Class Library project.  I have some customized model types, which implement the <code>IEquatable&lt;T&gt;</code> interface and have their own <code>Equals()</code> method,  in the project to be tested. 
I read several docs online where they say the <code>Assert.AreEqual</code> method only operates <code>RefereceEqual</code> when the object does not have its own <code>Equals()</code> method. But I found that the TestMethod still not return true even the object has its own <code>Equals</code> method. I recreated the scenario below using a simple example. Did I do something wrong?</p>

<pre><code>namespace Demo
{
    public class MyDog : IEquatable&lt;MyDog&gt;
    {
        public string Name;
        public int Age;

        public bool Equals(MyDog other)
        {
            if (other == null) return false;
            return (this.Name == other.Name) &amp;&amp; (this.Age == other.Age);
        }
    }
}
</code></pre>

<pre><code>namespace DemoTest
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void MyDogTest()
        {
            var dog1 = new MyDog { Age = 10, Name = ""Jack"" };
            var dog2 = new MyDog { Age = 10, Name = ""Jack"" };

            Assert.AreEqual(dog1, dog2);
        }
    }
}
</code></pre>

<p>the <code>dog1.Equals(dog2)</code> will return true, while the unit test will fail. How to properly compare dog1 and dog2 in the Test method.</p>
",https://stackoverflow.com/questions/56070558/why-unit-testing-assert-areequal-method-does-not-pick-up-my-own-equals-metho,"['c#', '.net', 'unit-testing']",424,True,0,1
How we can do unit testing in windows form c# where i have built in private methods,"<pre><code>private void name_KeyPress(object sender, KeyPressEventArgs e)
{
     char ch = e.KeyChar;
     if (!char.IsLetter (ch) &amp;&amp; (ch != 8))
     {
         e.Handled = true;
     } 
}
</code></pre>

<p>1.<strong>some part of the code.how to do unit testing for this code</strong></p>

<pre><code>public int validation()
{
    int flag = 0;
    Regex Rx = new Regex(@""^[\p{L} \.'\-]{0,20}$"");
    Regex Rx1 = new Regex(@""^[\p{L} \.'\-]{0,20}$"");
    Regex Rx2 = new Regex(@""^[0-9]{10}$"");
    if (name.Text=="""")
    {
         name.Focus();
         errorProvider1.SetError(name, MessageBox.Show(""enter your name"", ""error"", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
         flag = 1;
    }
    else if (fathername.Text == """")
    {
        fathername.Focus();
        errorProvider1.SetError(name, MessageBox.Show(""Enter your father name"", ""error"", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
        flag = 1;
    }
}
</code></pre>

<p>its a public method</p>
",https://stackoverflow.com/questions/54268849/how-we-can-do-unit-testing-in-windows-form-c-where-i-have-built-in-private-meth,"['c#', '.net', 'forms', 'winforms', 'unit-testing']",245,True,0,2
How to set a const value of a file from test file in node js unit testing,"<p>I am new to node js because of that facing some difficulties while doing unit testing of my code.
My issue is how to set a const value from testing file.
I have one class (ClassA) having two input param fileName and response, I am reading this file cell by cell and comparing its value in while loop.
I question is how to unit test this scenario.</p>

<p>Example :</p>

<p>ClassA.js </p>

<pre><code>function classAFunction(filename,res) { 
try {
        let workbook = XLSX.readFile(filename);
        let sheet_name = 'A';
        let worksheet = workbook.Sheets[sheet_name];
        let columnCount =1;
        let columnCountStartWithB = 'B'+columnCount;
        let valueOfColunBCell='';
        if(worksheet[columnCountStartWithB] != undefined ){
            valueOfColunBCell = worksheet[columnCountStartWithB].v; // how to set this value from test file
        } 

        while(true) {

          // some if else based of cell value 
          // increment value of columnCountStartWithB  B1, B2, B3....
         }

}catch (e){
        res.json({error_code:1,err_desc:""Corupted excel file""});
 }
}
</code></pre>

<p>ClassATest.js </p>

<pre><code>beforeEach(function() {

        mock({
            'fake-file-for-testing-only': 'file content'
          });

      });
 afterEach(mock.restore);

it('function Success Case', function(done) {
        let res = {
            status: sinon.spy(),
            json: sinon.spy()
          }

       //how to set valueOfColunBCell  value from this test file
        parsingUpload('fake-file-for-testing-only', res);

        done();
    });
</code></pre>
",https://stackoverflow.com/questions/59394873/how-to-set-a-const-value-of-a-file-from-test-file-in-node-js-unit-testing,"['node.js', 'unit-testing']",359,False,0,0
Unable to debug dll when unit testing - not hitting breakpoints and unable to change configuration in properties,"<p>Created a library and performing some unit test. One of the Test Methods failed and I am unable to debug the issue as any break points on the dll project fail to hit.</p>
<p>I have tried some of the solutions on stackoverflow unsuccessfully and I was trying <a href=""https://learn.microsoft.com/en-us/visualstudio/debugger/how-to-debug-from-a-dll-project?view=vs-2019"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/debugger/how-to-debug-from-a-dll-project?view=vs-2019</a></p>
<p>I have tried out both methods - &quot;Specify a calling app in the native dll project&quot; &amp; &quot;Specify a calling app in the managed dll project&quot;. But these options either do not exist or grayed out (see images).
<a href=""https://i.stack.imgur.com/b3KMk.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/b3KMk.jpg"" alt=""enter image description here"" /></a></p>
<p><a href=""https://i.stack.imgur.com/gzTzb.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gzTzb.jpg"" alt=""enter image description here"" /></a></p>
<p>How do I debug the DLL (add breakpoints) so I can debug the dll if it fails a Unit Test.</p>
",https://stackoverflow.com/questions/56845859/unable-to-debug-dll-when-unit-testing-not-hitting-breakpoints-and-unable-to-ch,"['c#', 'visual-studio', 'unit-testing', 'debugging', 'dll']",1207,True,0,1
Android unit testing if an activity starts with a timeout or after a delay is not working,"<p>I am developing an Android application using Kotlin programming language. I am adding instrumented tests into my project. Now, I am having a problem with testing if an activity is started after a delay. I am using Espresso for instrumented tests. </p>

<p>This is my activity class</p>

<pre><code>class MainActivity : AppCompatActivity() {

    companion object {
        val LAUNCH_DELAY: Long = 2000
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Handler().postDelayed({
            this.startLoginActivity()
        }, LAUNCH_DELAY)
    }

    protected fun startLoginActivity()
    {
        startActivity(Intent(this, LoginActivity::class.java))
    }
}
</code></pre>

<p>I tried this</p>

<pre><code>@RunWith(AndroidJUnit4::class)
class MainActivityTest {
    @Rule @JvmField
    val mainActivityRule: ActivityTestRule&lt;MainActivity&gt; = ActivityTestRule&lt;MainActivity&gt;(MainActivity::class.java)

    @Test
    fun itStartsLoginActivityAfterDelay() {
        Intents.init()
        mainActivityRule.launchActivity(Intent())
        Handler().postDelayed({
            Intents.intended(hasComponent(LoginActivity::class.java.name))
            Intents.release()
        }, 2000);
    }
}
</code></pre>

<p>I got this error</p>

<pre><code>E/TestRunner: failed: itStartsLoginActivityAfterDelay(com.example.memento.MainActivityTest)
    ----- begin exception -----
E/TestRunner: java.lang.RuntimeException: Can't create handler inside thread Thread[Instr: com.example.memento.MockTestRunner,5,main] that has not called Looper.prepare()
        at android.os.Handler.&lt;init&gt;(Handler.java:205)
        at android.os.Handler.&lt;init&gt;(Handler.java:118)
        at com.example.memento.MainActivityTest.itStartsLoginActivityAfterDelay(MainActivityTest.kt:37)
        at java.lang.reflect.Method.invoke(Native Method)
        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 androidx.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:531)
        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 androidx.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:104)
        at org.junit.runners.Suite.runChild(Suite.java:128)
        at org.junit.runners.Suite.runChild(Suite.java:27)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
        at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
        at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:388)
        at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2145)
    ----- end exception -----
</code></pre>

<p>I also tried this</p>

<pre><code>@Test
    fun itStartsLoginActivityAfterDelay() {
        Intents.init()
        mainActivityRule.launchActivity(Intent())
        Thread.sleep(2000);
        Intents.intended(hasComponent(LoginActivity::class.java.name))
        Intents.release()
    }
</code></pre>

<p>This time I got this error</p>

<pre><code>E/TestRunner: failed: itStartsLoginActivityAfterDelay(com.example.memento.MainActivityTest)
E/TestRunner: ----- begin exception -----
E/TestRunner: androidx.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: Wanted to match 1 intents. Actually matched 2 intents.

    IntentMatcher: has component: has component with: class name: is ""com.example.memento.LoginActivity"" package name: an instance of java.lang.String short class name: an instance of java.lang.String

    Matched intents:
    -Intent { cmp=com.example.memento/.LoginActivity } handling packages:[[com.example.memento]])
    -Intent { cmp=com.example.memento/.LoginActivity } handling packages:[[com.example.memento]])

    Recorded intents:
    -Intent { flg=0x10000000 cmp=com.example.memento/.MainActivity } handling packages:[[com.example.memento]])
    -Intent { cmp=com.example.memento/.LoginActivity } handling packages:[[com.example.memento]])
    -Intent { cmp=com.example.memento/.LoginActivity } handling packages:[[com.example.memento]])
        at dalvik.system.VMStack.getThreadStackTrace(Native Method)
        at java.lang.Thread.getStackTrace(Thread.java:1538)
        at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:94)
        at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:57)
        at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:318)
        at androidx.test.espresso.ViewInteraction.check(ViewInteraction.java:300)
        at androidx.test.espresso.intent.Intents.intended(Intents.java:189)
        at androidx.test.espresso.intent.Intents.intended(Intents.java:170)
        at com.example.memento.MainActivityTest.itStartsLoginActivityAfterDelay(MainActivityTest.kt:47)
        at java.lang.reflect.Method.invoke(Native Method)
        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 androidx.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
        at androidx.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:531)
        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 androidx.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:104)
        at org.junit.runners.Suite.runChild(Suite.java:128)
        at org.junit.runners.Suite.runChild(Suite.java:27)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
        at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
        at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:388)
        at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2145)
     Caused by: junit.framework.AssertionFailedError: Wanted to match 1 intents. Actually matched 2 intents.

    IntentMatcher: has component: has component with: class name: is ""com.example.memento.LoginActivity"" package name: an instance of java.lang.String short class nam
    ----- end exception -----
I/TestRunner: finished: itStartsLoginActivityAfterDelay(com.example.memento.MainActivityTest)
I/MonitoringInstr: Activities that are still in CREATED to STOPPED: 4
    Finishing activity: com.example.memento.LoginActivity@97c0733
I/MonitoringInstr: Finishing activity: com.example.memento.LoginActivity@65a941b
I/MonitoringInstr: Finishing activity: com.example.memento.MainActivity@39cc00e

androidx.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: Wanted to match 1 intents. Actually matched 2 intents.

IntentMatcher: has component: has component with: class name: is ""com.example.memento.LoginActivity"" package name: an instance of java.lang.String short class name: an instance of java.lang.String

Matched intents:
-Intent { cmp=com.example.memento/.LoginActivity } handling packages:[[com.example.memento]])
-Intent { cmp=com.example.memento/.LoginActivity } handling packages:[[com.example.memento]])

Recorded intents:
-Intent { flg=0x10000000 cmp=com.example.memento/.MainActivity } handling packages:[[com.example.memento]])
-Intent { cmp=com.example.memento/.LoginActivity } handling packages:[[com.example.memento]])
-Intent { cmp=com.example.memento/.LoginActivity } handling packages:[[com.example.memento]])
at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:1538)
at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:94)
at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:57)
at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:318)
at androidx.test.espresso.ViewInteraction.check(ViewInteraction.java:300)
at androidx.test.espresso.intent.Intents.intended(Intents.java:189)
at androidx.test.espresso.intent.Intents.intended(Intents.java:170)
at com.example.memento.MainActivityTest.itStartsLoginActivityAfterDelay(MainActivityTest.kt:47)
at java.lang.reflect.Method.invoke(Native Method)
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 androidx.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
at androidx.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:531)
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 androidx.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:104)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:388)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2145)
Caused by: junit.framework.AssertionFailedError: Wanted to match 1 intents. Actually matched 2 intents.

IntentMatcher: has component: has component with: class name: is ""com.example.memento.LoginActivity"" package name: an instance of java.lang.String short class name: an instance of java.lang.String

Matched intents:
-Intent { cmp=com.example.memento/.LoginActivity } handling packages:[[com.example.memento]])
-Intent { cmp=com.example.memento/.LoginActivity } handling packages:[[com.example.memento]])

Recorded intents:
-Intent { flg=0x10000000 cmp=com.example.memento/.MainActivity } handling packages:[[com.example.memento]])
-Intent { cmp=com.example.memento/.LoginActivity } handling packages:[[com.example.memento]])
-Intent { cmp=com.example.memento/.LoginActivity } handling packages:[[com.example.memento]])
at junit.framework.Assert.fail(Assert.java:50)
at androidx.test.espresso.intent.VerificationModes$Times.verify(VerificationModes.java:80)
at androidx.test.espresso.intent.Intents.internalIntended(Intents.java:346)
at androidx.test.espresso.intent.Intents$2.check(Intents.java:193)
at androidx.test.espresso.ViewInteraction$SingleExecutionViewAssertion.check(ViewInteraction.java:419)
at androidx.test.espresso.ViewInteraction$2.call(ViewInteraction.java:282)
at androidx.test.espresso.ViewInteraction$2.call(ViewInteraction.java:268)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code></pre>

<p>That is not working as well. How can I test it?</p>
",https://stackoverflow.com/questions/58049862/android-unit-testing-if-an-activity-starts-with-a-timeout-or-after-a-delay-is-no,"['android', 'kotlin', 'android-espresso', 'instrumented-test']",2075,True,0,1
Do you think It is right approach to separate private function from class definition for unit testing?,"<p>When I'm writing some typescript code, I wanted to unit test some private method of Foo Class.</p>

<pre><code>class Foo {
   private privateMethodWantToTest(argument) {
      return 'Bar'
   }
}

</code></pre>

<p>So, I separated function like this:</p>

<pre><code>
export function privateMethodWantToTest(this: Foo, argument) {
   return 'Bar'
}

class Foo {
   private privateMethodWantToTest(argument) {
      return privateMethodWantToTest.call(this, argument) 
   }
}

</code></pre>

<p>This approach may work, but It's a bit redundant.
And exporting all function may be a bad idea.</p>

<p>What do you think about this approach ?
Is there better solution for unit test, or should't I test private method ?</p>
",https://stackoverflow.com/questions/55979260/do-you-think-it-is-right-approach-to-separate-private-function-from-class-defini,['unit-testing'],313,True,0,1
Angular Unit Testing with Spectator - Unexpected value &#39;FormBuilder&#39; imported by the module &#39;DynamicTestModule&#39;. Please add a @NgModule annotation,"<p>I want to use <a href=""https://github.com/ngneat/spectator"" rel=""nofollow noreferrer"">spectator</a> to assist me with my unit tests as I have read great things about it. However I'm not sure about how to resolve a problem with my tests. In my component template I have a <code>formGroup</code> like so...</p>

<pre><code>&lt;form [formGroup]=""emailReportForm"" (ngSubmit)=""emailReport()""&gt;
&lt;!-- Lots more HTML  here --&gt;
&lt;/form&gt;
</code></pre>

<p>and in my TS file I have the following in my <code>ngOnInit</code> / <code>constructor</code>...</p>

<pre><code>constructor(@Inject(MAT_DIALOG_DATA) data: any,
              private formBuilder: FormBuilder,
              private apiService: ApiService,
              public dialogRef: MatDialogRef&lt;EmailReportComponent&gt;) {
    this.data = data;
  }

 ngOnInit(): void {
      this.emailReportForm = this.formBuilder.group({
        emailAddress: new FormControl(null, [
          Validators.required,
          Validators.pattern('^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$')
        ]),
        updateOn: 'keyup'
      });
  }
</code></pre>

<p>So I need to mock my services and imports, so here is my spec.ts file... I have reduced some of the code for readability: </p>

<pre><code>import { createComponentFactory, Spectator } from '#ng/node_modules/@ngneat/spectator/jest';
import { ApiService } from '#ng/src/app/common/services/api/api.service';
import { MAT_DIALOG_DATA, MatDialogRef } from '#ng/node_modules/@angular/material';
import { FormBuilder, FormControl, FormGroup, Validators,} from '#ng/node_modules/@angular/forms';

describe('EmailReportComponent', () =&gt; {
  let spectator: Spectator&lt;EmailReportComponent&gt;;
  const mockData = { };
  const dialogMock = { close: () =&gt; { } };

  const createComponent = createComponentFactory({
    component: EmailReportComponent,
    imports: [
      FormBuilder,
      FormControl,
      FormGroup,
      Validators,
    ],
    componentProviders: [
      { provide: ApiService, useValue: { emailReport: jest.fn() } },
      { provide: MAT_DIALOG_DATA, useValue: mockData },
      { provide: MatDialogRef, useValue: dialogMock },
    ],
  });

  beforeEach(() =&gt; spectator = createComponent());
  describe('Methods', () =&gt; {
    // tests go here
  });
</code></pre>

<p>When I run my tests I get the following error: </p>

<blockquote>
  <p>Error: Unexpected value 'FormBuilder' imported by the module
  'DynamicTestModule'. Please add a @NgModule annotation.</p>
</blockquote>

<p>Now I could use <code>CUSTOM_ELEMENTS_SCHEMA</code> to prevent the error, but this seems wrong. Can anyone please advise me how to resolve my issue.</p>
",https://stackoverflow.com/questions/59068035/angular-unit-testing-with-spectator-unexpected-value-formbuilder-imported-by,"['angular', 'unit-testing', 'angular-test', 'angular-spectator']",6152,True,4,1
How to pass auto wired dependencies as mock while unit testing a class which has constructors with arguments,"<p>I am trying to unit test two separate classes, the constructor of one being the default constructor and the constructor of another, a constructor having some arguments. Both the classes have an autowired component, say,</p>

<pre><code>class A {
  @Autowired
  private SomeClass someClass;
}
</code></pre>

<pre><code>class B {
  @Autowired
  private SomeClass someClass;

  public B(int a, String b) {
    //method implementation
  }
}
</code></pre>

<p>I am trying to unit test these two classes and for the first one if I create the class object using</p>

<pre><code>def mockedSomeClass = Mock(SomeClass)
def a = new A(someClass:mockedSomeClass)
</code></pre>

<p>it works fine.</p>

<p>But for the second class , I have tried passing the constructor arguments and the dependencies required through different syntaxes</p>

<p>like</p>

<pre><code>def mockedSomeClass = Mock(SomeClass)
def b = new B(10, ""g"", someClass:mockedSomeClass)
</code></pre>

<p>and</p>

<pre><code>def b = new B(someClass:mockedSomeClass, 10, ""g"")
</code></pre>

<p>and</p>

<pre><code>def b = new B(10, ""g"")(someClass:mockedSomeClass)
</code></pre>

<p>All these were trial and error as I could not find any documentation similar to this particular case. </p>

<p>Any help on how to correctly do this would be highly appreciated</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/56591743/how-to-pass-auto-wired-dependencies-as-mock-while-unit-testing-a-class-which-has,"['java', 'groovy', 'spock']",351,True,2,1
How to test components using new react router hooks?,"<p>Until now, in unit tests, react router match params were retrieved as props of component.
So testing a component considering some specific match, with specific url parameters, was easy : we just had to precise router match's props as we want when rendering the component in test (I'm using enzyme library for this purpose).</p>

<p>I really enjoy new hooks for retrieving routing stuff, but I didn't find examples about how to simulate a react router match in unit testing, with new react router hooks ?</p>
",https://stackoverflow.com/questions/58117890/how-to-test-components-using-new-react-router-hooks,['react-router'],84694,True,112,10
Do I need a unit-testing framework if I&#39;m already using Cypress in a Vue.js app?,"<p>When scaffolding a new project with the Vue.js CLI, it offers a choice of both unit-testing and E2E-testing frameworks. </p>

<p>Unit-testing functionality is perfectly adequate in Cypress. My question, then: is there an advantage to using a distinct unit-testing framework if I'm already using Cypress?</p>
",https://stackoverflow.com/questions/54764650/do-i-need-a-unit-testing-framework-if-im-already-using-cypress-in-a-vue-js-app,"['unit-testing', 'vue.js', 'cypress', 'end-to-end']",1535,True,8,1
Appium support android unit testing or not?,"<p>Appium support android unit testing or not. If <strong>yes</strong> then how to perform these tests and if <strong>no</strong> then which tool or framework is support Appium for unit testing. Or I have to use another framework or tool for unit testing.</p>
",https://stackoverflow.com/questions/59084519/appium-support-android-unit-testing-or-not,"['android', 'unit-testing', 'appium-android']",437,False,0,2
Flutter/Dart wait for a few seconds in unit testing,"<p>I am writing a timer app. In unit testing how do I wait for few seconds to test if my timer is working properly?</p>

<pre><code>// I want something like this.
test(""Testing timer"", () {
    int startTime = timer.seconds;
    timer.start();

    // do something to wait for 2 seconds

    expect(timer.seconds, startTime - 2);

});
</code></pre>
",https://stackoverflow.com/questions/54088397/flutter-dart-wait-for-a-few-seconds-in-unit-testing,"['unit-testing', 'dart', 'flutter', 'wait']",36654,True,41,2
Unit testing for Google Cloud Functions,"<p>I was trying to write unit testing for Google Cloud Functions referring to Google Cloud Platform unit testing docs but not able to understand how to mock when Google Cloud Storage is used. Below is sample code for which I am trying to write unit testing :</p>

<pre><code>exports.listFiles = async(req, res) =&gt; {
  let bucketName = req.body.bucket || req.query.bucket

  // Import the Google Cloud Storage library
  const {Storage} = require('@google-cloud/storage');

  // Initiate a Storage client
  const storage = new Storage();

  // List files in the bucket and store their name in the array called 'result'
  const [files] = await storage.bucket(bucketName).getFiles();
  let result = [];
  files.forEach(file =&gt; {
    result.push(file.name);
  });

  // Send the result upon a successful request
  res.status(200).send(result);
};
</code></pre>
",https://stackoverflow.com/questions/59283121/unit-testing-for-google-cloud-functions,"['google-cloud-platform', 'google-cloud-functions', 'mocha.js', 'chai', 'sinon']",2004,True,0,3
Unit testing a method with no return value,"<p>What would be an elegant a way of unit testing a method like this ?</p>

<pre><code>from feedgen.feed import FeedGenerator

def generate_feed(file_list):
    fg = FeedGenerator()
    for f in file_list:
        fe = fg.add_entry()
    fg.rss_str(pretty=True)
    fg.rss_file('podcast.xml')
</code></pre>

<p>Obviously the method doesn't return any value, but writes an xml file instead . Is there an elegant way of unit testing this ? Or should I look into refactoring my method to make it more unit testing friendly and assert against something ?</p>
",https://stackoverflow.com/questions/58809028/unit-testing-a-method-with-no-return-value,"['python', 'unit-testing']",57,True,1,3
Laravel 6 Unit Testing Responses 401,"<p>I am using Token based operations. The request for the Edit operation in Project works well in Postman. </p>

<pre><code>public function update(Request $request, $id)
    {
        $project = Project::find($id);
        $project-&gt;project_name = request('project_name');
        $project-&gt;project_description = request('project_description');
        $project-&gt;save();
        return response()-&gt;json([
            'message' =&gt;  ""Project Updated Successfully"",
            'updatedId' =&gt; $project-&gt;id
            ], 200);
    }
</code></pre>

<p>But in Unit Testing Not getting Proper Responses</p>

<pre><code> public function testBasicExample()
    {
        $response = $this-&gt;withHeaders([
            'Accept' =&gt; 'application/json',
            'Authorization' =&gt; 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi......'
        ])-&gt;json('POST', '/api/updateProject/1',
                ['project_name' =&gt; 'Sally'],
                ['project_description' =&gt; 'testing the api']
                );

                $response-&gt;assertStatus(200);
                $response-&gt;assertJson(['status' =&gt; true]);
    }
</code></pre>

<p>Error Shows </p>

<pre><code>PS D:\XMAPP\htdocs\minidmsapi&gt; ./vendor/bin/phpunit
PHPUnit 8.4.1 by Sebastian Bergmann and contributors.

..F.                                                                4 / 4 (100%)

Time: 516 ms, Memory: 18.00 MB

There was 1 failure:

1) Modules\Projects\Tests\Unit\ProjectTest::testupdate
Expected status code 200 but received 401.
Failed asserting that false is true.

D:\XMAPP\htdocs\minidmsapi\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestResponse.php:166
D:\XMAPP\htdocs\minidmsapi\Modules\Projects\Tests\Unit\ProjectTest.php:35

FAILURES!
Tests: 4, Assertions: 4, Failures: 1.
</code></pre>

<p>Why Unit Testing having Error Response 401 ?</p>

<p>Kindly anyone, please explain to me What is the actual error in unit testing and solution for that.</p>
",https://stackoverflow.com/questions/58447741/laravel-6-unit-testing-responses-401,"['api', 'unit-testing', 'testing', 'laravel-6']",1051,False,0,1
How to reduce the unit testing running time?,"<p>I'm using Eclipse and doing java code unit testing, but my unit testing running time taking a long time. Is there is any way to reduce the unit testing running time????</p>

<p>My project based on AWS S3 buckets and java. I am using java 8 and junit5 and i did the function move, copy, delete the single file and multiple files transaction functions. So I was checked that functions were correctly worked or not using junit5. but my unit testing taking a long times.</p>
",https://stackoverflow.com/questions/58534816/how-to-reduce-the-unit-testing-running-time,"['java', 'eclipse', 'unit-testing', 'junit5']",208,False,0,0
How to perform unit testing on void function with coverage,"<p>I am new to unit testing. <br/>
I am trying to perform unit testing on the below code<br/></p>

<pre><code>public void send(Map&lt;String, List&lt;Integer&gt;&gt; mapOf){

     mapOf.forEach((k ,v) -&gt; {
         v.stream().forEach(o -&gt;{
             myList.add(o)
             message.push(o);
         });
     });
    }
</code></pre>

<p><br/></p>

<pre><code>message.push(o), pushes data to the database. &lt;br/&gt;
</code></pre>

<p><br/>
How can I Unit test this method?</p>
",https://stackoverflow.com/questions/54613838/how-to-perform-unit-testing-on-void-function-with-coverage,"['java', 'unit-testing', 'mockito']",118,True,0,1
How to do unit testing retrofit api calls with viewmodel + livedata?,"<p>I just learned about Android unit testing. I want to implement a unit testing API retrofit call with viewmodel + livedata to my exercise project.
This is one of the viewmodel class.</p>

<pre><code>class NextMatchViewModel(league : League, application: Application): AndroidViewModel(application) {

// get idLeague passing for call getNextMatch()
private val _idLeague = MutableLiveData&lt;League&gt;()
private val idLeague: LiveData&lt;League&gt;
    get() = _idLeague

// next match liveData
private val _nextMatch = MutableLiveData&lt;List&lt;Match&gt;&gt;()
val nextMatch: LiveData&lt;List&lt;Match&gt;&gt;
    get() = _nextMatch

init {
    //get _idLeague value from argument(SafeArgs)
    _idLeague.value = league

    getNextMatch()
}

private fun getNextMatch() {

    idLeague.value?.idLeague?.let {
        LeagueApi.retrofitService.getNextMatch(it).enqueue(object : Callback&lt;MatchResponse&gt;{
            override fun onFailure(call: Call&lt;MatchResponse&gt;, t: Throwable) {
                Log.d(TAG, t.message!!)
            }

            override fun onResponse(call: Call&lt;MatchResponse&gt;, response: Response&lt;MatchResponse&gt;) {
                _nextMatch.value = response.body()?.events
                Log.d(TAG, ""success"")
            }

        })
    }
}

companion object {
    private val TAG = NextMatchViewModel::class.java.simpleName
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/59172360/how-to-do-unit-testing-retrofit-api-calls-with-viewmodel-livedata,"['android', 'unit-testing']",2272,False,1,2
How to override the H2 with embedded postgreSQl lib in unit testing?,"<p>In unit testing for Corda, it runs a H2 DB. Given that I run a postgreSQL in production, I would like to run using PostgreSQL during unit testing to close this gap (rather than leave it to integrating testing) as well. There are embedded postgreSQL lib to ""mock"" postgreSQL"". </p>

<p>How can i override the default H2 DB in Corda to run a embedded postgreSQL instead during unit testing?</p>
",https://stackoverflow.com/questions/57917481/how-to-override-the-h2-with-embedded-postgresql-lib-in-unit-testing,['corda'],110,True,1,1
Can I use C# for doing unit testing on VB code?,"<p>I've done a little bit of Unit Testing using JUnit with a Java program, and I am new to the .NET unit testing space. I'm sure it can't be so different, though.</p>

<p>At work, we have a legacy VB .NET codebase, with zero unit testing going on. I want to start adding some unit testing to this thing, and I see the option in Visual Studio to use C# for unit testing. </p>

<p>My question is, am I even able to use C# for testing the VB code? I would definitely want to use this as an opportunity to work with C# instead of more VB. I can't find this question anywhere else online, interestingly enough, and would love some insight. It seems like I'm asking a dumb question, but I hope to get an answer that would help me understand this, especially as to why it's a dumb question, if it is.</p>
",https://stackoverflow.com/questions/55498754/can-i-use-c-for-doing-unit-testing-on-vb-code,"['c#', '.net', 'vb.net', 'unit-testing']",822,True,4,1
How to fix @testable import failed to load module in xcode unit testing,"<p>I had created an Xcode project without unit testing. I have added cocoa pods when I try to create a new unit testing and try to import @testable import 'ProjectName' it gives an error  Failed to load module 'ProjectName'. can u please help me out to solve the problem</p>

<p>@testable import 'ProjectName' Failed to load module</p>
",https://stackoverflow.com/questions/56163189/how-to-fix-testable-import-failed-to-load-module-in-xcode-unit-testing,"['xcode', 'unit-testing', 'cocoapods']",5829,True,13,3
Unit Testing for IBM MFP 8 - Javascript Adapters,"<p>Is there any possibility to write Unit Testing on MFP 8 Javascript adapters using Jasmine/Karma/JUnit ?</p>

<p>I heard that Unit testing can be done for IBM MFP 8 - JAVA adapters</p>

<p>Is it possible ?</p>
",https://stackoverflow.com/questions/57474478/unit-testing-for-ibm-mfp-8-javascript-adapters,['ibm-mobilefirst'],66,False,1,0
Visual studio unit test for .NET framework 4.0,"<p>I am currently using visual studio 2019. I have an c# windows form application that runs on .NET framework 4.0 and I would like to use MS unit testing framework to carry out the unit testing for my software. However, the [TestClass] and [TestMethod] attribute does not seem to be available for .NET framework 4.0. </p>

<p>Below shows the current error that I am facing. Would it be possible to carry out unit testing for .NET framework 4.0 ?</p>

<p><a href=""https://i.stack.imgur.com/gEp1d.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gEp1d.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/56830632/visual-studio-unit-test-for-net-framework-4-0,"['.net', 'visual-studio', 'unit-testing']",1175,False,2,1
XUnit Testing using Autofac.Extras.Moq,"<p>I'm new in unit testing, Below is code for unit testing using xunit</p>

<pre><code>public class FloorManager
{
    public List&lt;FloorInfo&gt; Floors { get; }

    public FloorManager()
    {
        Floors = new List&lt;FloorInfo&gt;();
        SelectedFloor = -1;
    }        

    public FloorInfo FindFloorByName(string name)
    {
        FloorInfo fInfo = Floors.Find(floor =&gt; floor.Name == name);
        return fInfo;
    }
}

public class FloorInfo
{
    public String Name { get; set; }
}
</code></pre>

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

<pre><code>[Fact]
public void FindFloorByName_ShouldGetName()
{
    using (var mock = AutoMock.GetLoose())
    {
        string floorName = ""First Floor"";
        var fInfo = new FloorInfo { Name = floorName };
        mock.Mock&lt;FloorManager&gt;()
            .Setup(x =&gt; x.FindFloorByName(floorName)).Returns(fInfo);

        var cls = mock.Create&lt;FloorManager&gt;();
        var expected = ""First Floor"";

        var actual = cls.FindFloorByName(floorName);

        Assert.True(expected == actual.Name);
    }
}
</code></pre>

<p>but when i run test it gives me error :- </p>

<pre><code>&gt; `System.NotSupportedException : Unsupported expression: x =&gt; x.FindFloorByName(FloorManagerTests.&lt;&gt;c__DisplayClass0_0.floorName)`
</code></pre>

<p>Please give me solution how to test above function to pass test case</p>
",https://stackoverflow.com/questions/58303938/xunit-testing-using-autofac-extras-moq,"['c#', 'unit-testing', 'xunit', 'xunit.net', 'xunit2']",340,False,0,1
FileManager.containerURL(forSecurityApplicationGroupIdentifier) returning nil in unit testing,"<p>During unit testing the following function returns nil meaning my group id is invalid. <code>fileManager.containerURL(forSecurityApplicationGroupIdentifier:""group.myGroupId"")</code>However if I run the same code on a sim or a device it works perfectly.</p>

<p>What am I missing in order to use app groups during unit testing?</p>
",https://stackoverflow.com/questions/57656644/filemanager-containerurlforsecurityapplicationgroupidentifier-returning-nil-in,"['swift', 'ios-app-group']",263,False,1,0
How to trigger a click outside event?,"<p>I'm writing unit testing and e2e testing for a popover component in React.
I should check if the popup is hidden when I click outside the component.
I'm using Jest + Enzyme for unit testing and Cypress for e2e testing.
Does anybody know how to do this?</p>

<p>I've tried as follows in cypress.</p>

<pre><code>cy.get('[data-test-id=""popover-container""]').click(-20, -20, {force: true});
</code></pre>

<p>But the clicked point is actually outside of the popup window, but it doesn't work.
<code>react-tiny-popover</code> library is used to show the popover as follows:</p>

<pre><code>&lt;Popover
      content={({ position, targetRect, popoverRect }) =&gt; (
        &lt;ArrowContainer
          position={position}
          targetRect={targetRect}
          popoverRect={popoverRect}
          arrowColor={'#ccc'}
          arrowSize={10}
        &gt;
          &lt;div data-test-id=""popover-container""&gt;
            &lt;Content/&gt;
          &lt;/div&gt;
        &lt;/ArrowContainer&gt;
      )}
      isOpen={visible}
      onClickOutside={() =&gt; hideOnOutsideClick &amp;&amp; setVisible(false)}
      position={position}
    &gt;
      &lt;div onClick={() =&gt; setVisible(!visible)}&gt;{children}&lt;/div&gt;
    &lt;/Popover&gt;
</code></pre>
",https://stackoverflow.com/questions/58593525/how-to-trigger-a-click-outside-event,"['javascript', 'click', 'mouseevent', 'cypress']",19547,True,19,2
Unit testing .net project by Asserting Status Code returning,"<p>I am new to unit testing and <code>xunit</code>. I am writing unit tests that assert status codes returning. Is this something in the scope of Integration test or is it meeting unit testing logic?</p>

<p>For example I am asserting a get function's response like this: </p>

<pre class=""lang-cs prettyprint-override""><code>[Fact]
public async Task MyTest()
{
    SearchParam searchParam = new SearchParam() { };
    var bool= false;
    var bool2 = false;
    var actionResult = await _controller.Myfunction(searchParam, bool, bool2).ConfigureAwait(false);
    var okResult = actionResult.Result as OkObjectResult;
    Assert.True(okResult.StatusCode == 200, ""Ok"");
}
</code></pre>
",https://stackoverflow.com/questions/58435144/unit-testing-net-project-by-asserting-status-code-returning,"['c#', '.net', 'unit-testing', 'xunit.net']",406,True,1,1
Unit Testing a method containing Environment.Exit() call within it,"<p>I have a public method say, </p>

<pre><code>public void ErrorEncounter()
{
//Global Error Counter
gblErrorCount++;

//Process tremination
Environment.Exit();
}
</code></pre>

<p>This method terminates whenever it is called. However, it will update the <strong>Global Error Count</strong> which i'm suppose to test. Is there any way to perform Unit Testing on this method?</p>

<p>I'm Using <strong>NUnit</strong> Framework for Unit Testing.</p>
",https://stackoverflow.com/questions/55467019/unit-testing-a-method-containing-environment-exit-call-within-it,"['c#', 'unit-testing', 'nunit']",1618,True,1,2
Issue in dependency injection while implementing Unit testing in ASP.NET MVC 6,"<p>My unit testing code is </p>

<pre><code>[TestClass]
public class ProjectControllerTest
{
    Mock&lt;IProjectService&gt; addressRepositoryMock = new Mock&lt;IProjectService&gt;();
    ProjectController controller;

    [TestInitialize]
    public void TestInit()
    {
        controller = new ProjectController(addressRepositoryMock.Object);
    }

    [TestMethod]
    public void TestMethod1()
    {
        var response = controller.GetOverrides(1) as HttpResponseMessage;
    }
}
</code></pre>

<p>My controller code is:</p>

<pre><code>[Route(""GetOverrides"")]
[HttpGet]
public HttpResponseMessage GetOverrides(int Project_Id)
{
        List&lt;OverridesDto&gt; overrides = new List&lt;OverridesDto&gt;();

        try
        {
            overrides = projectService.GetOverrides(Project_Id);
        }
        catch (Exception ex)
        {
            Log.Logger.Error(ex, ""Exception:{Ex}"", null);
            ThrowHttpExceptionOnError(ex.ToString());
        }

        return Request.CreateResponse(HttpStatusCode.OK, overrides);
 }
</code></pre>

<p>I am able to hit method <code>GetOverrides</code> in controller from  unit testing project in debug mode but the problem is I can not hit BAL method <code>projectService.GetOverrides(Project_Id);</code> which is returning null</p>

<p>Please help me out with the above issue.</p>
",https://stackoverflow.com/questions/58760962/issue-in-dependency-injection-while-implementing-unit-testing-in-asp-net-mvc-6,"['c#', 'asp.net-mvc', 'testing']",41,False,0,0
Mock API in Unit Tesing on Nativescript Core,"<p>I'm implementing unit testing in my mobile app project with nativescript core. I want to mock api in unit testing but I can't do it, So this is my code</p>

<pre><code>// model that I want to test
const myfunction = async (): Promise&lt;myInterface&gt; =&gt; {
  const response = await fetch(""myURL"", {
    method: ""GET"",
    headers: { ""Content-Type"": ""application/json"" }
  });
  const { status, data }: { status: string, data?: any } = await response.json();
  if (!status || status !== ""ok"") {
    throw new Error(""failed fetching from host, status:"" + status);
  }

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

<pre><code>// my unit testing

import * as dataModel from ""../../../shared/models/data"";

describe('data', () =&gt; {
  describe('myfunction', () =&gt; {
    it('get data from api', async () =&gt; {
      try {
        // I want to mock api in this place
        const response = await dataModel.myfunction();
      } catch(err) { console.log(err); }
    });
  });
});
</code></pre>

<p>Does it have some plugin or something that can mock api from fetch with this mobile app nativescript core?</p>
",https://stackoverflow.com/questions/58334292/mock-api-in-unit-tesing-on-nativescript-core,"['api', 'unit-testing', 'mobile', 'mocking', 'nativescript']",121,False,0,0
how to test methods which set private variables in viewcontroller unit testing?,"<p>I have a ViewController, which conforms to a protocol. ViewController has the following private UI components:
backgroundImage, logoimage,  loginButton , signupButton - all of these are private. (hence not accessible by unit tests)</p>

<p>How can I test the below protocol method implementation in unit testing? I am using <code>XCTestFramework</code> for unit testing.</p>

<pre><code>extension ViewController : ViewControllerProtocol{
    func setbackgroundImage(_ image: UIImage) {
        backgroundImage.image = image
    }

    func setLogoImage(_ image: UIImage) {
        logoImage.image = image
    }

    func setLoginButtontitle(_ title: String) {
        loginButton.setTitle(title, for: .normal)
    }

    func setSignupButtonTitle(_ title: String) {
        signupButton.setTitle(title, for: .normal)
    }
}

protocol ViewControllerProtocol {
    func setbackgroundImage(_ image : UIImage)
    func setLogoImage(_ image : UIImage)
    func setLoginButtontitle(_ title: String)
    func setSignupButtonTitle(_ title: String)
    func setTitleLabel(_ title: String)
    func setContinuewithoutsignupTitle(_ title: String)
}

</code></pre>
",https://stackoverflow.com/questions/59310593/how-to-test-methods-which-set-private-variables-in-viewcontroller-unit-testing,"['ios', 'swift', 'tdd']",95,True,0,1
Testing practice an API wrapper without using unittest module,"<p>i have wrote an api wrapper which has around 70 endpoints. To test them all </p>

<p><a href=""https://paste.ubuntu.com/p/V6mkK4dSdh/"" rel=""nofollow noreferrer"">https://paste.ubuntu.com/p/V6mkK4dSdh/</a> 
i have wrote this script without actually usign the unit testing module. Is it a good practice and what are the downsides when compared with unit testing? Really could use some comments. </p>
",https://stackoverflow.com/questions/55772238/testing-practice-an-api-wrapper-without-using-unittest-module,"['python', 'unit-testing']",90,False,-2,1
Unit Testing with Firebase (Swift),"<p>Trying to do some simple unit testing with Firebase, but for some reason Firestore won't initialize:</p>

<p>ModelTests.swift:</p>

<pre><code>func testFirebase() throws
{
    // THIS IS ALWAYS ""UNINITIALIZED""
    let db = Firestore.firestore()

    // Because db isn't initialized correctly, this ref will always be nil.
    let ref: DocumentReference? = db.document(""unit_testing/xxx"")
    ref?.setData([
        ""id"" : ""someID"",
        ""name"" : ""goldenjoe"",
        ""another"" : ""bmus"",
        ""testDate"" : Date()
        ],
                 merge: true,
                 completion: { err in
                    if let err = err {
                        print(""Error adding document: \(err)"")
                    } else {
                        print(""Document added with ID: \(ref!.documentID)"")
                    }
                }
        )
}
</code></pre>

<p>AppDelegate.swift:</p>

<pre><code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool 
{
    // Set up Firestore
    FirebaseApp.configure()
}
</code></pre>

<p>Podfile:</p>

<pre><code>platform :ios, '11.0'

target 'MyWork' do
use_frameworks!

# ignore all warnings from all pods
inhibit_all_warnings!

# Pods for MyWork
pod 'CoreXLSX'
pod 'Eureka'
pod 'Firebase/Firestore'
pod 'Firebase/Auth'
pod 'ProgressHUD'
#pod 'GoogleSignIn'
pod 'SteviaLayout'

target 'MyWorkTests' do
  inherit! :complete
  end

end
</code></pre>

<p>However, when I run the app normally, I can use Firebase just fine in other parts of the app. Can't find anything online about a special configuration being needed for unit testing.</p>
",https://stackoverflow.com/questions/57837137/unit-testing-with-firebase-swift,"['ios', 'swift', 'xcode', 'firebase', 'cocoapods']",372,False,0,1
"How do we do junit for java8 Function,Predicate,Bifunction","<p>I am trying to migrate my application to java 8 from java 7 and trying to make use of the conciseness provided by using java 8 lambdas. but unit testing became a nightmare for me as I cannot refer Function/Predicate from testing class. I have below questions:</p>

<p>My previous code:<br/></p>

<pre><code>public String myMethod(int v1){
     //Some logic
}
</code></pre>

<p>Usign java8:<br/></p>

<pre><code>Fucntion&lt;Integer,String&gt; myMethod = (i) -&gt; {
    //Same some logic
};
</code></pre>

<p>So Unit testing became a night are for me in th above case. I am using Junit,Mockito for unit testing.</p>

<p>TestClass:</p>

<pre><code>@RunWith(JunitMockitoRunner.class)
public class TestClass{
    @InjectMock
    Testclass mock;

// want to test my method which i am trying to write using Fucntion&lt;I,O&gt;

}
</code></pre>

<p>Also will the performace be better if i go with java7 way having a method instead of lambda or fucntional Interface?</p>

<p>Thanks In Advance!</p>
",https://stackoverflow.com/questions/55895563/how-do-we-do-junit-for-java8-function-predicate-bifunction,"['lambda', 'junit', 'java-8', 'stream', 'mockito']",2494,False,0,1
Iceberg Class and Google Unit Testing,"<p>I am going through the process of doing unit testing of a existing code which is written not with unit testing in mind.</p>

<p>There is a few class structured like something like this:</p>

<pre><code>class Texture
{
public:
    friend class Model;
private:
 void Load( int a, int b);
 void Update(int a, int b);
 void Use(int a, int b);    
}

class Material
{
public:
    friend class Model;
private:
 void Load(int a);
 void Update(int a);
 void Use(int a);    
}

class Mesh
{
public:
    friend class Model;
private:
 void Load(int a, int b, int c);
 void Update(int a, int b, int c);
 void Use(int a, int b, int c);    
}


class Model
{
    public:

    void Load(); // call all the individual Load()
    void Use(); // call all the individual Use()
}
</code></pre>

<p>The reason why they are kept as private is because it is design in such a way where only Model class can call them, hence the friend. </p>

<p>[<em>In the actual code there is a Attorney-Client idiom which limit the access of Model to these class, but I leave it out of the code snippet</em>]</p>

<p>Now I am trying to do unit testing for the classes. While figuring out how to test these private functions, I came across this terminology of an <a href=""https://www.artima.com/weblogs/viewpost.jsp?thread=125574"" rel=""nofollow noreferrer"">Iceberg Class</a> which I feel the above class is in a way guilty of. </p>

<p>Most article touching on this topic also mentioned that if there is a need to test a private function, it mostly means that class is overdoing and these functions are better off in another standalone class where they stay as public.</p>

<p>So right now, I am not sure if this is a bad code design and I should redesign them to make unit testing easier, or those I just proceed with unit testing as it is.</p>

<p>Would like to hear your opinions</p>
",https://stackoverflow.com/questions/56536150/iceberg-class-and-google-unit-testing,"['c++', 'unit-testing', 'googletest', 'friend']",425,True,2,2
cannot setup jest with typescript,"<p>I'm following this example to set up some basic unit testing for a typescript project: <a href=""https://dev.to/muhajirdev/unit-testing-with-typescript-and-jest-2gln"" rel=""noreferrer"">https://dev.to/muhajirdev/unit-testing-with-typescript-and-jest-2gln</a></p>

<p>I have a <code>main.ts</code> exporting a <code>isInternalLink</code> function</p>

<p>and a <code>main.spec.ts</code> that tries to test it</p>

<p>but I get the following error:</p>

<pre><code>C:\data\devel\apps\tmp\jest-typescript\src\main.spec.ts:1
({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){import { isInternalLink } from './main.js';
SyntaxError: Unexpected token {
  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
</code></pre>

<p>This is the public repo with the complete example: <a href=""https://gitlab.com/opensas/jest-typescript"" rel=""noreferrer"">https://gitlab.com/opensas/jest-typescript</a></p>

<p>Can anybody point me in the right direction, or provide a working example?</p>
",https://stackoverflow.com/questions/57839008/cannot-setup-jest-with-typescript,"['typescript', 'jestjs', 'ts-jest']",8359,True,7,3
Can&#39;t figure out why I&#39;m getting java.lang.ArithmeticException: / by zero,"<p>I am trying to create a java program that would take an input amount and output the change with fewest coins. Although when I run my program I get the desired output, I get a unit testing error for the method Change. Here is my code:</p>

<pre><code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int totalamount;
        int[] coins = new int[] { 100, 25, 10, 5, 1 };
        Scanner s = new Scanner(System.in);
        totalamount = s.nextInt();
        Change(totalamount, coins);
    }

    public static void Change(int totalamount, int[] coins) {
        int[] amount = new int[5]; 

        for (int i = 0; i &lt; 5; i++) { 
            if (totalamount &gt;= coins[i]) { 
                amount[i] = totalamount / coins[i]; 
                totalamount = totalamount % coins[i]; 
            } 
        }

        for (int i = 0; i &lt; 5; i++) { 
            if(amount[i] != 0)
            System.out.println(amount[i]);
        } 
    }
}
</code></pre>

<p>and this is the unit testing error I get: </p>

<pre><code>Change(300, coins)
Your output
java.lang.ArithmeticException: / by zero
</code></pre>
",https://stackoverflow.com/questions/56055374/cant-figure-out-why-im-getting-java-lang-arithmeticexception-by-zero,"['java', 'arrays', 'methods']",75,True,-2,1
Get Error Argument(s) are different! Wanted with Mockito Test,"<p>I've got some problems with my unit testing. I want to do some unit testing with my code, but I found an error like this. I've looked for a solution on stack overflow, but haven't gotten the solution. </p>

<pre><code>view.setDetailLeague(
    []
);
-&gt; at com.example.submission3kotlin.TestAnother.getAnotherTest(TestAnother.kt:44)
Actual invocations have different arguments:
view.setDetailLeague(
    [League(dateFirstEvent=2000-08-18, idCup=0, idLeague=4328, idSoccerXML=1, intFormedYear=1992, strBadge=https://www.thesportsdb.com/images/media/league/badge/i6o0kh1549879062.png, strBanner=https://www.thesportsdb.com/images/media/league/banner/4m3g4s1520767740.jpg, strComplete=yes, strCountry=England, strDescriptionCN=英格兰足球超级联赛（英语：Premier League），简称英超，過往冠名為巴克萊超級聯賽（Barclays Premier League）]
);
</code></pre>

<p>and this is my presenter</p>

<pre><code>class DetailLeaguePresenter(val view: DetailLeagueContract.View, private val scheduler: SchedulerProvider): DetailLeagueContract.Presenter {
    override fun getDetailLeague(id: String) {
        val retrofit = RetrofitClient.getClient()
            .create(UserService::class.java)
        CompositeDisposable().add(
            retrofit.responseDetailLeague(id)
                .observeOn(scheduler.ui())
                .subscribeOn(scheduler.io())
                .subscribe(
                    {
                        view.setDetailLeague(it.leagues)
                    }, { error -&gt; Log.e(""Error"", error.message) }
                )
        )
    }
}
</code></pre>

<p>My test code with mockito :</p>

<pre><code>class TestAnother {
    @Mock
    lateinit var view: DetailLeagueContract.View

    @Mock
    private val retrofitClient = RetrofitClient.getClient().create(UserService::class.java)

    @Mock
    lateinit var scheduler: SchedulerProvider

    private lateinit var mPresenter: DetailLeaguePresenter

    @Before
    fun setupEnv(){
        MockitoAnnotations.initMocks(this)
        scheduler = TestSchedulerProvider()
        mPresenter = DetailLeaguePresenter(view, scheduler)
    }

    @Test
    fun getAnotherTest(){
        val data: MutableList&lt;League&gt; = mutableListOf()
        val response = DetailLeague(data)
        val id = ""4328""
        `when`(retrofitClient.responseDetailLeague(id)).thenReturn(Observable.just(response))

        mPresenter.getDetailLeague(id)
        verify(view).setDetailLeague(response.leagues)
    }
}
</code></pre>

<p>can anyone help me? Thank you in advance</p>
",https://stackoverflow.com/questions/59517085/get-error-arguments-are-different-wanted-with-mockito-test,"['android', 'unit-testing', 'mockito']",189,False,1,0
How do you mock an IAsyncEnumerable?,"<p>I want to unit test a method that calls another method of a service returning an <code>IAsyncEnumerable&lt;T&gt;</code>.
I have created a a mock of my service <code>Mock&lt;MyService&gt;</code> and I want to setUp this mock but I don't know how to do that. Is it possible ? Are there other ways of unit testing a method that calls something retuning an <code>IAsyncEnumerable</code> </p>

<pre class=""lang-cs prettyprint-override""><code>public async Task&lt;List&lt;String&gt;&gt; MyMethodIWantToTest()
{
  var results = new List&lt;string&gt;();
  await foreach(var item in _myService.CallSomethingReturningAsyncStream())
  {
    results.Add(item);
  }
  return results;
}
</code></pre>
",https://stackoverflow.com/questions/59071994/how-do-you-mock-an-iasyncenumerable,"['c#', 'unit-testing', 'asp.net-core', 'iasyncenumerable']",20965,True,47,4
Where should unit tests live in an angularJS application?,"<p>I'm trying to stick to the pure angular recommendations for unit testing:</p>

<p><a href=""https://docs.angularjs.org/guide/unit-testing"" rel=""nofollow noreferrer"">https://docs.angularjs.org/guide/unit-testing</a></p>

<p>But it really doesn't tell me where they should live. My guess would be inside an angular service, probably segregated by page or in the same file as the base controller, sort of a base testing factory or service.</p>
",https://stackoverflow.com/questions/55024311/where-should-unit-tests-live-in-an-angularjs-application,"['angularjs', 'unit-testing']",32,True,0,1
Unit Test Missing Branch Coverage in Java,"<p>I have been trying to get my head around unit testing <code>equals</code> method in java to cover all branches. There is one branch missing. I tried to look up couple of <a href=""https://www.guru99.com/junit-assert.html"" rel=""nofollow noreferrer"">resources</a>, but was not very helpful. Here is my code which I am trying to unit test it.</p>

<pre><code>public boolean isValid(Item item) {

    return !StringUtils.isEmpty(item.getCat()) &amp;&amp;        //both branches covered
            !StringUtils.isEmpty(item.getDog()) &amp;&amp;   //both branches covered
            !StringUtils.isEmpty(item.getDogCat()) &amp;&amp;       //both branches covered
            (String.format(""%s|%s"", item.getDog(), item.getCat())  //here one branch missing
                    .equals(item.getDogCat());
}
</code></pre>

<p>Unit Test:</p>

<pre><code>    boolean expectedValue = false;

    private static final Item ITEM_4 = 
      Item.builder()
            .dogCat(""bow|meow"")
            .dog(""bow"")
            .cat(""meow"")
            .build();


    @Test
    public void testIsValidWhenCatIsNull() {
        boolean actualValue = itemValidator.isValid(ITEM_1);
        Assert.assertEquals(expectedValue, actualValue);
    }

    @Test
    public void testIsValidWhenDogIsNull() {
        boolean actualValue = itemValidator.isValid(ITEM_2);
        Assert.assertEquals(expectedValue, actualValue);
    }

    @Test
    public void testIsValidWhenDogCatIsNull() {
        boolean actualValue = itemValidator.isValid(ITEM_3);
        Assert.assertEquals(expectedValue, actualValue);
    }

    @Test
    public void testIfDogCatMatchesConcatenatedDogCat() {
        itemValidator.isValid(ITEM_4);
        Assert.assertEquals(String.format(""%s|%s"" ,""bow"", ""meow""), (""bow|meow""));
    }

    @Test
    public void testIfDogCatDoesNotMatchesConcatenatedDogCat() {
        itemValidator.isValid(ITEM_4);
        Assert.assertNotEquals(String.format(""%s|%s"", ""bow"", ""meow""), (""bow|whoop""));
}
</code></pre>

<p>Unit testing world is quite new to me, any help is appreciated.</p>
",https://stackoverflow.com/questions/55528967/unit-test-missing-branch-coverage-in-java,"['java', 'unit-testing', 'testing', 'junit', 'mockito']",1673,True,1,1
Flutter: Test that a specific exception is thrown,"<p>in short, <code>throwsA(anything)</code> does not suffice for me while unit testing in dart. How to I test for a <strong>specific error message or type</strong>?</p>

<p>Here is the error I would like to catch:</p>

<pre><code>class MyCustErr implements Exception {
  String term;

  String errMsg() =&gt; 'You have already added a container with the id 
  $term. Duplicates are not allowed';

  MyCustErr({this.term});
}
</code></pre>

<p>here is the current assertion that passes, but would like to check for the error type above:</p>

<p><code>expect(() =&gt; operations.lookupOrderDetails(), throwsA(anything));</code></p>

<p>This is what I want to do:</p>

<p><code>expect(() =&gt; operations.lookupOrderDetails(), throwsA(MyCustErr));</code></p>
",https://stackoverflow.com/questions/54241396/flutter-test-that-a-specific-exception-is-thrown,"['dart', 'flutter', 'flutter-test']",31988,True,45,6
Error in unit testing (karma). There is no directive with &quot;exportAs&quot; set to &quot;ngbPopover&quot;,"<p>Am using the below ngbPopover in my angular page and while writing Unit testing for it. It throws me an compile error. Like below</p>

<p>There is no directive with ""exportAs"" set to ""ngbPopover""
                      (click)=""p1.open()"" [ERROR ->]#p1=""ngbPopover""></p>

<pre><code>    &lt;span placement=""bottom""  [ngbPopover]=""popContent""  triggers=""manual""
          (click)=""p1.open()"" #p1=""ngbPopover""&gt;
    &lt;/span&gt;




    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NotificationsService as ToasterService } from 'angular2-notifications';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { testComponent } from './test.component';

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [testComponent],
      imports: [ FormsModule, ReactiveFormsModule  ],
    }).compileComponents();
  }));

  beforeEach(() =&gt; {
    const toasterServiceStub = {
      create: () =&gt; ({})
    };
    TestBed.configureTestingModule({
      declarations: [testComponent],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        { provide: ToasterService, useValue: toasterServiceStub }
      ]
    });
    fixture = TestBed.createComponent(testComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    fixture = TestBed.createComponent(testComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>If I remove that #p1 from html, my unit testing gets compiled. But not sure why that causes an error. Please help me out</p>
",https://stackoverflow.com/questions/58874033/error-in-unit-testing-karma-there-is-no-directive-with-exportas-set-to-ngb,"['angular', 'unit-testing', 'karma-jasmine']",1070,True,1,1
How to code coverage a promise inside functions while unit testing using Jest,"<p>How to code cover then and catch function of a promise inside a function while unit testing using jest? Please see code below.</p>

<p>Service.js</p>

<pre><code>export const userLogin = data =&gt; {
  return AjaxService.post(
    ""http://localhost/3000/signin"", data
  ).then(
    res =&gt; {
      return res.data;
    },
    error =&gt; {
      return error.response.data;
    }
  );
};
</code></pre>

<p>AjaxService.js</p>

<pre><code>export const AjaxService = {
  post: (url, data, headers) =&gt; {
    return axios({
      method: ""POST"",
      url: url,
      headers: headers || { ""content-type"": ""application/json"" },
      data: data
    });
  }
</code></pre>

<p>}</p>

<p>Example.js</p>

<pre><code>class Login extends Component {

  handleSubmit = (event) =&gt; {
    if (this.props.handleSubmit) this.props.handleSubmit(); 
    this.setState({isLoggedIn: true})
    userLogin().then((res) =&gt; {
     // when promise resolve
     var response = res;
    }, (err) =&gt; {
      // when promise reject  
      var error = err;
    })
  }
  render() {
   return (
    &lt;form id=""login-form"" onSubmit={(e) =&gt; this.handleSubmit(e)} &gt;
     &lt;input type=""username"" /&gt;
     &lt;input type=""password"" /&gt;
     &lt;button type=""submit""&gt;Login&lt;/button&gt;
    &lt;/form&gt;
   )
  }

}
</code></pre>

<p>Example.test.js</p>

<pre><code>it(""test login form submit "", () =&gt; {
    wrapper = shallow(&lt;Login /&gt;);
    let instance = wrapper.instance(); // get class instance
    instance.handleSubmit(); // will trigger component method
    let actualVal = wrapper.state().isLoggedIn; // get state key value
    expect(true).to.eql(actualVal);
  });
</code></pre>

<p>After generating coverage report using <code>--coverage</code> in Jest</p>

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

<p>We can see that the code inside promise success and error function doesn't get covered as part of unit testing. So please help cover this. Thanks.</p>
",https://stackoverflow.com/questions/58110463/how-to-code-coverage-a-promise-inside-functions-while-unit-testing-using-jest,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'code-coverage']",2451,True,1,2
How to set -noverify option with gradle ktx for android robolectric tests?,"<p>I am using Roboelectric for unit testing an android app, and bumped into an error while trying to write to <code>SecureStorage</code> - <code>java.lang.VerifyError: Expecting a stackmap frame at branch target 10</code></p>

<p>I don't need verification enabled for unit tests, so would want to disable it, but using gradle ktx and don't know the right way to set jvm flags there for the unit testing task.</p>

<p>Thing I tried and doesn't work:</p>

<pre><code>tasks.withType&lt;Test&gt; {
    jvmArgs?.add(""-noverify"")
}

</code></pre>
",https://stackoverflow.com/questions/59470532/how-to-set-noverify-option-with-gradle-ktx-for-android-robolectric-tests,"['android', 'gradle', 'robolectric', 'android-ktx']",458,True,1,1
Is it still &quot;unit testing&quot; if you&#39;re using React Testing Library / Enzyme&#39;s mount function?,"<p>We're currently unit testing our React application with Enzyme's shallow render function. Every component is tested in isolation so I understand why this is called ""unit testing"". </p>

<p>We're moving towards rendering the component and it's children. You can do this with Enzyme's mount function or with React Testing Library as it never shallow renders. This also means we have to mock Redux if it's a connected component. </p>

<p>What is the name for this type of testing? I've heard it called ""integration testing"", but when I say this at work people think that I mean something else. Is it still a type of ""unit testing"" despite the fact that multiple components are tested together? </p>
",https://stackoverflow.com/questions/57091857/is-it-still-unit-testing-if-youre-using-react-testing-library-enzymes-moun,"['reactjs', 'testing']",1416,True,2,2
Calling relative paths from test file: &quot;Attempted Relative import beyond toplevel package&quot;,"<p>I'm trying to perform unit testing from the given file structure</p>

<pre><code>/logs_cleanup
---/cleanup_logs.py &lt;&lt; target
/test
---/unit
------/python
---------/tests.py &lt;&lt; test file
(Each directory has __init__.py)
</code></pre>

<p>Unit Testing command is</p>

<pre><code>python -m unittest test.unit.python.tests
</code></pre>

<p>In tests.py file, I have this import statement:</p>

<pre><code>from ....logs_cleanup.cleanup_logs import filename_matched
</code></pre>

<p>And it's causing this error below</p>

<blockquote>
  <p>ValueError: Attempted relative import beyond toplevel package</p>
</blockquote>

<p>The constraint is that,,, <strong>I can't use sys.path.append call in the very first statement</strong> because my pylint (Linting) doesn't allow it. is there any other solution?</p>
",https://stackoverflow.com/questions/56229013/calling-relative-paths-from-test-file-attempted-relative-import-beyond-topleve,['python'],67,False,0,1
Roboelectric with Room Database for android,"<p>How to do unit testing of Room Database with the help of Roboeletric?</p>

<p>I don't want to do instrumentation testing. </p>
",https://stackoverflow.com/questions/54327392/roboelectric-with-room-database-for-android,"['android-room', 'robolectric']",4660,True,9,2
Is there any way to test the order of Lists / Collections with jUnitJupiter?,"<p>I'm using JunitJupiter for unit testing. Now I'm at a point where I don't know how to check the order of a list.</p>

<p><strong>Code:</strong></p>

<pre><code>@Test
@DisplayName(""Should be in ascending order"")
void sortAscending() {
    List&lt;List&lt;AccountlinevaluesEntity&gt;&gt; finalList = monthlySuSa;
    for (List&lt;AccountlinevaluesEntity&gt; list : finalList) {
        list.sort(Comparator.comparing(AccountlinevaluesEntity::getAccountNumber));
        assert(list, ...........);

    }
}
</code></pre>

<p>I'm pretty new to unit testing, i searched a lot but I didn't figure out how to do it.</p>

<p>So, is there any way to do this with jUnitJupiter or are there other ways to do this? </p>
",https://stackoverflow.com/questions/59286146/is-there-any-way-to-test-the-order-of-lists-collections-with-junitjupiter,"['java', 'list', 'junit-jupiter']",309,False,0,1
scope keeps being undefined in angularjs unit-testing,"<p>I am trying to unit-testing for following code, I wrote following code for unit-testing like below, I have tried so many ways to work, but I keep getting error:</p>

<blockquote>
  <p>'Cannot read property 'num' of undefined'</p>
</blockquote>

<p>I do not know why scope is not properly set. If you have any idea about it, can you please give some advices?</p>

<pre><code>var angular = require('angular');
require('angular-mocks');

describe('test directive', function () {

    let $rootScope;
    let $compile;
    let scope;
    let newScope;
    let element;

    beforeEach(angular.mock.inject(function (_$compile_, _$rootScope_) {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
    }));

    describe('test directive', function () {

        beforeEach(function () {
            newScope = $rootScope.$new();
            element = $compile('&lt;test-directive&gt;&lt;/test-directive&gt;')(newScope);
            newScope.$digest();
            scope = element.isolateScope();
        });

        fit('scope initialized', function () {
            expect(scope.num).toEqual(1);
        });

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

<pre class=""lang-js prettyprint-override""><code>module.exports = module.directive('testDirective', ['$rootScope', '$scope', function($rootScope, $scope) {

    return {
        template: require('./test.html'),
        restrict: 'E',
        controller: [
            '$scope',
            function ($scope) {
                    $scope.num = 1

                    $scope.sum = function(a, b) {
                        return a + b;
                    }

            }]
    }
}]);
</code></pre>
",https://stackoverflow.com/questions/58735991/scope-keeps-being-undefined-in-angularjs-unit-testing,"['angularjs', 'unit-testing', 'scope', 'angularjs-scope']",133,False,0,1
Swift unit testing a method that includes timer,"<p>I am new in swift and unit testing in swift. Here in the code in MyClass I am using timer to trigger some method ..
I need to do unit testing for that method that has timer count value..
I have checked few answers. nothing worked out.
I am unable to do that. Can anyone help me out with this.
Thanks in advance.</p>

<pre><code> class MyClass(){

func triggerSecondTimer() {
    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(repeatSecondTimer), userInfo: nil, repeats: true)
}

@objc func repeatSecondTimer(){
    timerCount += 1
    if isServiceCallComplete || timerCount == secondInterval {
        timer?.invalidate()
        finishedSecondTimer()
    }
}
}
   func testSecondTimer() {

    splashScreenMock.triggerSecondTimer()
   // I want to check the timer count here..

    XCTAssertEqual(self.splashScreenMock.timerCount, 20)


}
</code></pre>
",https://stackoverflow.com/questions/59321364/swift-unit-testing-a-method-that-includes-timer,"['ios', 'swift', 'nstimer', 'swift5']",738,False,0,2
Unit testing React click outside component using Jest and react testing library,"<p>I found this implementation here but its using enzyme.</p>

<p><a href=""https://stackoverflow.com/questions/45046728/unit-testing-react-click-outside-component"">Unit testing React click outside component</a></p>

<p>Adding an event to window does not work either:</p>

<pre><code>window.addEventListener('click', () =&gt; {
      console.log('click on window');
    });
</code></pre>

<p>Has anyone came across this issue above using jest and ""@testing-library/react""?</p>
",https://stackoverflow.com/questions/56978283/unit-testing-react-click-outside-component-using-jest-and-react-testing-library,"['unit-testing', 'jestjs', 'react-testing-library']",23499,True,24,2
How to perform Unit testing on Spark Structured Streaming?,"<p>I would like to know about the unit testing side of Spark Structured Streaming. My scenario is, I am getting data from Kafka and I am consuming it using Spark Structured Streaming and applying some transformations on top of the data.</p>

<p>I am not sure about how can I test this using Scala and Spark. Can someone tell me how to do unit testing in Structured Streaming using Scala. I am new to streaming.</p>
",https://stackoverflow.com/questions/56894068/how-to-perform-unit-testing-on-spark-structured-streaming,"['scala', 'apache-spark', 'spark-structured-streaming', 'spark-streaming-kafka']",5882,True,5,2
Not able to increase code coverage in Angular Unit testing,"<p>I am trying to learn how to make unit testing for Angular with Karma and Jasmine.</p>

<p>My problem is that I make it with spyOn() and expect.toHaveBeenCalled() and even though Karma says that passed the tests, the Code Coverage is not updated.</p>

<p>I am new to angular unit testing and I dont know how to test methods properly so as to get code coverage.</p>

<p>Thanks everyone for the help.</p>
",https://stackoverflow.com/questions/58129821/not-able-to-increase-code-coverage-in-angular-unit-testing,"['angular', 'unit-testing', 'karma-jasmine', 'karma-coverage']",6754,True,2,2
"function is not giving expected result, failing Unit Testing","<p>I have to write a function <code>file_stats</code> that takes a  file name as parameter, and returns a tuple that contains three numbers: the number of lines, the number of words and the number of characters in the  file</p>

<p>I have wrote a code, that fails Unit Testing. But the output is fine.. Thanks in advance. How can it pass Unit Testing ?</p>

<pre><code>num_lines = 0
num_words = 0
num_chars = 0

def file_stats(filename):  

   global num_lines, num_words, num_chars  

   with open(filename, 'r') as file:
       for line in file:
           words = line.split()
           num_lines += 1
           num_words += len(words)
           num_chars += len(line)

   tuple1 = (num_lines, num_words, num_chars)
   file.close()
   return tuple1
</code></pre>

<p><strong>SampleFile.txt</strong></p>

<p>LIET</p>

<pre><code>Now, by Saint Peter's Church and Peter too,
He shall not make me there a joyful bride.
I wonder at this haste; that I must wed
Ere he, that should be husband, comes to woo.
I pray you, tell my lord and father, madam,
I will not marry yet; and, when I do, I swear,
It sh
</code></pre>

<p><strong>Expected Output</strong> - (9,58,304)</p>
",https://stackoverflow.com/questions/55566952/function-is-not-giving-expected-result-failing-unit-testing,"['python', 'python-3.x']",46,True,0,1
Is there any possibility for Root scss has to load in component while doing unit testing with karma &amp; Jasmine,"<p>Is there any possibility to load scss from root into component while doing unit testing? All the styles I have written in root styles.scss file.</p>

<p>But, When I am doing unit testing only scss in that component is loading so styles are not effecting which I have mentioned in root styles.scss file.</p>

<p>So I have to include that root styles.scss file while unit tests are running.</p>
",https://stackoverflow.com/questions/58743978/is-there-any-possibility-for-root-scss-has-to-load-in-component-while-doing-unit,['angular'],41,True,0,1
Unit testing controller functions in Nodejs using Mocha and Chai,"<p>I have a function in my controller which takes 2 arguments request and response. </p>

<pre><code>function convertTime (req, res) {
   callOtherFunction().then(function(result){
       res.status(200).send(result);
    }
}
</code></pre>

<p>My unit testing function to test this function looks something like this. </p>

<pre><code>describe('Testing my function ', function() {
  var req = {
      query: {}
     };

 var res = {
     sendCalledWith: '',
     send: function(arg) { 
              this.sendCalledWith = arg;
            },
    json: function(err){
            console.log(""\n : "" + err);
            },
     status: function(s) {this.statusCode = s; return this;}
   };

  it('Should error out if no inputTime was provided', function() {
    convertTime(req,res);
    expect(res.statusCode).to.equal(500)
  });

});
</code></pre>

<p>when I run my unit testing, it's not waiting for my response to resolve. As I don't have a callback function here to wait for, how do I make the test to wait until res object is updated?</p>
",https://stackoverflow.com/questions/54397897/unit-testing-controller-functions-in-nodejs-using-mocha-and-chai,"['node.js', 'unit-testing', 'express', 'mocha.js', 'chai']",1574,True,0,1
How to write the unit testing for the file upload method in the Angular 7 (or 2+),"<p>I'm trying to write the unit testing for the file upload method in the angular 7. Getting the below error in the testing window. I'm new for angular unit testing. Could someone help, How to add mock files to get the full code coverage? </p>

<blockquote>
  <p>TypeError: Cannot set property 'value' of undefined</p>
</blockquote>

<p>Here is my unit test code (spec file),</p>

<pre><code>describe('ImportComponent', () =&gt; {
    let component: ImportComponent;
    let fixture: ComponentFixture&lt;ImportComponent&gt;;
    let element;

    beforeEach(
        async(() =&gt; {
            TestBed.configureTestingModule({
                imports: [ HttpClientModule, RouterTestingModule ],
                declarations: [ ImportComponent ]
            }).compileComponents();
        })
    );

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

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

    it('should upload the file', () =&gt; {
        component.importFile();
        const inputEl = element.querySelector('#postal_file');
        const fileList = { 0: { name: 'foo', size: 500001 } };
        inputEl.value = {
            target: {
                files: fileList
            }
        };
        inputEl.dispatchEvent(new Event('change'));     
    });
});
</code></pre>

<p>Method in the component</p>

<pre><code>importFile() {
        const inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#postal_file');
        const fileCount: number = inputEl.files.length;
        const formData = new FormData();
        if (fileCount &gt; 0) {
            formData.append(this.postalFileName, inputEl.files.item(0));
            this.postalService.importPostalCodes(formData).subscribe((data) =&gt; {
                this.result = data;
            });
        }
    }
</code></pre>

<p>and the HTML,</p>

<pre><code>&lt;div class=""file-import""&gt;
        &lt;form action="""" method=""post"" encType=""multipart/form-data""&gt;
            &lt;label for=""postal_file""&gt;Choose File&lt;/label&gt;
            &lt;input type=""file"" name=""postal_file"" id=""postal_file""&gt;
            &lt;button type=""button"" (click)=""importFile()""&gt;Import&lt;/button&gt;
        &lt;/form&gt;
    &lt;/div&gt;
</code></pre>

<p>The unit test is not covered all the code as shown in the below image, please help , how to ge the 100% code coverage.</p>

<p><a href=""https://i.stack.imgur.com/79N1b.png"" rel=""noreferrer"">Code coverage image</a></p>
",https://stackoverflow.com/questions/55356093/how-to-write-the-unit-testing-for-the-file-upload-method-in-the-angular-7-or-2,"['angular', 'karma-jasmine', 'angular-test']",22175,True,12,2
How to do an unit test to check if the snack bar is open,"<p>I am new to angular and especially on unit testing. </p>

<p>Recently I have been doing a component to use the Mat-Snack-Bar material from angular material (<a href=""https://material.angular.io/components/snack-bar/overview"" rel=""nofollow noreferrer"">https://material.angular.io/components/snack-bar/overview</a>). </p>

<p>After creating my component, I am working on doing unit testing on this component to check if the class to open the snack bar is called. </p>

<p>I already tried to apply some answers that I found on stack overflow but I couldn't make work my unit testing and I constantly have this error message on the Karma app : </p>

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

<p>I can't understand what is going bad in my spec.ts of my component and how to fix this error. </p>

<p>My component.ts : </p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { MatSnackBar ,MatSnackBarHorizontalPosition, MatSnackBarVerticalPosition, } from ""@angular/material"";

@Component({
  selector: 'app-snack-bar',
  templateUrl: './snack-bar.component.html',
  styleUrls: ['./snack-bar.component.scss']
})
export class SnackBarComponent implements OnInit {

  ngOnInit() {
  }

  constructor(public snackBar: MatSnackBar) {}
  // Position of the snackbar
  horizontalPosition: MatSnackBarHorizontalPosition = 'right';
  verticalPosition: MatSnackBarVerticalPosition = 'top';

/**
 * To use a snackbar add the function openSnackBar('','','')
 * @param message Message that will be shown when the SnackBar is called
 * @param action The message that will be shown on the action button
 * @param state Permit to change the style of the SnackBar depending on the state
 */

  openSnackBar(message: string, action: string, state: string) {
    if ( state == 'suc') {
      var styleOfSnack = 'sucessSnackbar';
    } else if ( state == 'err') {
      var styleOfSnack = 'errorSnackbar';
    } else if ( state == 'inf') {
      var styleOfSnack = 'infoSnackbar';
    } else if ( state == 'war') {
      var styleOfSnack = 'warningSnackbar';
    }
    // code linked to the snackbar
    this.snackBar.open(message, action, {
      duration: 8000,
      panelClass: [styleOfSnack],
      horizontalPosition: this.horizontalPosition,
      verticalPosition: this.verticalPosition,
    });
  }
}
</code></pre>

<p>'''</p>

<p>And this is my component.spec.ts that verify the code : </p>

<pre><code>  describe('SnackBar should be open', () =&gt; {
  let component: SnackBarComponent;
  let a = """";
  let b = """";
  let c = """";

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ SnackBarComponent],
      providers: [ MatSnackBar, Overlay ]
    })
    .compileComponents();
    a = ""Test"";
    b = ""X"";
    c = ""suc"";
  });

  afterEach(() =&gt; {
    a = """";
    b = """";
    c = """";
  });

  it('opens', () =&gt; {
    expect(component.openSnackBar(a,b,c)).toHaveBeenCalled;
  });
})
</code></pre>

<p>I expect the unit test to check if the function openSnackBar is called! </p>

<p>Thank you for taking the time to read my issue, if you have any tips or tutorial to understand unit testing on angular for beginners I am taking them!</p>
",https://stackoverflow.com/questions/57091279/how-to-do-an-unit-test-to-check-if-the-snack-bar-is-open,"['angular', 'unit-testing', 'angular-material']",5975,True,0,1
I&#39;m beginner in Android testing with Mockito,"<p>I want to test this method using mockito and unit testing</p>

<p>public class CurrentIP {</p>

<pre><code>public static String getIPAddress() {
    try {
        List&lt;NetworkInterface&gt; interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List&lt;InetAddress&gt; addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress();
                    boolean isIPv4 = sAddr.indexOf(':') &lt; 0;
                    if (isIPv4)
                        return sAddr;
                }
            }
        }
    } catch (Exception ignored) {
    } // for now eat exceptions
    return """";
}
</code></pre>
",https://stackoverflow.com/questions/56824636/im-beginner-in-android-testing-with-mockito,"['android', 'testing', 'mockito']",152,False,-2,1
How to merge one branch to another without some files?,"<p>I've got two branches - development and master. I'm also using Catch2 framework for unit testing. Catch2 is on the development branch but when it comes to releasing a version to master, I don't want these files to go there.</p>

<p>Is there a command which allows me to ""lock"" some files on one branch? 
Let's say it looks like that:
<strong>Development</strong>
- Source Code
- Unit Testing Code</p>

<p>MERGE</p>

<p><strong>Master</strong>
- Source Code</p>
",https://stackoverflow.com/questions/57315951/how-to-merge-one-branch-to-another-without-some-files,"['git', 'git-merge']",39,True,1,2
NativeScript+Angular UnitTesting,"<p>I am new to Native Script with Angular. I need help for writing Unit Tests for Angular components by mocking a service with Karma and Jasmine. </p>

<p>I have followed the Native Script Unit Testing docs (<a href=""https://docs.nativescript.org/tooling/testing"" rel=""nofollow noreferrer"">https://docs.nativescript.org/tooling/testing</a>) to integrate the Unit Test environment but not much details available how to write test. </p>

<p>Please suggest me how to write or give some repo links of NS + ng Unit Testing.
Thanks.  </p>
",https://stackoverflow.com/questions/54865894/nativescriptangular-unittesting,"['nativescript', 'angular2-nativescript', 'nativescript-angular']",346,True,1,1
"property &#39;then&#39; does not exist on type void, Angular 6 unit testing error","<p>( angular 6 app, unit testing using karma and jasmine ) <br>
Hellooo,<br>
Being new at unit testing, I tried http testing on one of my Service's functions by copying and pasting this code that i found in a tutorial :</p>

<pre><code>let httpClientSpy: { get: jasmine.Spy };
import { TestBed, async, inject } from '@angular/core/testing';
import { TrainerCalendarService } from './trainer-calendar.service';
import { asyncData } from '../helpers/async-observable-helpers';
import { Appointment } from '../models/appointment';

let service: TrainerCalendarService;

describe('Service: TrainerCalendar', () =&gt; {
beforeEach(() =&gt; {
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get', 'post']);
service = new TrainerCalendarService(&lt;any&gt; httpClientSpy);
 });

it('should returns list of appointment', () =&gt; {
const list: Appointment[] = [
  new Appointment(),
  new Appointment()
];

httpClientSpy.get.and.returnValue(asyncData&lt;Appointment[]&gt;(list));

service.getAll().then(items =&gt; expect(items).toEqual(list, 'same items'));
});
});
</code></pre>

<p>And i got this after changing it according to my app: </p>

<pre><code>import { grpService } from ""./app/Services/grp.service""; 
import { of } from 'rxjs'
import { EtudiantComponent } from './app/etudiant/etudiant.component';

let httpClientSpy: { get: jasmine.Spy };

let service: grpService;

describe('Service: Test attendency ', () =&gt; {
beforeEach(() =&gt; {
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get', 'post']);
service = new grpService(&lt;any&gt; httpClientSpy);
 });

 it('should returns list of students', () =&gt; {
 const list: EtudiantComponent[] = [
  new EtudiantComponent(service),
  new EtudiantComponent(service)
];

httpClientSpy.get.and.returnValue(of&lt;EtudiantComponent[]&gt;(list));

service.getGroupesFromServer.then(items =&gt; expect(items).toEqual(list, 'same items'));
 });
});
</code></pre>

<p>i get an error for that last line of code : Property 'then' does not exist on type '() => void'.</p>

<p>How can i fix that?</p>
",https://stackoverflow.com/questions/59516298/property-then-does-not-exist-on-type-void-angular-6-unit-testing-error,"['unit-testing', 'angular6', 'karma-runner']",648,False,1,1
Autowired fields of mocked object returns null in Mockito,"<p>I have a <code>StudentService</code> class. And I have written a class for unit testing methods of <code>StudentService</code> class. My code is as follows:-</p>

<pre><code>@Component
@EnableAutoConfiguration
public class StudentService {

@Autowired
StudentInstitutionMapper studentInstitutionMapper;

public Integer getPresentStudentCount(StudentParams studentParam) {
    // TODO Auto-generated method stub
    StudentInstitutionExample example = new StudentInstitutionExample();
    StudentInstitutionExample.Criteria criteria = example.createCriteria();
    criteria.andActiveYnEqualTo(""Y"");
    criteria.andDeleteYnEqualTo(""N"");
    criteria.andIsPresentEqualTo(""Y"");
    criteria.andInstitutionTestIdEqualTo(studentParam.getInstitutionTestId());
    List&lt;StudentInstitution&gt; studentInstitutionList = studentInstitutionMapper.selectByExample(example);//line 8 in method
    return studentInstitutionList.size();
}


}
</code></pre>

<p>And in my unit testing class, I have written following method.</p>

<pre><code>    @Test
    public void testStudentService_getPresentStudentCount1()
    {



        StudentService service=new StudentService();
        StudentParams studentParam=mock(StudentParams.class);

        Integer institutionTestId=3539;
        when(studentParam.getInstitutionTestId()).thenReturn(institutionTestId);


        int i=service.getPresentStudentCount(studentParam);
        assertEquals(0,i);

    }
</code></pre>

<p>when I execute the test class, i get error. This is because in <code>StudentService</code> class, in <code>getPresentStudentCount()</code> method, at line 8, the <code>studentInstitutionMapper</code> field is <code>null</code>. This is happening only for mocked object. How do i get autowired fields of mocked object?</p>
",https://stackoverflow.com/questions/58877271/autowired-fields-of-mocked-object-returns-null-in-mockito,"['java', 'unit-testing', 'mockito', 'junit4']",3755,True,1,4
How to test function in laravel Unit testing,"<p>Using Unit Testing for the first time. </p>

<p>Ceated Test File by cmd:</p>

<pre><code>php artisan module:make-test ProjectTest Projects
</code></pre>

<p>I can test by cmd:</p>

<pre><code>./vendor/bin/phpunit
</code></pre>

<p>But I want to test my function, My function is like:</p>

<pre><code>public function update(Request $request, $id)
    {
        $project = Project::find($id);
        $project-&gt;project_name = request('project_name');
        $project-&gt;save();
        return response()-&gt;json([
            'message' =&gt;  ""Project Updated Successfully"",
            'updatedId' =&gt; $project-&gt;id
            ], 200);
    }
</code></pre>

<p>Can anyone please guide me on how to test this Controller in PHPUnit? </p>

<p>On PostMan testing the function like:</p>

<pre><code>URL:(POST method) http://localhost:8000/api/updateProject/1
</code></pre>

<p>On Body</p>

<pre><code>{
    ""project_name"":""school"",
}
</code></pre>

<p>How to use PHP Unit Testing in Laravel for the above Controller ?. Kindly explain to me with code Snippets.</p>
",https://stackoverflow.com/questions/58443921/how-to-test-function-in-laravel-unit-testing,"['api', 'unit-testing', 'testing', 'laravel-6']",1646,True,0,1
Angular unit testing &quot;If part not taken&quot;,"<pre><code> Dname = JSON.stringify(this.userDetails);
  Dpass = JSON.stringify({
    userName: 'test',
    password: 'test'
  });

  onSubmit() {
    this.userDetails = this.inputForm.value;
    this.submitted = true;
    if (this.Dname === this.Dpass) {
      this.router.navigate(['/page1']);
      console.log('ok');
    } else {
      console.log('not ok');
    }
  }
</code></pre>

<p><a href=""https://i.stack.imgur.com/ppMVX.png"" rel=""nofollow noreferrer""><strong>If path not taken --can someone help me to solve this issue in angular unit testing</strong></a></p>
",https://stackoverflow.com/questions/59072186/angular-unit-testing-if-part-not-taken,"['angular', 'unit-testing', 'karma-jasmine']",201,False,-1,2
Skip authorization while unit testing in Lumen,"<p>Is there a way to skip Authorization middleware when running unit testing for a Lumen application?</p>
",https://stackoverflow.com/questions/58536850/skip-authorization-while-unit-testing-in-lumen,"['middleware', 'lumen', 'lumen-5.8']",562,True,0,1
How to write unit test for controller in spring boot,"<p>I am new to Unit testing and TDD. I want to apply unit testing for my controller and service class which i have written in spring boot.</p>

<p>I have implemented test class using a tutorial. However, I could not implemented it successfully. I have included my current code.</p>

<p><strong>Controller</strong></p>

<pre><code>@RestController
@RequestMapping(""/api"")
public class MyController {
    private static final Logger LOGGER = LoggerFactory.getLogger(AdminController.class);
    @Autowired
    MyService myService;

    @PostMapping(""/create"")
    public ResponseEntity&lt;?&gt; createUser(@RequestHeader(""Authorization"") String token, 
        @RequestBody User user){
        ResponseDTO finalResponse = new ResponseDTO();
        try {
            ResponseEntity&lt;?&gt; entity = myService.create(token, user);             
            finalResponse.setMessageCode(entity.getStatusCode());
            finalResponse.setMessage(""Success"");
            finalResponse.setError(false);
            ResponseEntity&lt;ResponseDTO&gt; finalEntity = ResponseEntity.ok().body(finalResponse);
        return finalEntity;
        } catch (Exception e) {      
            finalResponse.setMessageCode(HttpStatus.EXPECTATION_FAILED);
            finalResponse.setMessage(e.getMessage());
            finalResponse.setError(true);
            ResponseEntity&lt;ResponseDTO&gt; finalEntity = 
            ResponseEntity.ok().body(finalResponse);
            return finalEntity;
    }
}
</code></pre>

<p><strong>ResponseDTO</strong></p>

<pre><code>public class ResponseDTO {
    private HttpStatus messageCode;
    private String message;
    private String messageDetail;
    private Object body;
    private boolean error;

    //setters and getters
}
</code></pre>

<p><strong>Current Test Class</strong></p>

<pre><code>@RunWith(SpringRunner.class)
public class MyControllerTest {
    private MockMvc mockMvc;

    @InjectMocks
    private MyController myController;

    @Before
    public void setUp() throws Exception {
    mockMvc = MockMvcBuilders.standaloneSetup(myController).build();
    }

    @Test
    public void testCreateUser() throws Exception {
        mockMvc.perform(post(""/api/create"")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isCreated())
            .andExpect(jsonPath(""$.*"", Matchers.hasSize(1)));
    }

}
</code></pre>

<p>When i run test class i am getting <code>WARN Resolved [org.springframework.web.bind.MissingRequestHeaderException: Missing request header 'Authorization' for method parameter of type String]</code></p>

<p>What am i doing wrong here? Any help would be grateful.</p>
",https://stackoverflow.com/questions/56070205/how-to-write-unit-test-for-controller-in-spring-boot,"['java', 'rest', 'unit-testing', 'spring-boot', 'junit']",4701,True,1,2
unit testing a login view controller in ios related queries,"<p>i need to perform unit tests for login screen( it has one email textfield, one password textfield and one loginbutton), having a few queries related to it.</p>

<p>what i understand of unit testing of viewcontroller is, i need to make rest of an interacting components (like viewmodels) as mock objects.</p>

<p>So viewcontroller responsibility is only to show/take action what has been sent from mockviewmodel/viewmodel. </p>

<p>In that case for unit testing of login screen, it should only check for, is it taking correct actions based on what has been sent from viewmodels ?</p>

<p><strong>So actual testing of what kind of error/output generated by different kind of email, password combinations should be done by viewmodel unit tests.</strong></p>

<p>Is my above understanding of unit testing of loginscreen (viewcontroller) correct ?</p>
",https://stackoverflow.com/questions/59327967/unit-testing-a-login-view-controller-in-ios-related-queries,"['ios', 'swift', 'unit-testing']",517,False,1,1
How to test function in class using jest,"<p>I wasn't able to make unit testing worked using jest</p>

<p>I'm trying to test a specific function that's calling or expecting result from other function but I'm not sure why it is not working. I'm pretty new to unit testing and really have no idea how could I make it work. currently this is what I've tried</p>

<pre><code>export class OrganizationService {

    constructor() {
        this.OrganizationRepo = new OrganizationRepository()
    }

    async getOrganizations(req) {
        if (req.permission !== 'internal' &amp;&amp; req.isAuthInternal === false) {
            throw new Error('Unauthenticated')
        }
        const opt = { deleted: true }
        return this.OrganizationRepo.listAll(opt)
    }

}
</code></pre>

<p>This is my OrganizationRepository that extends the MongoDbRepo</p>

<pre><code>import { MongoDbRepo } from './mongodb_repository'

export class OrganizationRepository extends MongoDbRepo {

    constructor(collection = 'organizations') {
        super(collection)
    }

}
</code></pre>

<p>and this is the MongoDbRepo</p>

<pre><code>const mongoClient = require('../config/mongo_db_connection')
const mongoDb = require('mongodb')

export class MongoDbRepo {

    constructor(collectionName) {
        this.collection = mongoClient.get().collection(collectionName)
    }

    listAll(opt) {

        return new Promise((resolve, reject) =&gt; {
            this.collection.find(opt).toArray((err, data) =&gt; {
                if (err) {
                    reject(err)
                }
                resolve(data)
            })
        })
    }
}
</code></pre>

<p>and this is the test that I've made</p>

<pre><code>import { OrganizationService } from '../../../src/services/organization_service'

describe('getOrganizations', () =&gt; {
    it('should return the list of organizations', () =&gt; {
        // const OrgRepo = new OrganizationRepository()
        const orgService = new OrganizationService()

        const OrgRepo = jest.fn().mockReturnValue(""[{_id: '123', name: 'testname'}, {_id: '456, name: 'testname2'}]"")
        // orgService.getOrganizations = jest.fn().mockReturnValue('')
        const result = orgService.getOrganizations()

        expect(result).toBe(OrgRepo)
    })
})
</code></pre>
",https://stackoverflow.com/questions/58540188/how-to-test-function-in-class-using-jest,"['node.js', 'jestjs']",4297,True,2,2
How to write typescript? Unit Testing Vue Components,"<p>How to write following code in typescript?
This code is from <a href=""https://v2.vuejs.org/v2/cookbook/unit-testing-vue-components.html#Real-World-Example"" rel=""nofollow noreferrer"">Unit Testing Vue Components</a>.</p>
<p>Code:</p>
<pre><code>const factory = (values = {}) =&gt; {
  return shallowMount(Foo, {
    data: { ...values  }
  })
}
</code></pre>
<p>Error:</p>
<pre><code>Missing return type on function.
</code></pre>
",https://stackoverflow.com/questions/56642016/how-to-write-typescript-unit-testing-vue-components,"['typescript', 'vue.js', 'vue-component']",61,False,0,0
How we can do unit testing in windows form c# where i have built in private methods,"<pre><code>private void name_KeyPress(object sender, KeyPressEventArgs e)
{
     char ch = e.KeyChar;
     if (!char.IsLetter (ch) &amp;&amp; (ch != 8))
     {
         e.Handled = true;
     } 
}
</code></pre>

<p>1.<strong>some part of the code.how to do unit testing for this code</strong></p>

<pre><code>public int validation()
{
    int flag = 0;
    Regex Rx = new Regex(@""^[\p{L} \.'\-]{0,20}$"");
    Regex Rx1 = new Regex(@""^[\p{L} \.'\-]{0,20}$"");
    Regex Rx2 = new Regex(@""^[0-9]{10}$"");
    if (name.Text=="""")
    {
         name.Focus();
         errorProvider1.SetError(name, MessageBox.Show(""enter your name"", ""error"", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
         flag = 1;
    }
    else if (fathername.Text == """")
    {
        fathername.Focus();
        errorProvider1.SetError(name, MessageBox.Show(""Enter your father name"", ""error"", MessageBoxButtons.OK, MessageBoxIcon.Error).ToString());
        flag = 1;
    }
}
</code></pre>

<p>its a public method</p>
",https://stackoverflow.com/questions/54268849/how-we-can-do-unit-testing-in-windows-form-c-where-i-have-built-in-private-meth,"['c#', '.net', 'forms', 'winforms', 'unit-testing']",245,True,0,2
Django 2 oauth2 toolkit register an application programmatically,"<p>Create a oauth2 application and get client_id and client_secret programmatically. This is helpful helpful for unit testing. </p>
",https://stackoverflow.com/questions/54810025/django-2-oauth2-toolkit-register-an-application-programmatically,['superuser'],289,False,0,1
Unit Testing Go Functions having ORM interactions,"<p>I have written a function:</p>

<pre><code>func AllItems(w http.ResponseWriter, r *http.Request) {
    db, err := gorm.Open(""sqlite3"", ""test.db"")
    if err != nil {
        panic(""failed to connect database"")
    }
    defer db.Close()

    var items [] Item
    db.Find(&amp;items)
    fmt.Println(""{}"", items)

    json.NewEncoder(w).Encode(items)
}
</code></pre>

<p>I want to do unit testing on this. Ideally, unit testing means that each line of the function needs to be tested. I'm not sure how I should test if a database connection is opened and then if it is displaying all the contents of the database. How should I test this code? </p>

<p>This function is the GET endpoint of a simple CRUD application. The code is <a href=""https://github.com/ShubhamRathi/ToDo-App"" rel=""nofollow noreferrer"">here</a>. </p>
",https://stackoverflow.com/questions/54648551/unit-testing-go-functions-having-orm-interactions,"['unit-testing', 'go', 'mocking', 'testify']",195,True,0,1
redux saga unit test expected but received deep-equality error,"<p>Getting this error when unit testing a simple api call in redux saga. </p>

<blockquote>
  <p>● My feature › testing api call</p>

<pre><code>expect(received).toEqual(expected) // deep equality

- Expected
+ Received

  Object {
    ""@@redux-saga/IO"": true,
    ""combinator"": false,
    ""payload"": Object {
-     ""args"": Array [
-       Object {
-         ""completed"": false,
-         ""id"": 1,
-         ""title"": ""delectus aut autem"",
-         ""userId"": 1,
-       },
-     ],
+     ""args"": Array [],
      ""context"": null,
      ""fn"": [Function getData],
    },
    ""type"": ""CALL"",
  }
</code></pre>
</blockquote>

<p>I have the api call that is set up like this. </p>

<pre><code>import axios from 'axios';   
export default {
  json: {
    getData: () =&gt; axios.get('https://jsonplaceholder.typicode.com/todos').then(res =&gt; res.data.slice(0, 1)),
  },
};
</code></pre>

<p>this api call is being used here in a redux-saga function.</p>

<p><strong>Redux-saga</strong></p>

<pre><code>import {
  put, fork, takeLatest, call,
} from 'redux-saga/effects';
import { GET_DATA_SAGA } from '../actions/types';
import api from '../api';
import { fetchDataSuccess, fetchDataError } from '../actions/dataActions';

export function* getData() {
  try {
    const data = yield call(api.json.getData);

    console.log(data);

    yield put(fetchDataSuccess(data));
  } catch (err) {
    yield put(fetchDataError(err));
  }
}

export function* watchData() {
  yield takeLatest(GET_DATA_SAGA, getData);
}

export default function* () {
  yield fork(watchData);
}
</code></pre>

<p>How should i be unit testing this properly, am i missing something ?</p>

<p>I'm also referencing this tutorial </p>

<p><a href=""https://codeburst.io/how-i-test-redux-saga-fcc425cda018"" rel=""nofollow noreferrer"">https://codeburst.io/how-i-test-redux-saga-fcc425cda018</a></p>

<p><strong>redux-saga unit test</strong></p>

<pre><code>import {
  put, fork, takeLatest, call,
} from 'redux-saga/effects';
import { GET_DATA_SAGA } from '../actions/types';
import {expectSaga} from 'redux-saga-test-plan';
import { fetchDataSuccess, fetchDataError } from '../actions/dataActions';
import api from '../api';
import { cloneableGenerator } from '@redux-saga/testing-utils';
import {getData} from './data';

const testData = {
  userId: 1, 
  id: 1, 
  title: ""delectus aut autem"", 
  completed: false
}

describe('My feature', () =&gt; {
  it('testing api call', () =&gt; {
    // const data = getData(api.json.getData);
    // console.log(data)
    const generator = cloneableGenerator(getData)(fetchDataSuccess)
    // console.log(generator)
    expect(generator.next().value).toEqual(call(api.json.getData, testData));
  })
})
</code></pre>
",https://stackoverflow.com/questions/57150863/redux-saga-unit-test-expected-but-received-deep-equality-error,"['reactjs', 'redux', 'redux-saga']",1657,True,0,1
How to throw JsonProcessingException while creating Json from List using Mockito?,"<p>I am trying to unit test catch block to convert List into Json format using jackson. Here is my code:</p>

<pre><code>   public String convert(List&lt;POJO&gt; list) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            data = objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException exception) {
            System.out.println(""Exception message: {}"", exception.getMessage());
        }
        return data;
    }
</code></pre>

<p>I tried unit testing this way:</p>

<pre><code>@Mock
ObjectMapper mockObjectMapper;

@Test(expected = JsonProcessingException.class)
public void doThrowException() throws JsonProcessingException {
    doThrow(JsonProcessingException.class).when(mockObjectMapper).writeValueAsString(any());
    dataTransformer.convert(new ArrayList&lt;&gt;());
    verify(mockObjectMapper.writeValueAsString(any()));
}
</code></pre>

<p>I have been trying to get my head around to cover this unit test for full coverage. I looked up couple of articles on SO, but no luck. Since I am new to unit testing world, I have a feeling that I am definitely missing something here.</p>
",https://stackoverflow.com/questions/56242217/how-to-throw-jsonprocessingexception-while-creating-json-from-list-using-mockito,"['java', 'json', 'unit-testing', 'exception', 'mockito']",1492,True,0,1
Jasmine - When to use toContain() or toMatch()?,"<p>I was studying about TDD and unit testing using Jasmine JS and I have a question about their methods.</p>

<p>I found two methods and would like to know what is the difference.</p>

<pre><code>describe('Teste do toContain', () =&gt; {
    var name = 'Lucas de Brito Silva'
    it('Deve demonstrar o uso do toContain', () =&gt; {
        expect(name).toContain('Lucas');
    });
});
</code></pre>

<pre><code>describe('Teste do toMatch', function () {
    var text = 'Lucas de Brito Silva'
    it('deve validar o uso do toMatch', () =&gt; {
        expect(text).toMatch('Brito');
    });
})
</code></pre>
",https://stackoverflow.com/questions/57325448/jasmine-when-to-use-tocontain-or-tomatch,"['unit-testing', 'jasmine', 'tdd']",13418,True,13,1
How to test vue Js metaInfo,"<p>Am writing some unit testing, I have a component with meta info set using Vue-meta</p>

<p>My Component looks like this.</p>

<pre><code>export default {
...
  metaInfo () {
    const expertName = this.getBlogInfo.blog.author.trim()
    const fullName = expertName ? `${expertName.first_name} ${expertName.last_name}` : 'Cowsoko'
    return {
      title: `Dairynomics - Blog post from ${fullName}`,
      meta: [
        {
          vmid: 'og:description',
          name: 'og:description',
          content: this.description
        },
        {
          vmid: 'og:image',
          name: 'og:image',
          content: this.getBlogInfo.blog.photo
        }
      ]
    }
  }
</code></pre>

<p>...</p>
",https://stackoverflow.com/questions/57901994/how-to-test-vue-js-metainfo,"['unit-testing', 'vue.js', 'testing', 'jestjs', 'vue-component']",927,True,2,2
Rxjava 2 on error is not called while unit testing,"<p>Rxjava 2 on error is not called while unit testing . I am using kotlin with rxJava 2 .</p>

<blockquote>
  <p>method</p>
</blockquote>

<pre><code>  @SuppressLint(""CheckResult"")
    override fun fetchFilms() {
        view.showLoader(true)
        disposable = getRetrofitInstance(false).create(API::class.java)
                .fetchFilms()
                .subscribeOn(io)
                .observeOn(main)
                .subscribeWith(object : DisposableObserver&lt;Response&gt;() {
                    override fun onComplete() {
                    }

                    override fun onNext(t: Response) {
                        println(t)
                        view.setAdapter(t?.results as List&lt;ResultsItem&gt;)
                        view.showLoader(false)
                    }

                    override fun onError(e: Throwable) {
                        e.printStackTrace()
                        view.showLoader(false)
                        view.showError(e.message.toString())                    }

                })


    }
</code></pre>

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

<pre><code>@Test
    fun  fetchInvalidDataShouldThrowError(){

        `when`(api.fetchFilms()).thenReturn(Observable.error(IOException()))
   filmsPresenter.fetchFilms()
        val subscriber = TestSubscriber&lt;Response&gt;()

        subscriber.awaitTerminalEvent(5,TimeUnit.SECONDS)

        verify(filmsView, times(1)).showLoader(true)
        verify(filmsView).showError(""t"")
        verify(filmsView).showLoader(false)


    }
</code></pre>
",https://stackoverflow.com/questions/55135379/rxjava-2-on-error-is-not-called-while-unit-testing,"['android', 'kotlin', 'junit']",2429,True,0,3
unit testing angular service that uses firebase auth?,"<p>I've setup simple authentication service on angular that returns a Promise:</p>

<pre><code>import * as firebase from 'firebase/app';

@Injectable({
    providedIn: 'root'
})

export class AuthService {

  doLogin(val:{email:string, password:string}) {
  return new Promise&lt;any&gt;((resolve, reject) =&gt; {
    firebase
      .auth()
      .signInWithEmailAndPassword(val.email, val.password)
      .then(
        res =&gt; resolve(res),
        err =&gt; reject(err)
      );
    });
  }

}
</code></pre>

<p>How do I properly implement unit testing on the service? 
The way I currently achieve this to do unit testing using jasmine, by providing real user credential (which is not a good thing, as I'm going to push the code to github) and calling the doLogin method directly using the credential.</p>

<pre><code>describe('AuthService', () =&gt; {
let service: AuthService;
const userCreds = {
    email: 'somerealemail@somedomain.com',
    password: 'somerealpassword'
};

beforeEach(() =&gt; TestBed.configureTestingModule({
    imports: [FirebaseModule],
    providers: [AuthService]
}));

beforeEach(() =&gt; {
    service = TestBed.get(AuthService);
});

it('should logged in', async((done) =&gt; {
    service.doLogin(userCreds).then(
        res =&gt; {
            expect(res).toBeTruthy();
        }
    )
}));
</code></pre>

<p>Sorry if the code is mess, I'm totally new on both angular and jasmine, any advice or idea is greatly appreciated,
thanks</p>
",https://stackoverflow.com/questions/55235078/unit-testing-angular-service-that-uses-firebase-auth,"['angular', 'firebase', 'unit-testing', 'jasmine', 'firebase-authentication']",1689,True,4,1
Unit Testing Custom iOS Framework with or without Host Application,"<p>I have a custom iOS framework written in Swift that presents AVCaptureVideoPreviewLayer and also presents some custom popup screens. I want to add unit tests and wondering if I can do this without having a host App specified and instead programmatically create a minimal host app.</p>

<p>Some resources I've found that seem to be moving in the direction but were not written with unit testing frameworks in-mind:</p>

<p><a href=""https://marcosantadev.com/fake-appdelegate-unit-testing-swift/"" rel=""nofollow noreferrer"">https://marcosantadev.com/fake-appdelegate-unit-testing-swift/</a></p>

<p><a href=""https://qualitycoding.org/ios-app-delegate-testing/"" rel=""nofollow noreferrer"">https://qualitycoding.org/ios-app-delegate-testing/</a></p>
",https://stackoverflow.com/questions/54030136/unit-testing-custom-ios-framework-with-or-without-host-application,"['swift', 'xcode', 'unit-testing', 'frameworks', 'xctest']",1925,True,2,1
WPF Automatic Build and Reload when source code change,"<p>I see some answer about it, suggest use Live Unit Testing feature.
So I don't have Microsoft Enterprise and therefore can't use its Live Unit Testing feature. Tried to create a simple application in order to compile &amp; reload into the WPF container window. </p>

<p>skeleton code look like:</p>

<pre><code>public void RecompileAndReloadPrj ()
{
   Grid.Content = null;
   ReleaseAsm()
   RunMsBuild(targetProject);
   Grid.Content = LoadComponetFromAsm(targetASM);
}
</code></pre>

<p>Unfortunately getting it to work has turned out to be a bit complicated... Does anyone have ready code that they could post, tips etc, or provide a link?</p>
",https://stackoverflow.com/questions/58094104/wpf-automatic-build-and-reload-when-source-code-change,"['c#', 'wpf', 'visual-studio']",191,True,-1,1
How to write unit test cases for login servie,"<p>I am new to the unit testing for angular 7. I write some test cases buts its not covered in my code coverage please any one help me.My login service.ts file and spec.ts file added below.
I am new to the unit testing for angular 7. I write some test cases buts its not covered in my code coverage please any one help me.My login service.ts file and spec.ts file added below.</p>

<p>My login.service.ts file</p>

<pre><code>import { Router } from '@angular/router';
import { Utility } from '../../shared/utility.module';
import { User } from './../Models/user.model';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';
import { GenericErrorHandler } from '../../error-handlers/generic.error.handler';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoginService {
  serverUrl = 'https://www.livepaperapi.com/';
  errorData: {};
  private isUserLoggedIn = new Subject&lt;boolean&gt;();
  isUserLoggedIn$ = this.isUserLoggedIn.asObservable();
  private utility: Utility;
  constructor(private http: HttpClient, private router: Router) {
    this.utility = new Utility();
  }

  login(username: string, password: string) {
    const headers: HttpHeaders = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: 'Basic ' + btoa(username + ':' + password)
    });

    return this.http
      .post&lt;User&gt;(
        `${this.serverUrl}auth/v2/token`,
        'grant_type=client_credentials&amp;scope=default',
        { headers }
      )
      .pipe(catchError(GenericErrorHandler.handleError))
      .pipe(
        map(user =&gt; {
          if (user &amp;&amp; user.accessToken) {
            this.utility.storeUserAccessToken(user.accessToken);
            this.isUserLoggedIn.next(true);
            return true;
          }
          this.isUserLoggedIn.next(false);
          return false;
        })
      );
  }

  get isLoggedIn(): boolean {
    return this.utility.isStoredTokenValid();
  }

  getAuthorizationToken() {
    return this.utility.getUserAccessToken();
  }

  logout() {
    this.utility.deleteUserAccessToken();
    this.router.navigate(['']);
    this.isUserLoggedIn.next(false);
  }
}
</code></pre>

<p>My login.service.spec.ts</p>

<pre><code>import { TestBed, inject, fakeAsync, tick } from '@angular/core/testing';
import { LoginService } from './login.service';
import { CommonTestModules } from '../../shared/common.test.modules';
import {
  HttpClientTestingModule,
  HttpTestingController
} from '@angular/common/http/testing';
import { User } from './../Models/user.model';

describe('LoginService', () =&gt; {
  beforeEach(() =&gt;
    TestBed.configureTestingModule({
      imports: [CommonTestModules, HttpClientTestingModule],
      providers: [LoginService]
    })
  );

  it('should be created', () =&gt; {
    const service: LoginService = TestBed.get(LoginService);
    expect(service).toBeTruthy();
  });

  it(
    'should perform login correctly',
    fakeAsync(
      inject(
        [LoginService, HttpTestingController],
        (loginService: LoginService, backend: HttpTestingController) =&gt; {

          // Set up
          const url = 'https://www.livepaperapi.com/auth/v2/token';
          const responseObject = {
            ""serviceName"": ""auth"",
            ""apiVersion"": ""2.0"",
            ""accessToken"": ""YW5kcmg3aDV1"",
            ""scope"": ""default""
          }

          let response = null;
          const mockResponse = {
            status: '200'
          };
          let username = ""hpzp8yyo5l6f9e8lbqqy4748xt7yc8hc"";
          let password = ""rpcB8VAZHT1XXePgHDahOXD9r0kDpRBL"";
          loginService.login(username, password).subscribe(
            (receivedResponse: any) =&gt; {
              response = receivedResponse;
              expect(mockResponse.status.toString()).toEqual('200');
            },
            (error: any) =&gt; {}
          );

          const requestWrapper = backend.expectOne({url: 'https://www.livepaperapi.com/auth/v2/token'});
          requestWrapper.flush(responseObject);

          tick();

          expect(requestWrapper.request.method).toEqual('POST');

        }
      )
    )
  );


});
</code></pre>
",https://stackoverflow.com/questions/57904298/how-to-write-unit-test-cases-for-login-servie,"['angular', 'unit-testing']",1726,False,0,1
Stub function with return function with sinon?,"<p>I want to make unit testing and cover my code, this is my code, how can cover the createClient with sinon ?</p>

<pre><code>const client = redis.createClient({
  retry_strategy: function(options) {
    if (options.error) {
      if (options.error.code === 'ECONNREFUSED') {
        return new Error('The server refused the connection');
      }
      if (options.error.code === 'ECONNRESET') {
        return new Error('The server reset the connection');
      }
      if (options.error.code === 'ETIMEDOUT') {
        return new Error('The server timeouted the connection');
      }
    }
    if (options.total_retry_time &gt; 1000 * 60 * 60) {
      return new Error('Retry time exhausted');
    }
    if (options.attempt &gt; 10) {
      return undefined;
    }
    return Math.min(options.attempt * 100, 3000);
  }
</code></pre>
",https://stackoverflow.com/questions/54971455/stub-function-with-return-function-with-sinon,"['javascript', 'node.js', 'redis', 'sinon', 'stub']",877,True,1,2
"Running into an Angular nested form error in unit test, what is the error?","<p>So I am getting the following error in unit testing a nested angular form:</p>

<pre><code> No value accessor for form control with path: 'address -&gt; address1'

      at _throwError (../packages/forms/src/directives/shared.ts:140:9)
      at setUpControl (../packages/forms/src/directives/shared.ts:37:27)
      at FormGroupDirective.addControl (../packages/forms/src/directives/reactive_directives/form_group_directive.ts:132:5)
      at FormControlName._setUpControl (../packages/forms/src/directives/reactive_directives/form_control_name.ts:278:66)
      at FormControlName.ngOnChanges (../packages/forms/src/directives/reactive_directives/form_control_name.ts:207:28)
</code></pre>

<p>The form is defined as follows</p>

<pre class=""lang-js prettyprint-override""><code>ngOnInit() {
  this.form = this.fb.group({
    address: this.fb.group({
      address1: '',
      address2: '',
      ...
    })
  })
}
</code></pre>

<p>Template:</p>

<pre><code>&lt;form formGroup=""form""&gt;
        &lt;form formGroupName=""address""&gt;
          &lt;custom-text-input formGroupName=""adress1"" label=""Address 1""&gt;
          &lt;/custom-text-input&gt;
          &lt;custom-text-input formGroupName=""adress2"" label=""Address 1""&gt;
          &lt;/custom-text-input&gt;
          &lt;custom-text-input formGroupName=""phone"" label=""Phone""&gt;
          &lt;/custom-text-input&gt;
          &lt;custom-text-input formGroupName=""zipCode"" label=""Zip Code""&gt;
          &lt;/custom-text-input &gt;
          &lt;custom-text-input formGroupName=""state"" label=""State""&gt;
          &lt;/custom-text-input &gt;
        &lt;/form&gt;
      &lt;/form&gt;
</code></pre>
",https://stackoverflow.com/questions/57815037/running-into-an-angular-nested-form-error-in-unit-test-what-is-the-error,"['angular', 'angular-reactive-forms']",1022,True,1,2
write test case in jest for DOM,"<p>I am trying to write unit testing in jest for the code below:</p>

<pre><code>var checkallboxes = document.getElementsByName(""rowSelectCheckBox"");
for (var i = 0, n = checkallboxes.length; i &lt; n; i++) {
  checkallboxes[i].checked = true;
}
</code></pre>

<p>How to write test code in jest?</p>
",https://stackoverflow.com/questions/55412067/write-test-case-in-jest-for-dom,"['vue.js', 'jestjs', 'babel-jest']",73,False,0,0
Mocking Kafka APIs for Unit Testing,"<p>I want to mock the Confluent Kafka APIs for Consumer and Producer in GO for Unit Testing, Is there any way (process/steps/library) to mock them successfully?</p>
",https://stackoverflow.com/questions/59316913/mocking-kafka-apis-for-unit-testing,"['unit-testing', 'go', 'apache-kafka', 'confluent-platform']",5613,False,7,1
AWS-CDK Lambda and Testing,"<p>Using aws-cdk (Typescript) to deploy an environment containing Lambdas, basics are working well but now I want to move onto developing the Lambdas and I'm confused about unit testing in the context of the CDK.</p>

<p>The CDK is using Jest for unit testing, am I able to use Mocha and Chai for my Lambda's or do I need to use Jest?</p>

<p>I think Jest makes sense for the CDK but I like Mocha\Chai for testing my business logic within the Lambdas.</p>
",https://stackoverflow.com/questions/58090157/aws-cdk-lambda-and-testing,"['amazon-web-services', 'aws-cdk']",1106,True,0,1
"Having issues intergrating Unit Testing into an active Vuetify 2 Project, Error with SASS (Mocha-webpack / Vue Unit Test Tools)","<p>When trying to run a Unit Test on a Vuetify 2 app I get the error for SASS Stylesheets not being found, they are there.</p>

<p>The app has had no unit testing before so we need to include it to this project, I have tried to create a new fresh project and the testing works perfectly there, I have used multiple guides such as: <a href=""https://vuetifyjs.com/en/getting-started/unit-testing"" rel=""nofollow noreferrer"">https://vuetifyjs.com/en/getting-started/unit-testing</a> But I get the same issues no matter what I use. I have tried mocha, mocha-webpack, chai, vue-test-utils, Jest etc.
<a href=""https://imgur.com/X3zHFBE"" rel=""nofollow noreferrer"">https://imgur.com/X3zHFBE</a>
<a href=""https://imgur.com/kQoiJBB"" rel=""nofollow noreferrer"">https://imgur.com/kQoiJBB</a></p>

<p>Does not work</p>

<pre><code>import { expect } from 'chai'
import { shallowMount } from '@vue/test-utils'
import Tabs from '@/components/ui/Tabs.vue'

let wrapper = shallowMount(Tabs);
console.log(wrapper);
describe('Tabs.vue', () =&gt; {
  it('current tab equals empty', () =&gt; {
    // wrapper.vm.clearValue();
    expect(wrapper.vm.currentTab).to.equal('');
  });
});
</code></pre>

<p>Works</p>

<pre><code>import { expect } from 'chai'
import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () =&gt; {
  it('renders props.msg when passed', () =&gt; {
    const msg = 'new message'
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg }
    })
    expect(wrapper.text()).to.include(msg)
  })
})
</code></pre>

<p>Also tried the code examples here: <a href=""https://vuetifyjs.com/en/getting-started/unit-testing"" rel=""nofollow noreferrer"">https://vuetifyjs.com/en/getting-started/unit-testing</a>
They do not work also.</p>

<p>I expect the tests to actually run and either return success or failed. I actually get an error for each of the stylesheets using SASS.</p>
",https://stackoverflow.com/questions/57605747/having-issues-intergrating-unit-testing-into-an-active-vuetify-2-project-error,"['unit-testing', 'vue.js', 'vuetify.js']",412,False,2,0
Angular - How to test a method that returns an Observable&lt;boolean&gt;,"<p>I have a method that returns an Observable :</p>

<pre><code>public hasFiltersSelected(): Observable&lt;boolean&gt; {
return this.store.pipe(
  select(selectSelectedFilters),
  map(obj =&gt; Object.keys(obj).length &gt; 0)
);
</code></pre>

<p>}</p>

<p>Does anyone know how should I do the unit testing for this one ? tyvm</p>
",https://stackoverflow.com/questions/54524618/angular-how-to-test-a-method-that-returns-an-observableboolean,"['angular', 'unit-testing', 'ngrx', 'ngrx-store']",2327,True,0,1
how to write unit testing for modal or alert popup in ionic 4,"<p>I want to cover unit testing for alert controller popup and callback handler in ionic 4?</p>

<pre class=""lang-js prettyprint-override""><code>it('should open popup', () =&gt; {
  component.showAlertPopup();
  const popupElem = fixture.debugElement.queryAll(By.css('alert-inner-button'));
  console.log('popup element', popupElem);
});
</code></pre>

<pre class=""lang-js prettyprint-override""><code>async showAlertPopup() {
  const alertOpts: AlertOptions = {
    message: 'applied successfully',
    button: [{
      text: 'YES',
      handler: () =&gt; {
        this.router.navigateByUrl('app/home');
      }
    }]
  };
  const alert = await this.alertCtrl.create(alertOpts);
  console.log('alert', alert);
  alert.present();
}
</code></pre>

<p>I expected the popup element but it is undefined.</p>
",https://stackoverflow.com/questions/57772546/how-to-write-unit-testing-for-modal-or-alert-popup-in-ionic-4,"['unit-testing', 'angular7', 'ionic4']",508,False,3,0
How to check which option is selected in mat-select angular 8 unit testing,"<pre><code>it( 'Should set the initial value for test dropdown', async () =&gt; {
    let testDropdown : HTMLElement;
    const debugElement : DebugElement = fixture.debugElement;
    fixture.detectChanges();
    testDropdown = debugElement.queryAll( By.css( 'mat-select' ) )[ 0 ].nativeElement;
    expect( testDropdown ).toBeTruthy();
// How to get the selected value from the mat-select, like below code, which is not working
    console.log( testDropdown.children[ 0 ].innerHTML ); 
} );
</code></pre>

<p>In the HTML template, I am setting the default value for mat-select while looping options. How to get that selected value in unit testing</p>
",https://stackoverflow.com/questions/57451260/how-to-check-which-option-is-selected-in-mat-select-angular-8-unit-testing,"['angular', 'unit-testing', 'typescript2.0']",6119,False,3,2
How much should I isolate my method for unit testing?,"<p>I have the following method:</p>

<pre><code>public &lt; V extends U &gt; boolean matchesObject (V object, String filter) {

    if (filterIsAny(filter)) return true;

    else {

        List&lt;T&gt; targets = getFilterTarget(object);

        for (T t : targets) if (matches(t, filter)) return true;
        return false;

    }

}
</code></pre>

<p>where filterIsAny(filter) is a trivial method (just checks filter != null). </p>

<p>My question is: when I'm unit testing, is it worth to mock this method so that I'm sure that my function follows the correct path in the function, or do I just assume that my filterIsAny(filter) works and test using the real method? In this particular case, it is pretty easy to mock this method, but I have other instances where it would take several lines of code to mock intermediate results returned by trivial functions, such as list.indexOf(object) in a list of mocked objects.</p>

<p>I know it wouldn't be ""pure"" unit testing, since theoretically I'd be testing more than one function at a time, but how is is worth doing pure unit testing when it takes more work than finding the error in the code in the case of the test failing?</p>
",https://stackoverflow.com/questions/56985546/how-much-should-i-isolate-my-method-for-unit-testing,"['java', 'unit-testing', 'testing', 'junit', 'mocking']",177,True,1,1
How to transfer a &quot;Origin/master&quot; branch to a local branch?,"<p>I move the ""<code>Origin/master</code>"" branch down to ""unit-testing"". How can I do it?</p>

<p>This is a screnshot so you can see it:</p>

<p><a href=""https://i.stack.imgur.com/WRTYs.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/WRTYs.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/55610979/how-to-transfer-a-origin-master-branch-to-a-local-branch,"['git', 'devops']",85,False,0,0
ImportError: cannot import name &#39;myClass&#39; from &#39;myModule&#39;: where did I mess up?,"<p>I'm trying to get into unit testing with Python, of which I'm severely out of practice, and I'm running into issues with importing.</p>

<p>It's been a long, long time since I did Python and I'm trying to get into unit testing too. I've mostly been working with bash until recently so I may have overlooked something. It's on Python 3 but I think the version ultimately doesn't matter. Only going to show relevant code.</p>

<pre><code>Directory structure:
myProject/
|
\keter/
|    |-keter.py
|    |-__init__.py
|
\tests/
|    |- test_first.py
</code></pre>

<p>in keter.py</p>

<pre><code>import os
import zipfile
import re
import xml.dom.minidom
class Converter:
    def my_function(params):
        #do stuff
</code></pre>

<p>in test_first.py</p>

<pre><code>import unittest
import sys
sys.path.append('../')
from keter import Converter

class TestConverter(unittest.TestCase):

    def test_instantiate(self):
        my_converter = Converter()
        self.assertIsInstance(my_converter,Converter)
</code></pre>

<p>On attempting to run the test...</p>

<pre><code>$ python -m unittest discover
E
======================================================================
ERROR: test_first (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_first
Traceback (most recent call last):
  File ""path_to_python\lib\unittest\loader.py"", line 436, in _find_test_path
    module = self._get_module_from_name(name)
  File ""path_to_python\lib\unittest\loader.py"", line 377, in _get_module_from_name
    __import__(name)
  File ""path_to_project\tests\test_first.py"", line 5, in &lt;module&gt;
    from keter import Converter
ImportError: cannot import name 'Converter' from 'keter' (..\keter\__init__.py)


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
</code></pre>
",https://stackoverflow.com/questions/57351466/importerror-cannot-import-name-myclass-from-mymodule-where-did-i-mess-up,['python'],259,False,1,1
I need help in unit testing. for the code. I want to cover this code in angular spec file by writing unit test,"<p>I need help in unit testing. for the code. I want to cover this code in angular spec file by writing unit test</p>

<pre><code>loadRefreshStatus(apiUrl, actionItemParam, httpGetOptions): void {

    for (const val of actionItemParam) {
      for (const inventory of this.inventory) {
        if (val.SID === inventory.SID) {
          inventory.Status = 'Refreshing';
          this.loadSucceeded(this.inventory);
        }
      }
      this.http.get(apiUrl + '/' + val.ProviderId + '/' + val.SID + '/info', httpGetOptions).map(data =&gt; data).subscribe(data =&gt; {
        const resData = data;
        for (const inventory of this.inventory) {
          if (resData.SID === inventory.SID) {
            inventory.Status = resData.status;
            //Delux table is losing context here and hence change detation is not working.
            //Ensuring that delux table gets the context back
            const dt = document.getElementById('inventory-listing_carbon-data-table-deluxe'); //ID of delux data table
            dt.click(); //restoring context back
            this.loadSucceeded(this.inventory);
          }
        }
      },
      errresourceData =&gt; {
        this.handleError(errresourceData)
      });
    }
  }
</code></pre>
",https://stackoverflow.com/questions/55669056/i-need-help-in-unit-testing-for-the-code-i-want-to-cover-this-code-in-angular,"['angular', 'unit-testing', 'karma-jasmine']",31,False,0,0
How do I unit test canActivate of Angular for authguard?,"<p>How do I perform unit testing for auth guard?</p>

<p>I don't know how to start, can anyone please help me?</p>

<p>This is my authguard.component:</p>

<pre><code>import { Injectable } from '@angular/core';
import {
  Router,
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';

import { LoginService } from '../services/login/login.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router, private loginService: LoginService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const currentUser = this.loginService.currentUserValue;
    if (currentUser) {
      // Authorized so return true
      return !0;
    }

    // not authorized so redirect to signin page with the return url
    this.router.navigate(['/login'], {
      queryParams: { returnUrl: state.url }
    });
    return !1;
  }
}
</code></pre>
",https://stackoverflow.com/questions/55235627/how-do-i-unit-test-canactivate-of-angular-for-authguard,"['angular', 'unit-testing']",2042,False,1,1
Running an In-Memory Sandboxed Neo4J Database for NodeJS Unit Testing,"<p>Is there a way to spin up small in-memory Neo4J database instances for use when unit testing NodeJS code? I am currently using Jest.</p>
",https://stackoverflow.com/questions/58356178/running-an-in-memory-sandboxed-neo4j-database-for-nodejs-unit-testing,"['javascript', 'node.js', 'unit-testing', 'neo4j', 'jestjs']",193,True,2,1
How to mock IHttpClientFactory using typed clients,"<p>I am trying to properly add <code>HttpClient</code> in my app while also allowing for mocking away the client factory for unit testing purposes. I am using <a href=""https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2#typed-clients"" rel=""nofollow noreferrer"">this</a> as as resource.</p>

<p>In my <strong>Startup.cs</strong></p>

<pre><code>services.AddHttpClient&lt;IUploader, Uploader&gt;()
    .ConfigurePrimaryHttpMessageHandler(() =&gt;
    {
        if (somecheckismet)
            return new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } };
        return new HttpClientHandler();
    });
</code></pre>

<p>And my <strong>Uploader.cs</strong></p>

<pre><code>public class Uploader : IUploader
{
    private readonly HttpClient m_httpClient;

    public Uploader(HttpClient client)
    {
        m_httpClient = client;
    }

    public async Task&lt;string&gt; UploadData(string url, Dictionary&lt;string, string&gt; data)
    {
        HttpResponseMessage result;
        try
        {
            result = await m_httpClient.PostAsync(url, new FormUrlEncodedContent(data));
            if (result.StatusCode != HttpStatusCode.OK)
            {
                return ""Some error message;
            }
            else
            {
                return null; // Success!
            }
        }
        catch (Exception ex)
        {
            return ""Uh-oh!"";
        }
    }
}
</code></pre>

<p>As you can see I am trying to dependency inject <code>HttpClient</code> into the <code>Uploader</code>. However, now that I've done this, how do I go about unit testing the <code>Uploader</code>? Previously, it would have worked to dependency inject <code>HttpClientHandler</code> which can be mocked away. However, now since I am trying to use <code>IHttpClientFactory</code>, it seems that I have to inject <code>HttpClient</code>.</p>

<p>Any help would be greatly appreciated.</p>
",https://stackoverflow.com/questions/56634201/how-to-mock-ihttpclientfactory-using-typed-clients,"['c#', '.net-core', 'dotnet-httpclient']",2696,False,2,2
Most RESTFUL API functions cannot be unit-tested,"<pre><code>postAdmin(req, res, cb) {
    const admin = await Admin.findOne({ req.body.username });

    if (!admin) {
        error(""Admin doesn't exist"");
    } //split here? adminValidationDAO();

    const isMatch = await bcrypt.compare(password, user.password);

    if(!isMatch){
        error(""Wrong password"");
    } //split here? passwordValidationDAO();
    const email = new Email ({
        text: req.body.text,
        title: req.body.title,
    });
    const response = await email.save();
    //split here? saveResponseDAO()?
}
</code></pre>

<blockquote>
  <p>Unit testing is the practice of testing small pieces of code,
  typically individual functions, alone and isolated. If your test uses
  some <strong>external resource, like the network or a database, it’s not a
  unit test.</strong></p>
</blockquote>

<p>I was thinking of testing the code I have above, but I realized after doing some research about unit testing that what I thought was unit testing was integration testing. Testing the whole chunk of code inside postAdmin would be integration testing. Then I was wondering if I could divide the code inside postAdmin into three chunks and make them unit testable, but here are the following issues:</p>

<p>The first one makes a database call with findOne().</p>

<p>The second one relies on a library, isn't that an external resource?</p>

<p>The third one makes a database call with save().</p>

<p>So would you agree that there's nothing that can be unit tested?</p>
",https://stackoverflow.com/questions/58896849/most-restful-api-functions-cannot-be-unit-tested,"['node.js', 'unit-testing', 'tdd']",57,True,0,2
using @InjectMocks outside @Before,"<p>I'm creating the base for my unit testing project( Spring boot rest controller) and I'm having a problem passing @InjectMocks value because it's only evaluated in @Before and therefore a nullpointer is thrown when i try to access it outside</p>

<p>Some tips to get around the problem please?<br>
Thank you very much</p>

<p>Ps : Any other advices on best practices or something i did wrong for unit testing regarding my current base class test will be appreciated as well</p>

<p>Class to test (rest controller)</p>

<pre><code>@RestController
@RequestMapping(""/management"")
@Api(description = ""Users count connections"", produces = ""application/json"", tags = {""ConnectionManagement API""})
public class ConnectionManagementControllerImpl implements ConnectionManagementController {

    @Autowired
    private ConnectionManagementBusinessService connectionManagementBusinessService;

    @Override
    @PostMapping(value = ""/countConnectionsByInterval"" , consumes = MediaType.TEXT_PLAIN_VALUE , produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = ""count all users connections by interval"")
    public ResponseEntity&lt;List&lt;ConnectionsCountDto&gt;&gt; countConnectionsByInterval(@RequestBody String format) {
        List&lt;ConnectionsCountDto&gt; connectionManagement = connectionManagementBusinessService.countConnectionsByInterval(format);
        return  new ResponseEntity&lt;List&lt;ConnectionsCountDto&gt;&gt;(connectionManagement, HttpStatus.OK);
    }
</code></pre>

<p>Abstract base test</p>

<pre><code>public abstract class AbstractBaseTest&lt;C&gt; {

     public MockMvc mockMvc;

     private Class&lt;C&gt; clazz;

     private Object inject;

     protected abstract String getURL();

     protected final void setTestClass(final Class&lt;C&gt; classToSet, final Object injectToSet) {
         clazz = Preconditions.checkNotNull(classToSet);
         inject = Preconditions.checkNotNull(injectToSet);
     }

    @Before
    public void init() throws Exception {
        MockitoAnnotations.initMocks(clazz);
        mockMvc = MockMvcBuilders.standaloneSetup(inject).build();
    }

    protected MockHttpServletResponse getResponse(MediaType produces) throws Exception {
        MockHttpServletResponse response = mockMvc.perform(
                get(getURL()).
                accept(produces)).
                andReturn().
                getResponse();
        return response;
    }

    protected MockHttpServletResponse postResponse(String content , MediaType consumes , MediaType produces) throws Exception {
        MockHttpServletResponse response = mockMvc.perform(
                post(getURL()).
                content(content).
                contentType(consumes).
                accept(produces)).
                andReturn().
                getResponse();
        return response;
    }
}
</code></pre>

<p>Test class</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class ConnectionManagementControllerImplTest extends AbstractBaseTest&lt;ConnectionManagementControllerImpl&gt;{

    @Mock
    private ConnectionManagementBusinessService connectionManagementBusinessServiceMocked;

    @InjectMocks
    private ConnectionManagementControllerImpl connectionManagementControllerMocked;

    public ConnectionManagementControllerImplTest() {
        super();            
        setTestClass(ConnectionManagementControllerImpl.class , connectionManagementControllerMocked); // null pointer there
    }

    @Test
    public void countConnectionsByInterval() throws Exception {

        // given
        given(connectionManagementBusinessServiceMocked.countConnectionsByInterval(Mockito.anyString()))
                .willReturn(new ArrayList&lt;ConnectionsCountDto&gt;());

        // when
        MockHttpServletResponse response = postResponse(""day"" , MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON_UTF8);

        // then
        assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());    
    }

    @Override
    protected String getURL() {
        return ""/management/countConnectionsByInterval"";
    }
</code></pre>
",https://stackoverflow.com/questions/55007125/using-injectmocks-outside-before,"['java', 'unit-testing', 'junit']",801,True,2,1
Issue importing CodeCoverage to SonarQube using Jenkins Pipeline,"<p>Cannot upload the CodeCoverage result to SonarQube. The Unit Tests appear (along the static analysis result) but codecoverage remains 0%</p>

<p>The Unit Testing is made in Jenkins and is successful according to the Jenkins Console but no coveragexml file is generated…</p>

<pre><code>pipeline {
  agent none
  stages{
    stage('Checkout'){
      agent {
        label 'Miguel'
      }
      steps {
        checkout scm
      }
    }

stage('Static Analysis'){
  agent {
    label 'Miguel'
  }
  steps {
    script {
      echo ""Starting Static Analysis Stage""
      def msbuild = tool name: 'MSBuildMiguel', type: 'hudson.plugins.msbuild.MsBuildInstallation'
      def sonarHome = tool 'MSBuildSonarScannerMiguel'
      def vstest = tool 'vstestMiguel'
      def codecoverage = tool 'codecoverageMiguel'
      withSonarQubeEnv('SonarQube'){
        bat """"""
          ${sonarHome}/SonarScanner.MSBuild.exe begin /k:com.SecurityUtilities /n:TTSecurity /v:1.0 /d:sonar.cs.vstest.reportsPaths=**/*.trx /d:sonar.cs.vscoveragexml.reportsPaths=**/*.coveragexml
          ${msbuild} TTSecurity.sln /t:Rebuild
          ${vstest} /Logger:trx ""TTSecurityTests\\bin\\Release\\TTSecurityTests.dll"" 

          ${codecoverage} analyze /output:d:**.coveragexml  d:**.coverage

          ${sonarHome}/SonarScanner.MSBuild.exe end
        """"""
      }
    }
  }
}
</code></pre>

<p>}
}</p>

<p>The Unit Testing is done:</p>

<p>Starting test execution, please wait...
(...)
Results File: C:\Users\FNM1AV\Desktop\JenkinsSlave\workspace\Security_Utilities_master\TestResults\FNM1AV_PT-N01504_2019-09-10_22_47_24.trx</p>

<p>Test Run Successful.
Total tests: 18
     Passed: 18
 Total time: 1.8712 Seconds</p>

<p>The Jenkins Console shows: </p>

<p>""WARN: Could not find any coverage report file matching the pattern '**/*.coveragexml'.""</p>
",https://stackoverflow.com/questions/57892410/issue-importing-codecoverage-to-sonarqube-using-jenkins-pipeline,"['c#', 'sonarqube', 'jenkins-pipeline', 'code-coverage']",270,False,1,0
How to implement a basic unit test in javascript for an azure durable function orchestration,"<p>What would be the unit test which would fake the calls to callActivity in the orchestrator below to return a known value and to expect that the orchestrator returns that value.</p>

<p>The examples on the azure durable functions documentation for unit testing[1] are all written in C# and I've not been able to replicate 
them in javascript despite several attempts. This is because I don't know how to construct an orchestrator with a fake context.</p>

<pre><code>  const df = require('durable-functions');

  module.exports = df.orchestrator(function* orchestratorFunctionGenerator(context) {
    const input = context.df.getInput();
    const apimApiName = input.apimApiName;
    const indexNames = yield context.df.callActivity('GetIndexNames', apimApiName);
    const indexerName = indexNames.idle;
    const indexerStatus = yield context.df.callActivity('GetIndexerStatus', indexerName);
    return indexerStatus;
  });
</code></pre>

<p>[1] <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>
",https://stackoverflow.com/questions/54863516/how-to-implement-a-basic-unit-test-in-javascript-for-an-azure-durable-function-o,"['javascript', 'unit-testing', 'azure-durable-functions']",995,True,1,1
I have a problem in the unit test of spring + testng + mockito + powermock,"<p>I am unit testing the controller of the spring project, the controller code is as follows::</p>

<pre><code>package app.dnatask.controller;

import ...

@Slf4j
@RestController
@RequestMapping(value = ""/API/scanresultconfigure"")

public class ScanResultConfigureController extends BaseController {
    @Autowired
    private ScanResultConfigureService scanResultConfigureService;

    @RequestMapping(value = ""/queryScanResultList/{taskId}/{externalname}"", method = RequestMethod.POST)
    public IBaseResult queryscanResultList(final HttpServletRequest request, @PathVariable final String taskId, @PathVariable final String externalname, @RequestBody Map map) throws Exception {
        return runController(new IControllRunner() {
            public void run(IOutResult or, CheckResult cr) throws Exception {
                Pageable p = getPageableFromRequest(map, ""glt_msg"", null);
                List list = scanResultConfigureService.findtitleConfigure(taskId, externalname, map);
                ......
            }
        }
    }
}
</code></pre>

<p>I used testng + mockito + powermock to unit test the controller.Because the controller extends BaseController (the code is as follows), when executing <code>Pageable p = getPageableFromRequest (map, ""glt_msg"", null);</code> NullPointerException will be reported.</p>

<p>BaseController::</p>

<pre><code>package app.frame.vendor.spring.springmvc.common.usercontext;

import ...

public abstract class BaseController extends BaseController_Web {
    public BaseController() {
    }

    protected Pageable getPageableFromRequest(Map map, String gltName, Sort sort) {
        ...
        return pageable;
    }
}
</code></pre>

<p>The test class is as follows::</p>

<pre><code>package app.dnatask.controller;

import ...

@WebAppConfiguration
@ContextConfiguration(classes = {ScanResultConfigureController.class})
@ComponentScan(
        excludeFilters = {
                @ComponentScan.Filter(type = FilterType.ANNOTATION, value = {
                        ComponentScan.class, Configuration.class, ImportResource.class
                })
        },
        useDefaultFilters = false,
        lazyInit = true
)
@EnableWebMvc
@PrepareForTest(BaseController.class)

public class ScanResultConfigureControllerTest extends AbstractTestNGSpringContextTests {
    @MockBean(answer = Answers.RETURNS_DEEP_STUBS)
    private ScanResultConfigureService scanResultConfigureService;

    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;

    @BeforeMethod
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).dispatchOptions(true).build();
    }

     @Test
    public void testQueryscanResultList() throws Exception {
        PowerMockito.mock(BaseController.class);
        when(BaseController.getPageableFromRequest).thenReturn(Pageable);

        Map&lt;String, String&gt; testMap = new HashMap&lt;&gt;();
        testMap.put(""key1"", ""value1"");
        testMap.put(""key2"", ""value2"");
        String requestJson = JSONObject.toJSONString(testMap);
        List testList = new ArrayList();
        testList.add(""test1"");
        testList.add(""test2"");

        when(scanResultConfigureService.findtitleConfigure(anyString(), anyString(), anyMap())).thenReturn(testList);

        MvcResult mvcResult = mockMvc.perform(
                post(""/API/scanresultconfigure/queryScanResultList/{taskId}/{externalname}"", ""123"", ""abc"")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(requestJson)
        )
                .andExpect(status().isOk())
                .andDo(print())
                .andReturn();
    }
}
</code></pre>

<blockquote>
  <p>The question I am confused about is :: how do I handle the <code>getPageableFromRequest</code> method of <code>BaseController</code> in that unit test.As we all know,the TestNG need to extends <code>AbstractTestNGSpringContextTests</code> and the PowerMock need to extends <code>PowerMockTestCase</code>. How should I combine these two tools for unit testing in spring projects</p>
</blockquote>
",https://stackoverflow.com/questions/59483241/i-have-a-problem-in-the-unit-test-of-spring-testng-mockito-powermock,"['spring', 'unit-testing', 'testng', 'powermock']",151,True,1,1
Unit testing python data types - test failed &quot;Expected :NaT Actual:NaT&quot;,"<p>I am introducing unit-testing my python data pipeline using <code>unittest</code> module.  </p>

<p>Data class object example:</p>

<pre class=""lang-py prettyprint-override""><code>class IsAvailable(Object)
    employee_id: int = Property()
    start_time: str = Property()
</code></pre>

<p>Unit test case:</p>

<pre class=""lang-py prettyprint-override""><code>class TestIsAvailable(TestCase):
    def setUp(self):
        self.employee = pd.read_json('employee_leave.json', orient='records')
        self.isAvailable = IsAvailable()
        self.isAvailable.id = self.employee['start_time'][0]
</code></pre>

<pre class=""lang-py prettyprint-override""><code>    def test_is_available_all_day_001(self):
        assert self.isAvailable.start_time == pd.NaT
</code></pre>

<p>test result:</p>

<pre class=""lang-py prettyprint-override""><code>self = &lt;tests.test_nodes.TestIsAvailable testMethod=test_is_available_all_day_001&gt;

    def test_is_available_all_day_001(self):
        """"""test employee is available all day on specific day of the week""""""
&gt;       assert self.isAvailable.start_time == pd.NaT
E       AssertionError: assert NaT == NaT
E        +  where NaT = &lt;IsAvailable id=1&gt;.start_time
E        +    where &lt;IsAvailable id=1&gt; = &lt;tests.test_nodes.TestIsAvailable testMethod=test_is_available_all_day_001&gt;.isAvailable
E        +  and   NaT = pd.NaT

</code></pre>

<p>How do you test data types?</p>
",https://stackoverflow.com/questions/57343061/unit-testing-python-data-types-test-failed-expected-nat-actualnat,"['python', 'unit-testing', 'python-unittest']",148,False,1,1
How do I use PHPUnit to test a Controller under ZFC RBAC,"<p>I am pretty new to unit testing and have just started my journey learning how to use tests to make my applications more reliable.</p>

<p>I am using Zend Framework 3 and am following this guide <a href=""https://docs.zendframework.com/tutorials/unit-testing/"" rel=""nofollow noreferrer"">https://docs.zendframework.com/tutorials/unit-testing/</a></p>

<p>What I want to do is test a route that requires a user to be Authenticated and have the correct ZFR Rbac role.</p>

<pre><code>   public function testOverviewActionCanBeAccessed()
   {
    //Setup a mock user
    $user = $this-&gt;createMock(User::class);
    $user-&gt;method('getRoles')-&gt;willReturn(['admin']);

    //Setup the mock auth identity interface
    $identity = $this-&gt;createMock('Zend\Authentication\AuthenticationService');
    $identity-&gt;method('getIdentity')
        -&gt;willReturn($user);


    //Run the following test

    $this-&gt;dispatch('/cp/overview');
    $this-&gt;assertResponseStatusCode(200);
    $this-&gt;assertModuleName('ControlPanel');
    $this-&gt;assertControllerName(AgentController::class);
    $this-&gt;assertControllerClass('AgentController');
    $this-&gt;assertMatchedRouteName('cp/overview');
}
</code></pre>

<p>At the moment when I run the test I get the following error:</p>

<pre><code>PHPUnit 6.2.4 by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)

Time: 1.27 seconds, Memory: 16.00MB

There was 1 failure:

1) ControlPanelTest\Controller\AgentControllerTest::testOverviewActionCanBeAccessed
Failed asserting response code ""200"", actual status code is ""302""

Exceptions raised:
Exception 'ZfcRbac\Exception\UnauthorizedException' with message 'You are not authorized to access this resource' in /var/www//public_html/application/vendor/zf-commons/zfc-rbac/src/ZfcRbac/Guard/AbstractGuard.php:66

/var/www//public_html/application/vendor/zendframework/zend-test/src/PHPUnit/Controller/AbstractControllerTestCase.php:482
/var/www/public_html/application/module/ControlPanel/test/Controller/AgentControllerTest.php:40
</code></pre>

<p>So my question is how do I setup RBAC in the test?</p>
",https://stackoverflow.com/questions/54029276/how-do-i-use-phpunit-to-test-a-controller-under-zfc-rbac,"['zend-framework3', 'phpunit', 'zend-test', 'zfc-rbac']",162,True,0,1
How to test a method with TokenSource cancellation?,"<p>I have a problems with unit testing of a method with TokenSource cancellation.</p>

<p>SUT method is very simple:</p>

<pre><code>public void OnTaskCancellationExecute(object obj)
        {
            TaskCancellation = true;

            TokenSource.Cancel();

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

<p>And is called by command execution:</p>

<p><code>TaskCancellationCommand = new DelegateCommand(OnTaskCancellationExecute);</code></p>

<p><code>CommandCompletedControlsSetup</code> method, that is executed after <code>TokenSource</code> is cancelled, contains: </p>

<p><code>TaskCancellation = false;</code></p>

<p>My test method:</p>

<pre><code>[Fact]
    public void OnTaskCancellationExecute_CancelTask_True()
    {
        _viewModel.TaskCancellation = false;
        _viewModel.TokenSource = new CancellationTokenSource();

        _viewModel.TaskCancellationCommand.Execute(null);

        Assert.True(_viewModel.TaskCancellation);
    }
</code></pre>

<p>Cancellation of all Tasks with <code>TokenSource</code> in SUT takes a while in running solution. But not in unit testing. How should I <code>Assert</code>, that <code>_viewModel.TaskCancellation</code> was <code>true</code>, before was changed again to <code>false</code> after <code>CommandCompletedControlsSetup</code> was called in tested method? Or it is kind of problem with my architecture? Should I create some Tasks in test method and attach the SUT tokens somehow?</p>
",https://stackoverflow.com/questions/56608906/how-to-test-a-method-with-tokensource-cancellation,"['c#', 'wpf', 'mvvm', 'xunit', 'cancellationtokensource']",462,True,0,1
How can I define a single pandas Interval?,"<p>For unit testing I need a single interval. However usually one uses <a href=""https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.IntervalIndex.html#pandas.IntervalIndex"" rel=""nofollow noreferrer""><code>interval_range()</code>, <code>from_arrays()</code>, <code>from_tuples()</code>, <code>from_breaks()</code> </a> to construct a new <code>IntervalIndex</code> containing several intervals. How can I get a single interval index?</p>
",https://stackoverflow.com/questions/58980283/how-can-i-define-a-single-pandas-interval,"['pandas', 'dataframe']",218,True,1,3
"How to Unit Test private methods that update a database, without actually updating the database - in a WinForms VB.Net legacy code app?","<p>I've started working on a legacy code (i.e. no unit tests) Windows Forms app written in VB.Net and I've been asked to start introducing unit tests as I make changes. I have not done much unit testing before and I am unsure how to test a recurring pattern I see in the methods. Here is my attempt to outline a simplified typical example:</p>

<pre><code>Private Sub cmdButton_Click(ByVal eventSender As Object, ByVal eventArgs As EventArgs) Handles cmdAprv.Click

    'The event is Private and it then calls multiple other private methods
    'but I will simplify drastically for this example:
    If &lt;conditions&gt; Then
        InsertEmployee()
    End If

End Sub

Private Function InsertEmployee() As Integer

    'Typically, the functions are quite long with lot of code initializing 
    'variables, but I will simplify drastically for this example:
    Dim _name As String = ""[]""
    Dim _departmenmt As String = ""Engineering""
    Dim _salary As Double = 2000

    'Then at the end there may be multiple database updates like this one:

    Dim connectionString As String = ""&lt;Call a Function to get ConnectionString details&gt;""
    Using conn As New SqlConnection(connectionString)
        Using cmd As New SqlCommand(""INSERT INTO Employees (Name, Department, Salary) VALUES (@Name, @Department, @Salary)"", conn)
            cmd.CommandType = CommandType.Text
            cmd.Parameters.AddWithValue(""@Name"", _name)
            cmd.Parameters.AddWithValue(""@City"", _departmenmt)
            cmd.Parameters.AddWithValue(""@City"", _salary)
            conn.Open()
            Dim i As Integer = cmd.ExecuteNonQuery()
            conn.Close()
            Return i
        End Using
    End Using

End Function
</code></pre>

<ol>
<li><p>There is a <em>lot</em> of code in Private methods like this. To make these methods accessible to the testing project, I reckon I can downgrade the Function's accessibility protection from Private to Friend (VB.Net “Friend” = C# “internal” access modifier) and then use <code>InternalsVisibleTo</code> Attribute to mark the unit testing assembly as a friend assembly.</p></li>
<li><p>But I’m really not sure what to do with the Database <code>INSERT</code> or <code>UPDATE</code> code to make the function testable? One requirement I have is that <strong>the Unit Tests must not actually modify the database</strong>. </p></li>
</ol>

<p>Can anyone show me a good example of refactoring a method like this for unit testing?</p>
",https://stackoverflow.com/questions/59092750/how-to-unit-test-private-methods-that-update-a-database-without-actually-updati,"['database', 'vb.net', 'winforms', 'unit-testing', 'refactoring']",150,True,0,1
ld: framework not found Pods_MyProject_MyProjectTests,"<p>Trying to do some unit testing with Firebase, but I'm having compiler problems. When I try to run a test, I get the following error:</p>

<pre><code>ld: framework not found Pods_MyProject_MyProjectTests
</code></pre>

<p>Pod:</p>

<pre><code>platform :ios, '11.0'

target 'MyProject' do
  use_frameworks!

# ignore all warnings from all pods
inhibit_all_warnings!

# Pods for MyProject
pod 'CoreXLSX'
pod 'Eureka'
pod 'Firebase/Firestore'
pod 'Firebase/Auth'
pod 'ProgressHUD'
pod 'GoogleSignIn'
pod 'SteviaLayout'

target 'MyProjectTests' do
  inherit! :search_paths
  # Pods for testing
  end

target 'MyProjectUITests' do
  inherit! :search_paths
  # Pods for testing
  end

end
</code></pre>
",https://stackoverflow.com/questions/57831931/ld-framework-not-found-pods-myproject-myprojecttests,"['ios', 'swift', 'xcode', 'firebase', 'cocoapods']",76,True,0,1
Angular Unit Tests : &#39;mat-nav-list&#39; is not a known element,"<p>I'm currently working on a legacy Angular 5 code that doesn't have any unit testing except the default ones when generating a component using the Angular CLI.</p>

<p>The project is using Angular Material 5 RC0 and it seems that the unit tests doesn't take into account my module's dependencies.</p>

<p><strong>app.module.ts :</strong></p>

<pre><code>@NgModule({
  declarations: [
    AppComponent,
    /* My module components... */
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    routing,
    DialogsModule,
    SharedModule ,
    MaterialModule,
    MatListModule, // It's the module that should be needed
    MatSidenavModule,
    ToastrModule.forRoot({
      timeOut: 5000,
      positionClass: 'toast-bottom-right',
      preventDuplicates: true
    }),
    HttpClientModule,
    TableFactoryModule
  ],
  providers: [
    /* My module services */,
    AuthGuard
  ],
  bootstrap: [AppComponent]

})
export class AppModule {

}
</code></pre>

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

<pre><code>import { Component, Input, ViewChild } from '@angular/core';
import { Router, RouterModule, ActivatedRoute } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import { JwtHelperService } from '@auth0/angular-jwt';
import * as _ from 'lodash';

import { Subscription } from 'rxjs/Subscription';
import { ToastrService } from 'ngx-toastr';

import { UsersService } from 'app/services/users.service';
import { ComplexesService } from 'app/services/complexes.service';
import { ActivatedUserService } from 'app/shared/activateduser.service';
import { ActivatedComplexesService } from 'app/shared/activatedcomplexes.service';

import { User } from 'app/user';
import { Complex } from './complex/complex'
import { MatSidenav } from '@angular/material';
import { MatList } from '@angular/material/list'


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  isConnected = false;
  private subscription;
  private currentUser: User;
  userSubscription: Subscription;
  complexesSubscription: Subscription;
  @ViewChild(MatSidenav) sidenav: MatSidenav;

  constructor(
    private usersService: UsersService,
    private complexesService: ComplexesService,
    private router: Router,
    private toastr: ToastrService,
    private activatedUser: ActivatedUserService,
    private activatedComplexes: ActivatedComplexesService,
  ){
  }
  ngOnInit() {
    let getToken = this.usersService.isConnected();
    if (getToken) {
      this.getComplexes();
      this.userGetById();      
    }
    else
      this.router.navigate(['']);

    this.userSubscription = this.activatedUser.activatedUser$
    .subscribe(user =&gt; {
      if(user) {
        this.currentUser = user;
        this.sidenav.open();
      }
    });
  }
  logout(){
    this.usersService.logout();
    this.isConnected = this.usersService.isConnected();
    this.router.navigate(['']);
  }
  ngOnDestroy() {
    this.userSubscription.unsubscribe();
    this.complexesSubscription.unsubscribe();    
  }

  private userGetById(){
    let token = JSON.parse(localStorage.getItem('futbakCurrentUser'));
    let jwtHelperService: JwtHelperService = new JwtHelperService({});
    let currentUser = jwtHelperService.decodeToken(token);
    this.usersService.getByID(currentUser.id).subscribe(
      (res) =&gt; {
        this.currentUser = res
      }, (err: HttpErrorResponse) =&gt; {
        if (err.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          this.toastr.error(""Une erreur est survenue : ""+err.error.message  , '', { closeButton: true });
        } else {
          this.toastr.error(""Une erreur est survenue code : ""+ err.status+"", message : ""+err.statusText, '', { closeButton: true });
        }
      },
      () =&gt; {
        if(this.currentUser.role == 'superadmin' || this.currentUser.role == 'complexmanager') {
          this.activatedUser._activatedUser$.next(this.currentUser)
        }
        if(this.currentUser.role == 'superadmin') {
          this.router.navigate(['usersList']);
          this.getComplexes();
        } else if (this.currentUser.role == 'complexmanager') {
          this.router.navigate(['admins/'+this.currentUser._id])
        } else {
          this.toastr.error(""Vous n'avez pas les droits pour accèder à l'application."",'',{closeButton :true});
        }
      });
  }

  private getComplexes(){
   return this.complexesService.get()
    .subscribe(
      res =&gt; {
        if(res)
          this.activatedComplexes._activatedComplexes$.next(res)
    }, (err: HttpErrorResponse) =&gt; {
        if (err.error instanceof Error) {
          this.toastr.error(""Une erreur est survenue : ""+err.error.message  , '', { closeButton: true });
        } else {
          this.toastr.error(""Une erreur est survenue code : ""+ err.status+"", message : ""+err.statusText, '', { closeButton: true });       
        }
      },
      () =&gt; {
      });
  }

 }
</code></pre>

<p><strong>The failing test :</strong></p>

<pre><code>it('should create the app', async(() =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
</code></pre>

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

<pre><code>&lt;mat-sidenav-container fullscreen &gt;

  &lt;mat-sidenav #sidenav mode=""side"" disableClose&gt;
    &lt;!-- sidenav content --&gt;

    &lt;div&gt;&lt;img src=""./assets/logo.png"" class=""logo"" &gt;&lt;/div&gt;
    &lt;div class=""title-app""&gt;
      &lt;h2&gt;Admin&lt;/h2&gt;
    &lt;/div&gt;

    &lt;mat-nav-list&gt;
      &lt;a mat-list-item routerLinkActive=""active"" routerLink=""['usersList']""&gt;
        &lt;!-- &lt;mat-icon fontSet=""fa"" fontIcon=""fa-users"" &gt;&lt;/mat-icon&gt; --&gt;
        &lt;i class=""fa fa-users fa-fw fa-lg""&gt;&lt;/i&gt; Joueurs
      &lt;/a&gt;
      &lt;a mat-list-item routerLink=""['adminsList']""&gt;
        &lt;i class=""fa fa-user fa-fw fa-lg""&gt;&lt;/i&gt; Admins
      &lt;/a&gt;
      &lt;a mat-list-item routerLinkActive=""active"" routerLink=""['gamesList']""&gt;
          &lt;i class=""fa fa-futbol-o fa-fw fa-lg""&gt;&lt;/i&gt; Matchs
      &lt;/a&gt;
      &lt;a mat-list-item routerLinkActive=""active""  routerLink=""['playgroundsList']""&gt;
        &lt;i class=""fa fa-cubes fa-fw fa-lg""&gt;&lt;/i&gt; Terrains
      &lt;/a&gt;
      &lt;a mat-list-item routerLinkActive=""active"" routerLink=""['complexesList']""&gt;
        &lt;i class=""fa fa-cube fa-fw fa-lg""&gt;&lt;/i&gt; Complexes
      &lt;/a&gt;
      &lt;a mat-list-item routerLinkActive=""active"" routerLink=""['devicesList']""&gt;
        &lt;i class=""fa fa fa-share-alt fa-fw fa-lg""&gt;&lt;/i&gt; Capteurs
      &lt;/a&gt;
      &lt;a mat-list-item routerLinkActive=""active"" routerLink=""['experimental', 'playgrounds']""&gt;
        &lt;i class=""fa fa fa-share-alt fa-fw fa-lg""&gt;&lt;/i&gt; Business
      &lt;/a&gt;
      &lt;a mat-list-item routerLinkActive=""active"" routerLink=""['experimental', 'devices']""&gt;
        &lt;i class=""fa fa fa-share-alt fa-fw fa-lg""&gt;&lt;/i&gt; Technique
      &lt;/a&gt;
    &lt;/mat-nav-list&gt;
    &lt;mat-nav-list class=""account""&gt;
        &lt;button mat-button (click)=""logout()""&gt;&lt;i class=""fa fa-sign-out""&gt;&lt;/i&gt; Déconnexion&lt;/button&gt;
    &lt;/mat-nav-list&gt;

  &lt;/mat-sidenav&gt;
  &lt;div class=""main mat-typography""&gt;
    &lt;!-- primary content --&gt;
    &lt;router-outlet &gt;&lt;/router-outlet&gt;
  &lt;/div&gt;
&lt;/mat-sidenav-container&gt;
</code></pre>

<p>And finally, the error :</p>

<pre><code>Failed: Template parse errors:
'mat-nav-list' is not a known element:
1. If 'mat-nav-list' is an Angular component, then verify that it is part of this module.
2. If 'mat-nav-list' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (""
    &lt;/div&gt;

    [ERROR -&gt;]&lt;mat-nav-list&gt;
      &lt;a mat-list-item routerLinkActive=""active"" routerLink=""['usersList']""&gt;
       ""): ng:///DynamicTestModule/AppComponent.html@10:4
</code></pre>

<p>So, as you've seen, I've already tried those kind of solution :</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/52105095/angular-6-mat-button-toggle-is-not-a-known-element"">'mat-nav-item' is not a known element</a></li>
<li><a href=""https://stackoverflow.com/questions/52105095/angular-6-mat-button-toggle-is-not-a-known-element"">'mat-button-toggle' is not a known element</a></li>
</ul>

<p>and so on.</p>

<p>I only have this problem on the unit testing, the website is running properly.</p>
",https://stackoverflow.com/questions/56145278/angular-unit-tests-mat-nav-list-is-not-a-known-element,"['angular', 'typescript', 'unit-testing', 'dependencies', 'angular5']",2989,True,3,1
cannot get rid of date unit testing - javascript,"<p>I'm new to unit testing and I implementing a unit test for a function that returns date.</p>

<pre><code>const getLastHour = () =&gt; {
const date = new Date().getTime() - 3600000;
return date;
};
</code></pre>

<p>I made something like this but it deosn't work</p>

<pre><code>describe('getLastHour', () =&gt; {
        const getLastHour = mobileArticleService.__get__('getLastHour');
        const getTime = sinon.stub(2019052906);
        const Date = sinon.stub({ getTime });

        before(() =&gt; {
            mobileArticleService.__set__({
                Date,
                getTime,
            });
        });

        it('should return date with hours ', () =&gt; {
            expect(Date).to.be.called;
            expect(getTime).to.be.called;
        });
    });
</code></pre>
",https://stackoverflow.com/questions/56359325/cannot-get-rid-of-date-unit-testing-javascript,"['mocha.js', 'chai', 'sinon']",30,False,-1,1
How to use unittest to assert an assert?,"<p>Let's say I have this function:</p>

<pre><code>def to_upper(var):
    assert type(var) is str, 'The input for to_upper should be a string'
    return var.upper()
</code></pre>

<p>And a file for unit testing using <code>unittest</code>:</p>

<pre><code>class Test(unittest.TestCase):

    def test_1(self):
        -- Code here --


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

<p>How do I test that if I call <code>to_upper(9)</code> it throws an assertion error?</p>
",https://stackoverflow.com/questions/55578865/how-to-use-unittest-to-assert-an-assert,"['python', 'testing', 'assert', 'python-unittest']",60,False,0,2
Angular How to test &quot;new Subject&lt;void&gt;() &quot;,"<p>I'm new to Angular unit testing. I have used <code>new Subject&lt;void&gt;()</code> in my service , but I am unable to write jasmine code for it.</p>

<p><strong>service.ts file</strong></p>

<pre class=""lang-js prettyprint-override""><code>public _refreshNeeded = new Subject&lt;void&gt;();

get refreshNeeded() {
  console.log(this._refreshNeeded)
  return this._refreshNeeded;
}

getDetails() {
  return  this.httpClient.get&lt;Data[]&gt;(`${this.API_URL}`);
}

postDetails(user: Data, seqcode: any): Observable&lt;Data[]&gt;{
  return this.httpClient.post&lt;Data[]&gt;(`${this.API_URL}`, user).pipe(tap(()=&gt; {
      this._refreshNeeded.next()
  }));
}
</code></pre>

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

<pre class=""lang-js prettyprint-override""><code>ngOnInit() {
  this.corpTrustService._refreshNeeded.subscribe(() =&gt; {
    this.getDetails();
  });

  this.getDetails();
}
</code></pre>
",https://stackoverflow.com/questions/56007968/angular-how-to-test-new-subjectvoid,"['angular', 'karma-jasmine']",438,False,0,0
Do I need to implement try/catch expections for testing this method? Not really sure where to start?,"<p>I'm unit testing code for an application and I'm confused on how to test try/catch exceptions. What would be a good approach for testing this method? </p>

<pre><code>  public static Exception Create&lt;TException&gt;(string format, params object[] args) where TException : Exception
  {
      var type = typeof(TException);
      try
      {
          if (type == typeof(ArgumentOutOfRangeException))
          {
              return (TException)Activator.CreateInstance(type, String.Empty, String.Format(format, args));
          }

          if (type == typeof(ArgumentNullException))
          {
              var name = format;
              return (TException)Activator.CreateInstance(type, String.Empty, Constants.Strings.ValueCannotBeNull.FormatWith(name));
          }

          return (TException)Activator.CreateInstance(type, String.Format(format, args));
      }
      catch (MissingMethodException)
      {
          try
          {
              return (TException)Activator.CreateInstance(type);
          }
          catch (MissingMethodException ex)
          {
              return new Exception(ParameterlessConstructorMissing.FormatWith(type), ex);
          }
      }
  }
</code></pre>
",https://stackoverflow.com/questions/56259392/do-i-need-to-implement-try-catch-expections-for-testing-this-method-not-really,"['c#', 'unit-testing']",53,False,0,0
NullInjectorError: StaticInjectorError(DynamicTestModule)[ToastrService -&gt; InjectionToken ToastConfig]: in tslint angular 8,"<p>When i run the unit testing in angular 8 project, i found an error in ngx-toastr </p>

<blockquote>
  <p>NullInjectorError: StaticInjectorError(DynamicTestModule)[ToastrService -> InjectionToken ToastConfig]:</p>
</blockquote>

<p>And i imported the requierd modules in the spec.ts file, And also i declared forRoot() in app.module.ts</p>

<pre><code>  beforeEach(async(() =&gt; {
TestBed.configureTestingModule({
  imports: [MatTabsModule,
    ReactiveFormsModule,
    MatTooltipModule,
    HttpClientTestingModule,
    RouterTestingModule,
    ToastrModule
  ],
  declarations: [CommunicationComponent],
  providers: [
    ToastrService,
  ]
})
  .compileComponents();
</code></pre>

<p>}));</p>
",https://stackoverflow.com/questions/59190786/nullinjectorerror-staticinjectorerrordynamictestmoduletoastrservice-injec,"['angular', 'unit-testing', 'eslint', 'ngx-toastr']",16825,True,12,4
Unit testing services in Angular,"<p>I am new to unit testing in Angular. Is there any way other than this to write unit tests for this particular function? Thank you!</p>

<p>list-user.component.ts</p>

<pre><code>constructor(private auth: AuthenticationService, private router: Router, private dialog: MatDialog) { }

fetchOfficeInfoByManager() {
          this.auth.getUserbyLM().subscribe((data: User[]) =&gt; {
          this.usersource = new MatTableDataSource(data);
}

ngOnInit() {`
this.fetchOfficeInfoByManager();
}
</code></pre>

<p>list-user.component.spec.ts</p>

<pre><code>import { ListUserComponent } from './list-user.component';
import { AuthenticationService } from '../../shared/services/authentication.service';
import { Observable } from 'rxjs';
import { from } from 'rxjs'


describe ('ListUserComponent', () =&gt; {
    let component: ListUserComponent;
    let service: AuthenticationService;

    beforeEach(() =&gt; {
        service = new AuthenticationService(null, null);
        component = new ListUserComponent(service, null, null);
    });

    it('should get employees according to line manager', () =&gt; {
        let data = [];
        spyOn(service, 'getUserbyLM').and.callFake(() =&gt; {
            return from([ data ]);
        });

        component.fetchOfficeInfoByManager();
        expect(component.data).toBeTruthy();
    });
});
</code></pre>
",https://stackoverflow.com/questions/54500080/unit-testing-services-in-angular,"['angular', 'unit-testing']",117,True,2,1
How to do Jasmine unit test to a function?,"<p>I am very new to Typescript and Jasmine Unit testing.
I ran the code coverage, and I need to test this function. How do I do this?</p>

<pre><code> public amountValidator(formControl: AbstractControl): any {
    if (formControl.value) {
        const amount: number = CurrencyUtility.parseLocaleNumber(formControl.value);
        if (amount &gt; 0) {
            return undefined;
        } else if (amount &lt;= 0 || isNaN(amount)) {
            return { isInvalid: true };
        }

    }

    return { isRequired: true };
}
</code></pre>
",https://stackoverflow.com/questions/57839568/how-to-do-jasmine-unit-test-to-a-function,"['angular', 'typescript', 'karma-jasmine']",38,False,0,0
Good practices for unit-testing class hierarchies,"<p>What are common/widely accepted practices for unit testing class hierarchies? </p>

<p>I've tried to look for different questions that are related to this problem, but couldn't find comprehensive one.</p>

<p>Let's suppose there is a hierarchy under test.</p>

<pre><code>class Base 
{
        int base_internal() { return 10;}                

    public:
        int virtual do_f() { return 0; }

        int execute() {
            return do_f()*base_internal();
        }
};

class DerrivedA : public Base
{
        int a_specefic() { return 4; }

    public:
        int virtual do_f()  { return a_specefic(); }
};


class DerrivedB : public Base
{
        int b_specefic() { return 8; }

    public:
        int virtual do_f()  { return b_specefic(); }
};

</code></pre>

<p>Now for unit testing infrastructure I am thinking about two strategies here.</p>

<p><strong>Strategy 1.</strong>  Have ""tester"" class for each type, derive from appropriate class and do the testing</p>

<pre><code>class TestForBase : public Base {...};
class TestForDerrivedA : public DerrivedA {...};
class TestForDerrivedB : public DerrivedB {....};
</code></pre>

<p><strong>Strategy 2.</strong> Use ""concertized"" version of visitor design pattern, (which will have single TestVisitor), than modify each class under test with accept() method,  and do the testing inside visit() of Tester class</p>

<pre><code>class Base 
{
        void accept(Tester&amp; t);
        int base_internal();

    public:
        int virtual do_f();
        int execute();
};


class Derrived : public Base
{
        void accept(Tester&amp; t);
        int a_specefic();

    public:
        int virtual do_f();
};

struct Tester
{
        void visit(Base* b)  { ... };
        void visit(Derrived* d) { ... } ;
};

</code></pre>

<p>What are the other options?</p>
",https://stackoverflow.com/questions/55635830/good-practices-for-unit-testing-class-hierarchies,"['c++', 'unit-testing', 'testing', 'class-hierarchy']",394,False,2,0
What is the difference between Jest-vue and Vue-jest?,"<p>I am studying unit testing for quasar framework now.
But I have not clear about vue-jest and jest-vue.
Please help me what the difference is? thank you.</p>
",https://stackoverflow.com/questions/56316732/what-is-the-difference-between-jest-vue-and-vue-jest,"['vue.js', 'jestjs', 'babel-jest']",86,True,1,1
How to do unit testing on Image as input and output in python?,"<p>I am doing unit testing on object detection <a href=""https://stackoverflow.com/questions/54576667/how-can-i-correctly-classify-the-number-of-positive-bright-color-circles-and-n"">code</a> (accepted answer) in Python. I know that in unit testing, we basically put in test parameters to functions we have defined in our program and we enter the expected result. If the expected result is output, we get OK, otherwise, we will get an error.</p>

<p>So my problem is that my <strong>input</strong> is the <strong>Image</strong> and my <strong>output</strong> is the also an image (i.e. <strong>object detected in the image</strong>) and later on, the result is represented using the bar chart and the histogram with slider. <strong>How can I do unit testing on such data?</strong></p>

<p>So far, this is what I have tried (This <a href=""https://stackoverflow.com/questions/54576667/how-can-i-correctly-classify-the-number-of-positive-bright-color-circles-and-n"">code</a> is saved as cirCode)</p>

<pre><code>from unittest import TestCase

import unittest
from unittest import TestCase
import cirCode

class TestFind_circles(TestCase):

        def setUp(self):
            pass

        def tearDown(self):
            pass

        #def test_circle(self):
         #   self.fail()

        def test_find_circles(self):

            Negative_circles, Positive_circles, out_filepath, circles, threshold = cirCode.find_circles('blobs.jpg')

            self.assertEqual(Negative_circles, 20)
            self.assertEqual(Positive_circles, 8)

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

<p>Now, I do not know how to test <strong>def circle</strong> function. Also, I am not sure if it is a correct way to test <strong>find_circles</strong> function. </p>

<p>Do you guys have any better idea to do the unit test on this <a href=""https://stackoverflow.com/questions/54576667/how-can-i-correctly-classify-the-number-of-positive-bright-color-circles-and-n"">code</a> and also how can I proceed with the unit test on the <em>circle</em> function?</p>
",https://stackoverflow.com/questions/56416041/how-to-do-unit-testing-on-image-as-input-and-output-in-python,"['python', 'unit-testing', 'opencv', 'oop', 'hough-transform']",4347,True,3,1
How can we run the test cases in Android,"<p>I am new in android and I am working on unit testing. we don,t know to check or compile the unit cases in android. Please Suggest me.</p>
",https://stackoverflow.com/questions/56184235/how-can-we-run-the-test-cases-in-android,"['java', 'android', 'unit-testing']",37,False,-1,1
Unit tests with CakePHP 3 and PHPUnit 8 outside project,"<p>Is there someway to do unit testing in CakePHP 3.x with the latest version of PHPUnit? </p>

<p>Using composer inside the project is limited to PHPUnit version 6.</p>
",https://stackoverflow.com/questions/57380075/unit-tests-with-cakephp-3-and-phpunit-8-outside-project,"['php', 'unit-testing', 'cakephp', 'phpunit']",143,False,0,0
Unit testing the async await function in angular 5,"<p>I need to know how to write unit testing for async/await functions in angular 5 which connect with a background service for STT service .Can anybody help?</p>

<pre><code>async listen(){
 let data = await fetch('http://localhost:13005/getGoogleText', {
      method: 'GET'
    })
    .then(function(response) {
      if (response.ok) {
      return response.json();
      }
    })
    .then(response =&gt; {
      return response;
    })
    .catch(error =&gt; {
      return (error);
      console.error(error);
    });
}
</code></pre>
",https://stackoverflow.com/questions/56001896/unit-testing-the-async-await-function-in-angular-5,"['angular', 'unit-testing', 'async-await']",80,False,0,0
unable to run command ~$ vue add unit-mocha in vue cli 3,"<p>I want to add mocha as a unit testing plugin to my already created vue project, which was built using CLI 3 i.e. vue create myProj</p>

<p>this is for vue CLI 3.0.0+, in which my current project is running</p>

<p>BELOW IS THE ERROR when i run command</p>

<p>~$ vue add unit-mocha</p>

<pre><code>npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/vue-cli-plugin-unit-mocha - Not found
npm ERR! 404
npm ERR! 404  'vue-cli-plugin-unit-mocha@latest' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Piktorlabs\AppData\Roaming\npm-cache\_logs\2019-11-04T10_03_45_315Z-debug.log
 ERROR  command failed: npm install --loglevel error -D vue-cli-plugin-unit-mocha
</code></pre>

<p>hence as per the NPM documentation at <a href=""https://www.npmjs.com/package/@vue/cli-plugin-unit-mocha"" rel=""nofollow noreferrer"">https://www.npmjs.com/package/@vue/cli-plugin-unit-mocha</a></p>

<p>it says to run command ~$ vue add unit-mocha
to add mocha unit testing plugin in an already created project, but i get a 404 error in the CLI saying that the npm directory does not exist</p>
",https://stackoverflow.com/questions/58691273/unable-to-run-command-vue-add-unit-mocha-in-vue-cli-3,"['javascript', 'vue.js', 'vue-cli', 'mocha-webpack']",405,False,1,1
Unit tests for Angular Post API calls,"<p>I am new for unit testing. My api makes post request. I want to know,what kind of unit tests can be done for Post request using HttpTestingController?</p>
",https://stackoverflow.com/questions/55971480/unit-tests-for-angular-post-api-calls,"['angular', 'unit-testing', 'jasmine', 'integration-testing']",150,True,-1,2
Mockery::mock Versus createMock,"<p>I'm just leaning unit testing with PHP. I'm looking at existing unit tests and I noticed some tests are using</p>

<pre><code>$this-&gt;createMock(object::class)
</code></pre>

<p>and other cases are using </p>

<p><code>\Mockery::mock(Object::class)</code></p>

<p>What are the differences between the two when creating Mocks?</p>
",https://stackoverflow.com/questions/54314491/mockerymock-versus-createmock,"['php', 'phpunit']",419,False,6,0
C++ unit testing framework with type and value parametrisation,"<p>I am looking for a unit testing framework that allows passing type and value parameters to test function at the same time. </p>

<p>Example: let's say I have a few template sorting functions:</p>

<pre><code>template&lt;class ITERATOR, class COMPARATOR = std::less&lt;typename std::iterator_traits&lt;ITERATOR&gt;::value_type&gt;&gt;
void selectionSort(const ITERATOR first,const ITERATOR last, const COMPARATOR comparator = COMPARATOR ()){ ... };

template&lt;class ITERATOR, class COMPARATOR = std::less&lt;typename std::iterator_traits&lt;ITERATOR&gt;::value_type&gt;&gt;
void insertionSort(const ITERATOR first,const ITERATOR last, const COMPARATOR comparator = COMPARATOR ()) { ... }
</code></pre>

<p>and I want to test these functions with different input types as:</p>

<pre><code>template&lt;class T&gt;
vector&lt;T&gt; makeRandomVector(int size){ ... }

vector&lt;int&gt; intVec = makeRandomVector&lt;int&gt;(10);  //10 is vector size
someSort(intVec.begin(),intVec.end())
vector&lt;MyCustomStruct&gt; structVec = makeRandomVector&lt;MyCustomStruct&gt;(10);  
someSort(structVec.begin(),structVec.end())
</code></pre>

<p>and with different size arguments for <code>makeRandomVector</code> to test these function if vector size is 0,1,10 etc.</p>

<p>So I am looking for C++ unit testing framework that allows creating test that would accept type (int,MyCustomStruct) and value parameters (0,1,10) at the same time and perform the test for each element of the cartesian product of Types x Values. </p>
",https://stackoverflow.com/questions/55023264/c-unit-testing-framework-with-type-and-value-parametrisation,"['c++', 'unit-testing']",239,True,1,1
How to do unit testing in the case of access log middleware,"<p>I have a middleware to log this service access. But I'm confused to do the unit testing several times I surfed googling. I have not found the right way to solve this</p>

<pre><code>package accesslog

import (
    ""net/http""
    ""time""

    ""github.com/go-chi/chi/middleware""

    ""transactionService/pkg/log""
)

func Handler(logger log.Logger) func(next http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        fn := func(w http.ResponseWriter, r *http.Request) {
            ctx := r.Context()
            ctx = log.WithRequest(ctx, r)
            ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)

            start := time.Now()
            defer func() {
                logger.With(ctx, ""duration"", time.Since(start), ""status"", ww.Status()).
                    Infof(""%s %s %s %d %d"", r.Method, r.URL.Path, r.Proto, ww.Status(), ww.BytesWritten())
            }()

            next.ServeHTTP(ww, r.WithContext(ctx))
        }

        return http.HandlerFunc(fn)
    }
}


</code></pre>
",https://stackoverflow.com/questions/59495537/how-to-do-unit-testing-in-the-case-of-access-log-middleware,"['unit-testing', 'go', 'middleware', 'go-chi']",1603,True,3,1
NullPointerException Problem when trying to mock Elastic Search&#39;s RestHighLevelClient,"<p>I'm facing a NullPointerException during unit testing, when trying to test and mock a <code>RestHighLevelClient</code>  inside an <code>ElasticClient</code> class:</p>

<pre><code>@Configuration
@NoArgsConstructor
public class ElasticClient{

   @Setter
   private RestHighLevelClient restHighLevelClient;

    @PostConstruct
    public void buildRestHighLevelClient(){

        RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(
                ""127.0.0.1"",
                9200, ""http"")
        );

        restClientBuilder.setRequestConfigCallback(
                requestConfigBuilder -&gt;
                        requestConfigBuilder
                                .setConnectTimeout(500000)
                                .setSocketTimeout(600000)
                                .setConnectionRequestTimeout(0)
        )
                .setHttpClientConfigCallback(
                        httpClientBuilder -&gt;
                                httpClientBuilder
                                        .setMaxConnPerRoute(2048)
                );

        restHighLevelClient = new RestHighLevelClient(restClientBuilder);
    }

   public boolean isReachable(){
     return restHighLevelClient.ping(RequestOptions.DEFAULT);
   }

}
</code></pre>

<p>And the test class:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public class ElasticClientTest{

@Mock
private RestHighLevelClient restHighLevelClient;


ElasticClient elasticClient;

@Before
public void init(){

    elasticClient = new ElasticClient();
    elasticClient.setRestHighLevelClient(restHighLevelClient);

}
</code></pre>

<p>And the NullPointerException is coming from here:</p>

<pre><code>    @Test
    public void whenElasticIsPingable_thenReturnTrue() throws IOException{

           when(restHighLevelClient.ping(RequestOptions.DEFAULT)).thenReturn(true);
           Assertions.assertThat(elasticClient.isReachable()).isTrue();
    }
</code></pre>

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

<pre><code>java.lang.NullPointerException
at org.elasticsearch.client.RestHighLevelClient.internalPerformRequest(RestHighLevelClient.java:1764)
at org.elasticsearch.client.RestHighLevelClient.performRequest(RestHighLevelClient.java:1734)
at org.elasticsearch.client.RestHighLevelClient.ping(RestHighLevelClient.java:694)
at com.example.ElasticClientTest.whenElasticIsPingable_thenReturnTrue(ElasticClientTest.java:44)
</code></pre>
",https://stackoverflow.com/questions/58914298/nullpointerexception-problem-when-trying-to-mock-elastic-searchs-resthighlevelc,"['java', 'spring', 'spring-boot', 'mockito', 'resthighlevelclient']",4852,True,3,3
RxSwift Observing test cases on mocked UserDefaults,"<p>I am observing for value change in userDefaults </p>

<p><code>userDefaults.rx.observe(Int.self, option.userDefaultsKey)</code></p>

<p>For unit testing I did userDefaultsMock, I am not getting how to emit when value is updated or set for those particular keys</p>

<pre><code> override func setValue(_ value: Any?, forKey key: String) {
        tempArray[key] = value
    }
</code></pre>
",https://stackoverflow.com/questions/56724018/rxswift-observing-test-cases-on-mocked-userdefaults,"['ios', 'swift', 'unit-testing', 'mocking', 'rx-swift']",407,False,2,2
How to test / mock the following:,"<p>here is what I have for <strong>file.js</strong>
How could I mock the following and perform a unit testing:
thanks</p>

<pre><code>var dataset = document.getElementById('test') ? 
document.getElementById('test').dataset : {};
export const SERVICE_URL = 'http://localhost:/';
</code></pre>

<p>Using JEST / EZNYME  for REACTJS - something along these lines: <strong>file.test.js</strong></p>

<pre><code>const mockTrue = {SERVICE_URL};

describe ( "" Service URL "", () =&gt;{
 it ( ' should output ', () =&gt; {
expect(mockTrue).toBeCalled('http://localhost:xxxxxxx/');
});
</code></pre>
",https://stackoverflow.com/questions/54404769/how-to-test-mock-the-following,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",92,True,0,2
Vue CLI creates empty project,"<p>I installed the Vue CLI globally and tried to create a new project </p>

<ul>
<li>my package manager is npm</li>
<li>my first git message is ""init""</li>
<li>I add Babel, Router, Vuex, Linter, Unit Testing and config files manually</li>
<li>I lint on save with Prettier</li>
<li>My unit testing solution is Jest</li>
</ul>

<p>This is what I get:</p>

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

<p>It only installs the node modules, nothing else..
I tried to reinstall the cli but it didn't help. Within the Vue ui admin panel each tab is completely empty because the project seems to be corrupted</p>

<p>(the language is german)</p>

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

<p>What might be wrong?</p>
",https://stackoverflow.com/questions/55326937/vue-cli-creates-empty-project,"['vue.js', 'vue-cli', 'vue-cli-3']",564,False,0,0
unit testing covering the branch case,"<p>I am trying write unit test for below .js using mocha</p>

<pre><code>const fs = require('fs')
const defaultValue = 255

const envValue = process.env.Var1Value
const valueToUse = envValue &amp;&amp; !isNaN(envValue) ? parseInt(envValue) : defaultValue

module.exports.MyFun = () =&gt; {
  //use the value of 'valueToUse'
}
</code></pre>

<p>In my unit testing, I am trying to cover the cases for ""valueToUse"" both from environment and from default value.
I trying to understand how can cover both the scenarios for unit testing. If I set the process.env.Var1Value before loading the module (using require) it covers the first scenario, but not the other case and in reverse if I don't set the env variable it cover the other case, as the module is being loaded only once... how shall I have an unit test that covers both the scenario?  Thanks in advance!</p>
",https://stackoverflow.com/questions/55013051/unit-testing-covering-the-branch-case,"['node.js', 'unit-testing', 'mocha.js']",128,True,0,1
ValueError: No module named &#39;notmigrations&#39; during unit tests,"<p>I have django application 2.1.7 with django-tenant plugin (creating schemas in the database for saas).</p>

<p>My problem is unit testing. I run the command:
<code>python manage.py test --settings=project.settings_test</code>
and I'm getting a error: <code>ImportError: No module named 'notmigrations'</code></p>

<p>My code in settings_test file</p>

<pre><code>from .settings_base import *


class DisableMigrations(object):
    def __contains__(self, item):
        return True

    def __getitem__(self, item):
        return 'notmigrations'

MIGRATION_MODULES = DisableMigrations()
</code></pre>
",https://stackoverflow.com/questions/55894810/valueerror-no-module-named-notmigrations-during-unit-tests,"['python', 'django', 'unit-testing', 'multi-tenant', 'django-unittest']",743,True,5,1
Unexpected value &#39;undefined&#39; imported by the module &#39;DynamicTestModule&#39; in jasmine-karma,"<p>I am doing unit testing using jasmine-karma. 
configuration -</p>

<pre><code>""@types/jasmine"": ""~2.8.6"",
""@types/jasminewd2"": ""~2.0.3"",
""@types/jquery"": ""^3.3.22"",
""@types/node"": ""~8.9.4"",
""codelyzer"": ""~4.2.1"",
""jasmine-core"": ""~2.99.1"",
""jasmine-spec-reporter"": ""~4.2.1"",
""karma"": ""~1.7.1"",
""karma-chrome-launcher"": ""~2.2.0"",
""karma-coverage-istanbul-reporter"": ""~1.4.2"",
""karma-jasmine"": ""~1.1.1"",
""karma-jasmine-html-reporter"": ""^0.2.2"",
</code></pre>

<p>I am getting the same error for all the test cases.</p>

<blockquote>
  <p>Error: Unexpected value 'undefined' imported by the module 'DynamicTestModule'</p>
</blockquote>

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

<pre class=""lang-js prettyprint-override""><code>    describe('SignupComponent', () =&gt; {
            let component: SignupComponent;
        let fixture: ComponentFixture&lt;SignupComponent&gt;;
        let de: DebugElement;
        let username: DebugElement;
        let firstName: DebugElement;
        let lastName: DebugElement;
        let mobileNumber: DebugElement;
        let email: DebugElement;
        let password: DebugElement;
        let confirmPassword: DebugElement;
        let router: Router;
        beforeEach(async () =&gt; {
            TestBed.configureTestingModule({
                declarations: [SignupComponent],
                imports: [HttpClientModule, RouterTestingModule,   RouterTestingModule.withRoutes([
                ]),FormsModule, ReactiveFormsModule, BrowserModule, ,ToastrModule],
                providers: [

                { provide: SignupService, useClass: SignupService },
                { provide: ToastrService, useClass: ToastrService },
            ]
            }).compileComponents().then(() =&gt; {
                fixture = TestBed.createComponent(SignupComponent);
                component = fixture.componentInstance;
                de = fixture.debugElement.query(By.css('form'));
                router = TestBed.get(Router)
                username = fixture.debugElement.query(By.css('input[id=username]'));
                firstName = fixture.debugElement.query(By.css('input[id=firstName]'));
                lastName = fixture.debugElement.query(By.css('input[id=lastName]'));
                mobileNumber = fixture.debugElement.query(By.css('input[id=mobileNumber]'));
                email = fixture.debugElement.query(By.css('input[id=email]'));
                password = fixture.debugElement.query(By.css('input[id=password]'));
                confirmPassword = fixture.debugElement.query(By.css('input[id=confirmPassword]'));
            });
        });
        beforeEach(() =&gt; {
            fixture = TestBed.createComponent(SignupComponent);
            component = fixture.componentInstance;
            fixture.detectChanges();
        });
        it('Defining SignupComponent component', () =&gt; {
            fixture = TestBed.createComponent(SignupComponent);
            component = fixture.componentInstance;
            fixture.detectChanges();
            expect(component).toBeDefined();
        })
        it('should create component', () =&gt; {
            fixture = TestBed.createComponent(SignupComponent);
            component = fixture.componentInstance;
            fixture.detectChanges();
            expect(component).toBeTruthy();
        });
        it('SignUp form is inValid when empty', () =&gt; {
            expect(component.addRegisterData.invalid).toBeTruthy();
        });
        }));
</code></pre>

<p><strong>service.stub.ts</strong></p>

<pre class=""lang-js prettyprint-override""><code>    export class SignupStubService {
        constructor(private http: HttpClient) { }
        register(value):Observable&lt;any&gt;  {
            console.log(""in service.ts"")
            return this.http.post(baseUrl + ""user/register"", value)
            .pipe(map(Response =&gt; Response))

        }
    }
</code></pre>

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

<pre class=""lang-js prettyprint-override""><code>    export class SignupComponent {

      constructor(private fb: FormBuilder, private http: HttpClient, private router: Router,
         public toastr: ToastrService, public signupservice: SignupService, ) {}
    ngOninit()
    }
</code></pre>
",https://stackoverflow.com/questions/57769446/unexpected-value-undefined-imported-by-the-module-dynamictestmodule-in-jasmi,"['angular', 'typescript', 'jasmine', 'karma-jasmine']",2495,True,2,1
"Could not find implicit in Scala Tagless Final, Implicit, unit test","<p>Getting:</p>

<pre><code>Error:(20, 5) could not find implicit value for parameter console: example.Console[F]
    new NameThing().program
Error:(20, 5) not enough arguments for constructor NameThing: (implicit evidence$1: cats.Monad[cats.package.Id], implicit console: example.Console[cats.package.Id])example.NameThing[cats.package.Id].
Unspecified value parameter console.
    new NameThing().program
</code></pre>

<p>Not sure why.</p>

<p>I'm trying to understand unit testing with Tagless Final</p>

<p>So i have:</p>

<pre><code>case class FullName(first:String, last:String)

trait Console[F[_]] {
  def prompt:F[Unit]
  def read:F[String]
  def display(fullName: FullName):F[Unit]
}

class NameThing[F[_]: Monad](implicit console: Console[F]) {

  def program: F[Unit] = for {
    _ &lt;- console.prompt
    rawName &lt;- console.read
    fullName = parse(rawName)
    _ &lt;- console.display(fullName)
  } yield ()

  def parse(rawName:String):FullName = {
    val parts = rawName.split("" "")
    FullName(parts(0), parts(1))
  }
}
</code></pre>

<p>And in my unit test I have:</p>

<pre><code>   case class TestEnv()
   type Test[A] = Reader[TestEnv, A]

   implicit object TestConsole extends Console[Test] {
      override def prompt: Test[Unit] = Reader(_ =&gt; Unit)
      override def read: Test[String] =  Reader(_ =&gt; ""Joe Bloggs"")
      override def display(fullName: FullName): Test[Unit] = Reader(_ =&gt; Unit)
    }

    new NameThing().program
</code></pre>

<p>Full Code: <a href=""https://bitbucket.org/jameskingconsulting/scala-effects/src/master/"" rel=""nofollow noreferrer"">https://bitbucket.org/jameskingconsulting/scala-effects/src/master/</a></p>
",https://stackoverflow.com/questions/56513247/could-not-find-implicit-in-scala-tagless-final-implicit-unit-test,"['scala', 'unit-testing', 'implicit', 'scala-cats', 'tagless-final']",300,True,2,1
how to write angular 6 unit testing for if condition,"<p>How to write unit testing for if the condition, please help me, anyone I tried to like this but it's not covered in my codecoverage</p>

<p>My component</p>

<pre><code>isAppListEditable(){
    if(this.requestType === ""new""){
      //console.info('inside');
      return false;
    }else{
      return true;
    }
  }
</code></pre>

<p>my spec file </p>

<pre><code>it('isAppListEditable', () =&gt; {
    let requestType = ""new"";
    component.isAppListEditable();
    expect(component.isAppListEditable()).toBeFalsy;
  });
</code></pre>
",https://stackoverflow.com/questions/55293125/how-to-write-angular-6-unit-testing-for-if-condition,"['angular', 'unit-testing']",320,False,0,0
How can I test error handing without try-- catch,"<p>I am writing code that validates texts. This is how I test it. But I don't want to use try--catch in unit testing. Please give me a better way to do it.</p>

<pre><code>it('Testing if hook errors on invalid description.', async () =&gt; {
      try {
        workRequest.requestor = 'John';
        workRequest.description = 1;
        result = await app.service('dummy').create(workRequest);
      } catch (error) {
        assert.equal(error.errors.description, 'Description is must be a string');
      }
    });
</code></pre>
",https://stackoverflow.com/questions/55907492/how-can-i-test-error-handing-without-try-catch,"['javascript', 'node.js', 'unit-testing', 'mocha.js']",60,True,2,1
TypeError : Is Event handler &#39;change&#39;. working correctly?,"<p>I am unit testing the following method :</p>

<pre><code>const initImageUpload = () =&gt; {
  const input = document.querySelector('.file-input');
  const fileName = document.querySelector('.file-name');
  if (input) {
    input.addEventListener('change', () =&gt; {
      fileName.classList.remove('is-invisible');
    });
  }
};
</code></pre>

<p>However when I trigger .change() I get an error :</p>

<pre><code>let inputImage = document.querySelector('.file-input');
let inputImageFileName = document.querySelector('.file-name');

// WHEN
inputImage.change();
await Promise.resolve().then(); // wait two cycles of the PromiseJobs queue
// THEN
console.log('IMAGE FILENAME: ', inputImageFileName.outerHTML);

**TypeError: inputImage.change is not a function**
</code></pre>

<p>where am I wrong ? is change() on input field working or not ?</p>

<p>thanks for feedback</p>
",https://stackoverflow.com/questions/54180020/typeerror-is-event-handler-change-working-correctly,"['javascript', 'dom']",32,False,0,1
How to programmatically change &quot;/test/unit/python/tests.py&quot; to &quot;test.unit.python.tests&quot; in Bash?,"<p>There are many python files in <code>test</code> directory.</p>

<pre><code>file=""test/unit/python/tests.py""
</code></pre>

<p>I want to somehow call all of Python scripts for unit testing.</p>

<p><code>python -m unittest test.unit.python.tests</code></p>

<p>How to programmatically sub-string ""/test/unit/python/tests.py"" to ""test.unit.python.tests"" in Bash?</p>

<pre><code>$ echo $file    ===&gt; /test/unit/python/tests.py
$ '${file.???}' ===&gt; How can I get test.unit.python.tests 
                =&gt;              or test.unit.python.tests.py
</code></pre>
",https://stackoverflow.com/questions/56244221/how-to-programmatically-change-test-unit-python-tests-py-to-test-unit-python,"['string', 'bash']",30,True,1,3
Test Class Not Found when Unit Testing on Scala,"<p>I am trying to run the following Unit Test on Scala. I am getting error test class not found: mainFolder.TestDictionary</p>

<p>Here is what my directory looks like:</p>

<pre><code>src
  |_ mainFolder
  |     |_ Dictionary.scala
  |_ testing
        |_ TestDictionary.scala
</code></pre>

<p>Here is my <code>TestDictionary.scala</code> Unit Testing Code</p>

<pre><code>package testing

import org.scalatest._
import mainFolder.Dictionary

class TestDictionary extends FunSuite {
test(""Use many test cases for many category""){
    val test1 = ""CAT""
    val test2 = ""BAT""
    val test3 = ""DIAMOND""
    val test4 = ""THOUSAND""
    val test5 = """"
    val test6 = ""HALF""
    val test7 = ""PHOTOGRAPH""
    val test8 = ""STAFF""

    assert(Dictionary.isSounds(test1, test2) == true)
    assert(Dictionary.isSounds(test5, test7) == true)
    assert(Dictionary.isSounds(test4, test5) == true)
    assert(Dictionary.isSounds(test5, test8) == true)
    assert(Dictionary.isSounds(test3, test2) == true)
    assert(Dictionary.isSounds(test4, test1) == true)
    assert(Dictionary.isSounds(test1, test8) == true)
    assert(Dictionary.isSounds(test8, test3) == true)
    assert(Dictionary.isSounds(test5, test6) == true)
    assert(Dictionary.isSounds(test8, test2) == true)
}
}
</code></pre>
",https://stackoverflow.com/questions/54700878/test-class-not-found-when-unit-testing-on-scala,"['java', 'scala', 'unit-testing', 'intellij-idea']",2557,True,2,2
Unit testing ember-concurrency tasks and yields,"<p>We have a lot of code in our project that isn't covered because of ember concurrency tasks.</p>

<p>Is there a straightforward way of unit testing an controller that contains something like the following:</p>

<pre><code>export default Controller.extend({
    updateProject: task(function* () {
        this.model.project.set('title', this.newTitle);
        try {
            yield this.model.project.save();
            this.growl.success('success');
        } catch (error) {
            this.growl.alert(error.message);
        }
    })
});```
</code></pre>
",https://stackoverflow.com/questions/58452244/unit-testing-ember-concurrency-tasks-and-yields,"['javascript', 'unit-testing', 'ember.js', 'ember-testing', 'ember-concurrency']",695,True,2,1
Mock static method in .NET Core 2.2,"<p>How to mock a static extension method like <code>AsNoTracking</code> in <code>.NET Core 2.2</code> application for unit testing?</p>

<p>The problem is that I need to mock EF Core DbContext, but my code uses a static <code>AsNoTracking</code> method.</p>
",https://stackoverflow.com/questions/54429574/mock-static-method-in-net-core-2-2,"['.net-core', 'mocking']",250,True,0,1
Unit test using class with RestTemplate injected with java and spring boot,"<p>I'm running unit testing with a class that has the injected RestTemplate and only when I run the tests does RestTemplate get null after consuming the API I'm consuming.</p>

<pre><code>class ReceitaWsIntegrationImpl implements ReceitaWsIntegration {

  private static final String URL_RECEITA_WS_CNPJ
    = ""https://www.receitaws.com.br/v1/cnpj"";

  private final RestTemplate restTemplate;

  @Override
  public void findByCnpj(String cnpj) {
    ResponseEntity&lt;CnpjResource&gt; forEntity = restTemplate.getForEntity(
      URL_RECEITA_WS_CNPJ.concat(""/"").concat(cnpj), CnpjResource.class);
  }
}
</code></pre>

<p>Test class:</p>

<pre><code>public class ReceitaWsIntegrationImplTest extends TestSupport {

private static final String CNPJ = ""27865757000102"";
private static final String URL_RECEITA_WS_CNPJ = ""https://www.receitaws.com.br/v1/cnpj/"";
@Mock
private RestTemplate restTemplate;
private ReceitaWsIntegration receitaWsIntegration;

    @Override
    public void init() {
        receitaWsIntegration = new ReceitaWsIntegrationImpl(restTemplate);
    }

    @Test
    public void should_find_company_by_cnpj() {
        receitaWsIntegration.findByCnpj(CNPJ);

        InOrder inOrder = inOrder(restTemplate);

        inOrder.verify(restTemplate, times(1))
            .getForEntity(URL_RECEITA_WS_CNPJ.concat(CNPJ), CnpjResource.class);
        inOrder.verifyNoMoreInteractions();
    }
}
</code></pre>
",https://stackoverflow.com/questions/56993808/unit-test-using-class-with-resttemplate-injected-with-java-and-spring-boot,"['java', 'spring-boot', 'junit', 'mockito', 'resttemplate']",180,True,0,2
Unity Framework Unit Testing undefined reference to &quot;setUp&quot; and &quot;tearDown&quot;,"<p>I copied the simplest code from the <a href=""http://www.throwtheswitch.org/unity"" rel=""noreferrer"">Unity for C Unit Testing library</a> and set up a very basic test, which I copied and pasted from the site:</p>
<pre><code>#include &quot;unity/src/unity.h&quot;

int main(void)
{
    UNITY_BEGIN();
    int a = 1;
    TEST_ASSERT( a == 1 ); //this one will pass
    TEST_ASSERT( a == 2 ); //this one will fail
    return UNITY_END();
}
</code></pre>
<p>What I typed into terminal:</p>
<pre><code>gcc TestDumbExample.c ./unity/src/unity.c -o Test
</code></pre>
<p>I am getting this error message in Terminal:</p>
<pre><code>/tmp/ccqgFGn8.o: In function `UnityDefaultTestRun':
unity.c:(.text+0x26af): undefined reference to `setUp'
unity.c:(.text+0x26ca): undefined reference to `tearDown' collect2:
error: ld returned 1 exit status

Unsure why this error is occurring and it has undefined references.
</code></pre>
",https://stackoverflow.com/questions/57573905/unity-framework-unit-testing-undefined-reference-to-setup-and-teardown,"['c', 'unit-testing', 'gcc', 'compiler-errors', 'unity-test-framework']",3506,True,8,3
How to pass the wrong value to my request header and assert error message from it,"<p>I have to do a unit testing of my servlet by passing the wrong request headers and parameters and getting failure message printed in the console</p>

<p>I have used Mockito framework</p>
",https://stackoverflow.com/questions/57215507/how-to-pass-the-wrong-value-to-my-request-header-and-assert-error-message-from-i,"['junit', 'request-headers']",282,False,0,1
How can I solve error when unit testing with mocha on vue?,"<p>I using <code>mocha</code> to do unit testing to my vuetify project</p>

<p>I had install it. So I run <code>npm run test:unit</code>, there exist error like this :</p>

<pre><code>npm ERR! Failed at the test-vuetify@0.1.0 test:unit script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code></pre>

<p>The full error like this :</p>

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

<p>How can I solve this error?</p>

<p><strong>Note</strong> :</p>

<p>When I first installed vuetify and tried unit testing, it worked. No error</p>

<p>After I edited some parts and ran the unit test, the above error appeared</p>

<p>How do I resolve this error?</p>

<p><strong>Update</strong> :</p>

<p>I have updated the version of vuetify. Is that what caused this error?</p>

<p>I am confused to solve this error. Because all errors are located in the node-modules folder. Not in the component that I made</p>
",https://stackoverflow.com/questions/59127109/how-can-i-solve-error-when-unit-testing-with-mocha-on-vue,"['unit-testing', 'vue.js', 'mocha.js', 'vue-component', 'vuetify.js']",226,False,1,1
How to mock objects which return a promise?,"<p>I want to create a mock of this object for unit testing purposes.</p>

<pre><code>sqs.listQueues().promise()
      .then(...
</code></pre>

<p>Here's one of my attempts at mocking this and still getting the error <code>sqs.listQueues(...).promise is not a function</code></p>

<pre><code>const sqs = {
    listQueues: () =&gt; Promise.resolve(this),
    promise: () =&gt; Promise.resolve()
  }
</code></pre>

<p>How can i properly mock this object?</p>
",https://stackoverflow.com/questions/55107350/how-to-mock-objects-which-return-a-promise,"['javascript', 'node.js']",161,True,1,2
Is this the good class design practice in Java?,"<pre><code>public class OneClass {
        private AnotherClass anotherClass = new AnotherClass();

        private void doOneJob(){
            anotherClass.doOtherJob();
        }
    }
</code></pre>

<p>In the above code, AnotherClass is instantiated and held as a class variable of OneClass.</p>

<ul>
<li>What are the consequences of this design?</li>
<li>Is it a good practice?</li>
<li>Will this support unit testing?</li>
</ul>
",https://stackoverflow.com/questions/54586654/is-this-the-good-class-design-practice-in-java,"['java', 'design-patterns']",89,True,-1,2
Is there a way to unit test a simple directive declaration in AngularJS? (no link function),"<p>So I have a simple directive definition like this</p>

<pre><code>function computeTotals() {
  return {
    restrict: 'A',
    templateUrl: 'compute-totals.html',
    controller: 'ct as ctrl',
    scope: {},
    bindToController: {
      property: '=',
      numbersArray: '='
    }
  };
}
</code></pre>

<p>How would I go about unit testing to make sure this directive is set-up correctly?  I just want to verify these properties</p>
",https://stackoverflow.com/questions/58009445/is-there-a-way-to-unit-test-a-simple-directive-declaration-in-angularjs-no-lin,"['angularjs', 'angularjs-directive']",33,True,0,1
jest Unexpected token Import when semicolons are appended to import statements,"<p>using the <code>vue-cli v3</code> and adding unit testing and using jest if you append semicolons to the end of import statements jest throws an error <code>Unexpected token import</code> but when there are no semicolons everything works fine</p>

<p>i tried to search about the effects of semicolons to import statements but i got nothing<br>
as far as eslint is concerned i have the vue cli option eslint with error checking only</p>

<p>package.json:</p>

<pre><code>{
  ""name"": ""frontend-jest"",
  ""version"": ""0.1.0"",
  ""private"": true,
  ""scripts"": {
    ""serve"": ""vue-cli-service serve"",
    ""build"": ""vue-cli-service build"",
    ""lint"": ""vue-cli-service lint"",
    ""test:unit"": ""vue-cli-service test:unit""
  },
  ""dependencies"": {
    ""core-js"": ""^2.6.5"",
    ""register-service-worker"": ""^1.6.2"",
    ""vue"": ""^2.6.10"",
    ""vue-router"": ""^3.0.3"",
    ""vuex"": ""^3.0.1""
  },
  ""devDependencies"": {
    ""@vue/cli-plugin-babel"": ""^3.7.0"",
    ""@vue/cli-plugin-eslint"": ""^3.7.0"",
    ""@vue/cli-plugin-pwa"": ""^3.7.0"",
    ""@vue/cli-plugin-unit-jest"": ""^3.7.0"",
    ""@vue/cli-service"": ""^3.7.0"",
    ""@vue/test-utils"": ""1.0.0-beta.29"",
    ""babel-core"": ""7.0.0-bridge.0"",
    ""babel-eslint"": ""^10.0.1"",
    ""babel-jest"": ""^23.6.0"",
    ""eslint"": ""^5.16.0"",
    ""eslint-plugin-vue"": ""^5.0.0"",
    ""node-sass"": ""^4.9.0"",
    ""sass-loader"": ""^7.1.0"",
    ""vue-template-compiler"": ""^2.5.21""
  },
  ""eslintConfig"": {
    ""root"": true,
    ""env"": {
      ""node"": true
    },
    ""extends"": [
      ""plugin:vue/essential"",
      ""eslint:recommended""
    ],
    ""rules"": {},
    ""parserOptions"": {
      ""parser"": ""babel-eslint""
    }
  },
  ""postcss"": {
    ""plugins"": {
      ""autoprefixer"": {}
    }
  },
  ""browserslist"": [
    ""&gt; 1%"",
    ""last 2 versions""
  ],
  ""jest"": {
    ""moduleFileExtensions"": [
      ""js"",
      ""jsx"",
      ""json"",
      ""vue""
    ],
    ""transform"": {
      ""^.+\\.vue$"": ""vue-jest"",
      "".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$"": ""jest-transform-stub"",
      ""^.+\\.jsx?$"": ""babel-jest""
    },
    ""transformIgnorePatterns"": [
      ""/node_modules/""
    ],
    ""moduleNameMapper"": {
      ""^@/(.*)$"": ""&lt;rootDir&gt;/src/$1""
    },
    ""snapshotSerializers"": [
      ""jest-serializer-vue""
    ],
    ""testMatch"": [
      ""**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)""
    ],
    ""testURL"": ""http://localhost/"",
    ""watchPlugins"": [
      ""jest-watch-typeahead/filename"",
      ""jest-watch-typeahead/testname""
    ]
  }
}
</code></pre>

<p>Code examples:</p>

<pre><code>// this will not work it doesn't matter 
// which import statement has a semicolon
import { shallowMount } from '@vue/test-utils';
import HelloWorld from '@/components/HelloWorld.vue';

describe('HelloWorld.vue', () =&gt; {
  it('renders props.msg when passed', () =&gt; {
    const msg = 'new message'
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg }
    })
    expect(wrapper.text()).toMatch(msg)
  })
})

// however this does
import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () =&gt; {
  it('renders props.msg when passed', () =&gt; {
    const msg = 'new message'
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg }
    })
    expect(wrapper.text()).toMatch(msg)
  })
})
</code></pre>

<p>expected: semicolon has no effect
what happens: test breaks when semicolon is applied</p>

<p>how to reproduce:<br>
  1.<code>vue create projectname</code><br>
  2.make sure you have enabled unit testing with jest using vue-cli options<br>
  3.go to <code>./tests/unit/example.spec.js</code> and append semicolons to imports</p>
",https://stackoverflow.com/questions/56203128/jest-unexpected-token-import-when-semicolons-are-appended-to-import-statements,"['javascript', 'vue.js', 'jestjs', 'babel-jest', 'vue-test-utils']",769,False,1,0
Laravel Unit Testing,"<p>I am implementing unit testing in laravel.
While running the test cases using the below command.</p>

<pre><code> vendor/bin/phpunit --filter = MethodName
</code></pre>

<p>It is prompting me to install composer,although I have already installed it.
Can anyone help?</p>
",https://stackoverflow.com/questions/55104043/laravel-unit-testing,"['laravel', 'unit-testing', 'lumen']",129,False,0,1
Is there a way to express the &quot;sign&quot; of a TemporalAmount?,"<p>Based on this <a href=""https://stackoverflow.com/a/56026271/1531124"">answer</a>, I decided to implement my own <code>MutableClock</code> for unit testing purposes that works slightly different:</p>

<pre><code>class MutableClock extends Clock {
  private final List&lt;Instant&gt; instants = new ArrayList&lt;&gt;();

  public MutableClock(Instant now, TemporalAmount... amounts) {
    Objects.requireNonNull(now, ""now must not be null"");
    Objects.requireNonNull(amounts, ""amounts must not be null"");
    instants.add(now);
    for (TemporalAmount amount : amounts) {
        Instant latest = instants.get(instants.size() - 1);
        instants.add(latest.plus(amount));
    }
  }

  @Override
  public Instant instant() {
    Instant latest = instants.get(0);
    if (instants.size() &gt; 1) {
        instants.remove(0);
    }
    return latest;
  }

  ... 
</code></pre>

<p>But then I noticed I was doing this here:</p>

<pre><code>instants.add(latest.plus(amount));
</code></pre>

<p>So, basically, I can only tick the clock ""forward"". Sure, that makes sense most of the time, but as all of this is for unit testing, I can imagine that I want to use such a <code>MutableClock</code> instance and have it return instants that aren't always ""increasing"". </p>

<p>But when looking at the <a href=""https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAmount.html"" rel=""nofollow noreferrer"">TemporalAmount</a> interface: there is no way to express a <strong>negative</strong> amount of time?! In other words: it seems that instances of <code>TemporalAmount</code> aren't ""signed"". </p>

<p>So, how could one go about this?</p>
",https://stackoverflow.com/questions/57390684/is-there-a-way-to-express-the-sign-of-a-temporalamount,"['java', 'datetime', 'java-time']",594,True,1,2
Creating MOCK UP Data for Neo4j Unit testing,"<p>I want to do unit testing for my application in neo4j with java code .We are writing junit test cases for it. But we want when we run the junit test cases it should not communicate it to the main database rather then some other mockup data. </p>

<p><strong>We are using neo4j server and no embedded database is used.</strong></p>

<blockquote>
  <p>How could this be achieved?</p>
  
  <p>How can we create mockup data for testing neo4j related code?</p>
  
  <p>How to create a mocked database for unit testing so that main database
  not be touched.</p>
  
  <p>Is there any tool to mock the main database or we have to do it
  manually through the code?</p>
</blockquote>
",https://stackoverflow.com/questions/56017824/creating-mock-up-data-for-neo4j-unit-testing,"['unit-testing', 'neo4j', 'junit5']",1663,True,1,1
Payload contains two or more files with the same destination path for Default.rd.xml file,"<p>I was trying to do unit testing for UWP App. When I added target application reference in Test project, the following error is giving while running the test method</p>
<p><code>Payload contains two or more files with the same destination path'Properties\Default.rd.xml'.Source files:   D:\Test\MyAppTesting\Properties\Default.rd.xml   D:\Test\MyApp\Properties\Default.rd.xml</code></p>
<p>No error code was given.</p>
<p><a href=""https://i.stack.imgur.com/KD0jE.png"" rel=""nofollow noreferrer"">adding refernce</a></p>
<pre><code>public class MyAppTesting
{
     [Fact]
     public async void PassingWinAppServiceTest()
     {
        
         AgendaService agendaService = new AgendaService();
         var memberModel = await agendaService.GetMemberDetailsById(&quot;234&quot;);

       Assert.False(String.IsNullOrEmpty(memberModel.MemberId.ToString()));
        
     }
</code></pre>
",https://stackoverflow.com/questions/58205458/payload-contains-two-or-more-files-with-the-same-destination-path-for-default-rd,"['unit-testing', 'uwp', 'reference', 'xunit']",479,True,3,2
How to implement integration testing for guards in nest js?,"<p>I want to implement unit testing for guards using nest js(Jest JS). I could nt find much documentation.</p>

<pre><code>import {Test, TestingModule} from '@nestjs/testing';
import {CatsController} from '../src/modules/cats/cats.controller';
import {CatsService} from '../src/modules/cats/cats.service';
import {ICat} from '../src/modules/cats/interfaces/ICat';
import {JwtStrategy} from '../src/strategy/AppId.strategy';

  beforeEach(async () =&gt; {
     const module = await Test.createTestingModule({
             controllers: [CatsController],
             providers: [CatsService],
         }).compile();

    catsService = module.get&lt;CatsService&gt;(CatsService);
    catsController = module.get&lt;CatsController&gt;(CatsController);

  });
  describe('findAll', () =&gt; {
    it('should return an array of cats', async () =&gt; {
      // const appIdAuthContext: AppIDAuthToken = tokenInfo;
      const result: ICat = {
        name: 'test',
        age: 1,
        breed: 'one'
      };
      jest.spyOn(catsService, 'findAll').mockImplementation(() =&gt; result);
      console.log(result);
      console.log(catsController.findAll());
      expect(await catsController.findAll()).toBe(result);
    });
  });
</code></pre>

<p>The above code will return array of cats. i want to implement guards for this unit test.</p>
",https://stackoverflow.com/questions/56218530/how-to-implement-integration-testing-for-guards-in-nest-js,"['node.js', 'angularjs', 'jestjs', 'nestjs']",4477,True,3,1
"Getting error, Spring BeanCreationException: Error creating bean with name &#39;validateableConstraintsEvaluator&#39;","<p>I have updated my project from <code>grails2.5.6</code> to <code>grails3.3.9</code> and successfully completed unit testing.<br>
While running the integration test I am getting the following Exception.</p>

<pre><code>2019-03-07 18:26:12.169  WARN --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.spockframework.spring.SpringMockTestExecutionListener@157b7da6] to process 'before' execution of test method [public void com.mdw360.sec.UserControllerSpec.$spock_feature_0_1()] for test instance [com.mdw360.sec.UserControllerSpec@36f464d8]

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'validateableConstraintsEvaluator': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException: Cannot get property 'config' on null object
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:185)
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:103)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1646)
</code></pre>

<p><strong>Controller</strong></p>

<pre><code>@Transactional(readOnly = true)
class UserController {

    def userCache
    def springSecurityService
    def utilityService

    static allowedMethods = [save: ""POST"", update: ""PUT"", delete: ""DELETE""]


    def create() {
        List&lt;Role&gt; roles = Role.list()
        Map roleMap = [:]
        roles.each { role -&gt; roleMap[role] = false }
        render view: 'create', model: [userCO: new SaveUserCO(), roleMap: roleMap]
    }

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

<p><strong>TestClass</strong></p>

<pre><code>import grails.gorm.transactions.Rollback
import grails.testing.mixin.integration.Integration
import org.springframework.beans.factory.annotation.Autowired
import spock.lang.Specification

@Integration
@Rollback
class UserControllerSpec extends Specification {
    @Autowired
    UserController controller
}

    def cleanup() {
    }

    void ""test create render correct view and model when no role exists""() {
        when:
        controller.request.method='POST'
        controller.create()

        then:
        assert controller.modelAndView.viewName == '/user/create'
        assert controller.modelAndView.model.size() == 2
        assert controller.modelAndView.model.roleMap.size() == 0
        assert controller.modelAndView.model.userCO != null
    }

    void ""test create render correct view and model when role exists""() {
        when:
        controller.request.method='POST'
        createRole('ROLE_TEST')
        controller.create()

        then:
        assert controller.modelAndView.viewName == '/user/create'
        assert controller.modelAndView.model.size() == 2
        assert controller.modelAndView.model.roleMap.size() == 1
        assert controller.modelAndView.model.userCO != null
    }
...
....
}
</code></pre>

<p>I am using Grails 3.3.9 with JDK 1.8, gormVersion 6.1.11 and 
gradle3.5</p>
",https://stackoverflow.com/questions/55045394/getting-error-spring-beancreationexception-error-creating-bean-with-name-vali,['grails3'],690,False,4,1
I want to generate &amp; compile Visual Studio projet with CMake I need to exclude unit testing files from the build. Is there a way to dothis?,"<p>My project contain unit testing file I want to excludes from the compilation process. I want to modify the .vcxproj Visual Studio file with CMake. What could be the possible solutions of my issue ?</p>

<pre><code>set_source_files_properties(BankTestCase_1.h PROPERTIES VS_DEPLOYEMENT_CONTENT 0)

set_source_files_properties(BankTestCase_1.h PROPERTIES EXCLUDE_FROM_BUILD 1)
</code></pre>
",https://stackoverflow.com/questions/56889233/i-want-to-generate-compile-visual-studio-projet-with-cmake-i-need-to-exclude-u,"['c++', 'visual-studio', 'cmake']",24,True,1,1
Why won&#39;t it let me add songs in name space when ive added a ref,"<p><a href=""https://i.stack.imgur.com/v58pa.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/v58pa.png"" alt=""enter image description here""></a>I can't add the namespace song to do some unit testing when I have added it to the refs I have closed and opened visual studio multiple times now and that isn't working.</p>

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

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

        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/54537783/why-wont-it-let-me-add-songs-in-name-space-when-ive-added-a-ref,"['c#', 'unit-testing']",44,True,-3,2
&#39;chrome&#39; could not be found and loaded in phpStorm acceptance test,"<p>I am new to unit testing,
I am new to acceptance testing. I am using laravel 5.5.
The below is my <code>acceptance.suite.dist.yml</code></p>

<pre><code>class_name: AcceptanceTester
modules:
  enabled:
    - WebDriver
        url: 'http://amazon-ce.localhost.tom/'
        browser: chrome
    - Db
    - Filesystem
config:
  PhpBrowser:
   url: 'http://amazon-ce.localhost.tom/'
WebDriver:
   url: 'http://amazon-ce.localhost.tom/'
   browser: chrome
Db:
  dsn: 'mysql:dbname=myDb;host=127.0.0.1'
  user: 'root'
  password: ''
</code></pre>

<p>when I run the test, 
it throwing 
<code>
Module WebDriver url: 'http://amazon-ce.localhost.tom/' 
browser: 'chrome' could not be found and loaded</code></p>

<p>can anyone help on this.? </p>
",https://stackoverflow.com/questions/55157461/chrome-could-not-be-found-and-loaded-in-phpstorm-acceptance-test,"['laravel', 'selenium', 'acceptance-testing']",31,False,0,1
How to add a .vbproj file to an existing project inside a solution in Visual Studio 2015,"<p>I have an existing VB.Net project inside a solution that has been in use for 10 years. It is large, and recreating it is not an option. We would like to add a Unit Testing project to test it with, but it needs to have a .vbproj file in order to reference it from the Unit Testing project.</p>

<p>The existing project does not have a .vbproj file. Apparently, it was created as a ""New Website"" and a .vbproj file was never created. Is there a way to add this .vbproj file to the existing Project, or another way to reference it from the Unit Test?</p>
",https://stackoverflow.com/questions/58809001/how-to-add-a-vbproj-file-to-an-existing-project-inside-a-solution-in-visual-stu,"['vb.net', 'visual-studio-2015', 'projects-and-solutions']",619,False,0,0
C Unit Testing - Mock (In Check Framework),"<p>I'm trying to ""mock"" some things in my unit testing of a C project.
I am using the Check framework for testing and I have a function that reads from a file on disk to verify the contents.</p>

<p>My function is: </p>

<pre><code>#include ""verifier.h""
#include &lt;stdio.h&gt;

int verify_content(char *path, char *verify_string) {
    File *fptr
    fptr = fopen(path, ""r"")
    // Do verification
    return 0
</code></pre>

<p>and my test is</p>

<pre><code>START_TEST (verify_content_test)
    {
        char *test_path = ""test_path"";
        char *test_string = ""unique_string_content_here"";
        ck_assert_str_eq(verify_content(test_path, test_string), 0);
    }
END_TEST
</code></pre>

<p>However, I don't want this to read from disk, because that would be slow, and I'd have to have multiple static files just for testing against.</p>

<p>Is there a way to ""mock""/""fake"" the fopen?</p>

<p>I'm still new to C development and super new to unit testing in C so if I should approach this problem differently, please point me in the right direction.</p>
",https://stackoverflow.com/questions/58174186/c-unit-testing-mock-in-check-framework,"['c', 'unit-testing', 'mocking']",253,False,0,1
Please help understand the use case of unit testing,"<p>I have 2 scripts.</p>

<ol>
<li><p>It runs a load test using locust, collects the output in dict format, then pass it to the 2nd script.</p></li>
<li><p>2nd script will accept a dict as input from script-1, parses it, creates a json payload and sends the data to an api endpoint where it stores in some db. </p></li>
</ol>

<p>The application starts running from the 1st script and all the functionalities are working well. I have never worked on a unit testing. My question here is:
What can be tested here using unit testing in order to keep proper standard of building an application.</p>

<p>script-1. (suppose locust is running in already)</p>

<pre><code>def on_slave_report(data):
    send_to_db(data)

events.slave_report += on_slave_report
</code></pre>

<p>script-2.</p>

<pre><code>def send_to_db(data):
     send_it(take_only_needed(data))

def take_only_needed(data):
     needed=data[stats]
     payload = json.dumps({'stats' : needed, 'bla': bla})
     return payload

def send_it(payload):
     requests.request(""POST"", url, data=payload, headers=headers)
</code></pre>
",https://stackoverflow.com/questions/57093624/please-help-understand-the-use-case-of-unit-testing,"['python', 'unit-testing']",50,False,0,1
How to mock objects in C# using Visual Studio Unit Testing framework or NUnit framework?,"<p>I have moved to developing applications in C# from Java. I came across the Visual Studio unit testing framework provided by Visual Studio, and another framework called NUnit. </p>

<ol>
<li>Which of these frameworks support mocking objects, or something similar to returning specific response to a method in another project whose source code is not available?</li>
</ol>

<p>I'm using Visual Studio Pro, so Microsoft Fakes is not applicable to me. Also, I came across moq, and rhinomocks but I'm not sure about these. </p>

<ol start=""2"">
<li>I was wondering if I can use a unit testing framework like the one provided by Visual Studio or NUnit without having to add additional dependency.</li>
</ol>
",https://stackoverflow.com/questions/59014713/how-to-mock-objects-in-c-using-visual-studio-unit-testing-framework-or-nunit-fr,"['c#', 'visual-studio', 'unit-testing', 'mocking', 'nunit']",3447,True,-1,1
Visual Studio Live Unit Test and Old Tests,"<p>I am using Visual Studio 2019 with Live Unit Testing turned on and everything is working fine until I delete a unit test.  Now the old unit test is showing as a build failure (even though it doesn't exist anymore).</p>

<p>How can I clear this?</p>
",https://stackoverflow.com/questions/57537796/visual-studio-live-unit-test-and-old-tests,"['c#', 'visual-studio', 'live-unit-tests']",1030,True,9,2
How to unit test the mat-error content validation based on the input value,"<p>New to unit testing mat-form-field which has an input, which gets it from a form and mat-error which has error messsage. Have to enter an invalid input to verify the error message.</p>

<pre class=""lang-html prettyprint-override""><code>&lt;div class=""px-3""&gt;

    &lt;mat-form-field class=""formField""&gt;

        &lt;mat-label&gt;threshold&lt;/mat-label&gt;

        &lt;input matInput placeholder=""Threshold"" formControlName=""threshold"" 
               required type=""number"" min=""0"" max=""1"" step=""0.0001""
               (blur)=""onValueChange($event.target)"" id=""rebalanceThreshold"" /&gt;

        &lt;percent-change-label class=""mat-input-element"" id=""percentLabel""
                [inputValue]=""holdingForm.rebalanceThreshold.value""&gt;
        &lt;/percent-change-label&gt;

        &lt;mat-error class='errorMessage' id=""rebalanceThresholdError"" 
                *ngIf=""holdingForm.rebalanceThreshold.errors""&gt;
            {{ testForm.getValidationError('threshold') }}
        &lt;/mat-error&gt;

    &lt;/mat-form-field&gt;
&lt;/div&gt;
</code></pre>
",https://stackoverflow.com/questions/58430274/how-to-unit-test-the-mat-error-content-validation-based-on-the-input-value,"['angular', 'unit-testing']",488,False,1,0
Android studio unit test for activity,"<p>I'm following this tutorial <a href=""https://www.youtube.com/watch?v=_TR6QcRozAg"" rel=""nofollow noreferrer"">https://www.youtube.com/watch?v=_TR6QcRozAg</a> for my first time android studio activity unit testing but getting some error in the code where ""ActivityTestRule"" and ""getClass()"" showing red colour.Cant run the code</p>

<pre><code>package e.asus.supershop;

import android.view.View;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import static org.junit.Assert.*;

public class LoginActivityTest {

    @Rule
    public ActivityTestRule&lt;LoginActivity&gt; mActivityTestRule = new ActivityTestRule&lt;LoginActivity&gt;(LoginActivity.class);

    private LoginActivity mActivity = null;
    @Before
    public void setUp() throws Exception {

        mActivity = mActivityTestRule.getClass();
    }
    @Test
    public void testLaunch()
    {
        View view = mActivity.findViewById(R.id.buttonSignin);
        assertNotNull(view);

    }
    @After
    public void tearDown() throws Exception {
        mActivity = null;
    }
}
</code></pre>
",https://stackoverflow.com/questions/56010296/android-studio-unit-test-for-activity,"['android', 'junit4']",43,False,1,0
How to unit test a private method?,"<p>I am new to unit testing and i don't know how to test a private method? </p>

<p>Is there is any way to test a private method <strong>?</strong> </p>

<p>I am using MSTest framework.</p>

<p><strong>Private Method Code:</strong></p>

<pre><code>private int IncreasePoints(int userPoints)
{
   if (userPoints &gt; 0 &amp;&amp; userPoints &lt; 50)
      userPoints += 0;

   else if (userPoints &gt;= 50 &amp;&amp; userPoints &lt; 100)        
      userPoints += 10;

   else if (userPoints == 100)
      userPoints += 15;

   else if (userPoints &gt; 100)
      userPoints += 25;

   else
      userPoints += 0;

   return userPoints;
}
</code></pre>
",https://stackoverflow.com/questions/54061498/how-to-unit-test-a-private-method,"['c#', 'unit-testing', 'mstest']",99,False,0,0
Mock Router and Ngzone in Angular 7 Jest Unit test,"<p>I used ngzone and router in component class.
My unit testing was working fine but now getting error cannot read toLowerCase() of undefined.
Can anyone suggest me how to mock both Ngzone and Router.</p>
",https://stackoverflow.com/questions/59011530/mock-router-and-ngzone-in-angular-7-jest-unit-test,"['jestjs', 'angular7', 'ngzone']",4546,True,0,1
Using Identity&#39;s Managers in IdentityDbContext that was created by UseInMemoryDatabase(),"<p>I made this method to make unit testing <code>DbContext</code> much easier. This method makes <code>Context</code> of my <code>db</code> in memory. It works because i testing it with entities (like <code>_context.Projects</code>, <code>_context.Tests</code> etc., in unit testing, this method works):</p>

<pre><code>        public static TaskManagerDbContext Create()
        {
            var options = new DbContextOptionsBuilder&lt;TaskManagerDbContext&gt;()
                                .UseInMemoryDatabase(Guid.NewGuid().ToString())
                                .EnableSensitiveDataLogging(true)
                                .Options;

            var context = new TaskManagerDbContext(options);
            context.SaveChanges();

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

<p>My <code>DbContextClass</code> looks like this:</p>

<pre><code>
    public class TaskManagerDbContext : IdentityDbContext&lt;ApplicationUser&gt;, ITaskManagerDbContext
    {
        public TaskManagerDbContext(DbContextOptions&lt;TaskManagerDbContext&gt; options)
            : base(options)
        {
        }

        //db sets here

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfigurationsFromAssembly(typeof(TaskManagerDbContext).Assembly);
        }
    }
</code></pre>

<p>My question is, can we make Identity's <code>UserManager</code>, <code>SignInManager</code>, <code>RoleManager</code> in memory, like we can do with <code>IdentityDbContext</code>? How to unit test <code>Identity</code> things like users, roles in memory like we can do with standard <code>Context</code>? How to call this <code>Managers</code> in fake context that is stored in memory while im testing it?</p>

<p><strong>EDIT:</strong></p>

<p>Based on <a href=""https://stackoverflow.com/questions/48519780/asp-net-core-identity-using-applicationdbcontext-and-usermanager-do-they-share"">this SO Question</a> Identity shares <code>context</code> that is obvious. But how to use <code>Managers</code> on created <code>IdentityDbContext</code> by <code>UseInMemoryDatabase()</code> method?</p>

<p><strong>EDIT2:</strong></p>

<p>Im injecting <code>context</code> by fixture:</p>

<pre><code>public class DatabaseFixture
{
    public TaskManagerDbContext Context { get; private set; }

    public DatabaseFixture()
    {
        this.Context = DatabaseContextFactory.Create();
    }
}

[CollectionDefinition(""DatabaseTestCollection"")]
public class QueryCollection : ICollectionFixture&lt;DatabaseFixture&gt;
{
}
</code></pre>

<p>And usage of it:</p>

<pre><code>[Collection(""DatabaseTestCollection"")]
public class RegisterUserCommandTests
{
    private readonly TaskManagerDbContext _context;

    public RegisterUserCommandTests(DatabaseFixture fixture)
    {
        _context = fixture.Create();
    }

    //and usage of it in class:
    var user = _context.Projects.Find(8);
}
</code></pre>

<p>Im using <code>Xunit</code>.</p>
",https://stackoverflow.com/questions/56929729/using-identitys-managers-in-identitydbcontext-that-was-created-by-useinmemoryda,"['c#', 'entity-framework', 'unit-testing', 'asp.net-core', 'asp.net-identity']",1051,True,3,1
Unit test validation with chai,"<p>I am new to unit testing with chai, and I want to write one for this simple code that compares 2 items. my code:::</p>

<p>This is a sample test followed by the main code</p>

<pre><code>describe('Challenge', function() {
  it('should return the right array', function() {
    assert.deepEqual(number_game(2,12), [3, 5, 7, 9, 11]);
    assert.deepEqual(number_game(0,0), []);
  });
});

function number_game(x, y) {
    var arr = [];
    if (x &gt; y) {
        //if x is greater than y
        //print out even numbers between x and y
        for (let i = x; i &gt; y; i--) {
            if (i % 2 == 0) {

                arr.push(i);
            }
        }
        return arr
    } else if (x &lt; y) {
        for (let i = x; i &lt; y; i++) {
            if (i % 2 == 1) {

                arr.push(i);
            }
        }
        return arr
    } else {
        return ([]);
    }
    //nothing is done when x is equal to y

    return arr;
}
number_game(2, 12);
number_game(0, 0);
</code></pre>
",https://stackoverflow.com/questions/55796264/unit-test-validation-with-chai,"['javascript', 'arrays', 'sorting', 'chai']",180,False,0,1
How to do unit testing of function which is depends on another function using karma jasmine,"<p>I want to test getTokenExpirationDate() method which uses other method jwt_decode and it is imported from jwt-decode. How I can do unit testing for this method?. How This jwt_decode method can be mocked.</p>

<pre><code>import { Injectable } from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import * as jwt_decode from 'jwt-decode';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) { }

  canActivate(): boolean {
    const token = localStorage.getItem(('loginToken'));
    if (this.isTokenExpired(token)) {
      localStorage.removeItem('loginToken');
      this.router.navigate(['/login']);
      return false;
    } else {
      return true;
    }
  }

  isTokenExpired(token: string): boolean {
    if (!token) { return true;
    } else {
      const date = this.getTokenExpirationDate(token);
      if (date === undefined) {
        return false;
      } else {
        return !(date.valueOf() &gt; new Date().valueOf());
      }
    }
  }

  getTokenExpirationDate(token: string): Date {
    const decoded = jwt_decode(token);
    if (decoded.exp === undefined) {
      return null;
    } else {
      const date = new Date(0);
      date.setUTCSeconds(decoded.exp);
      return date;
    }
  }

}
</code></pre>
",https://stackoverflow.com/questions/57521773/how-to-do-unit-testing-of-function-which-is-depends-on-another-function-using-ka,"['angular', 'unit-testing', 'karma-jasmine']",699,False,0,1
Is Angular component unit testing actually unit testing?,"<p>I'm starting to learn unit testing, and understand the primary objective is to test a system in isolation. Therefore, any dependencies should be stubbed, mocked, etc. </p>

<p>According to the Angular documentation on testing, you should mock whatever is provided via dependency injection. So far, so good. But then, as shown in the code below, you can simply import other required modules, components, directive, pipes through a shared or feature module.</p>

<p>Is this really unit testing then? If the target system under test is a component, isn't this actually testing its entire module?</p>

<p>Or is this just a concession that it'd be near impossible to mock all the requirements in a real world application?</p>

<pre><code>beforeEach(async(() =&gt; {
  const routerSpy = createRouterSpy();

  TestBed.configureTestingModule({
    imports:      [ SharedModule ],
    declarations: [ HeroDetailComponent ],
    providers: [
      { provide: ActivatedRoute, useValue: activatedRoute },
      { provide: HeroService,    useClass: TestHeroService },
      { provide: Router,         useValue: routerSpy},
    ]
  })
  .compileComponents();
}));
</code></pre>
",https://stackoverflow.com/questions/56984970/is-angular-component-unit-testing-actually-unit-testing,"['angular', 'unit-testing', 'jasmine']",768,True,3,3
Mocking of BlazeClientBuilder[IO] to return mock client[IO],"<p>I am using the <code>BlazeClientBuilder[IO].resource</code> method to get <code>Client[IO]</code>. Now, I want to mock the client for unit testing but cannot figure out how to do so. Is there a good way of mocking this and how would I do that?</p>

<pre><code>class ExternalCall(val resource: Resource[IO, Client[IO]], externalServiceUrl: Uri) {
def retrieveData: IO[Either[Throwable, String]] = {
for {
  req &lt;- IO(Request[IO](Method.GET, uri = externalServiceUrl))
  response &lt;- resource.use(client =&gt; {
    client.fetch[String](req)(httpResponse =&gt; {
      if (!httpResponse.status.isSuccess)
        throw new Exception(httpResponse.status.reason)
      else
        httpResponse.as[String]
    })
  })
} yield Right(response)
}
}
</code></pre>

<p>Caller code </p>

<pre><code>new ExternalCall(BlazeClientBuilder[IO](global).resource).retrieveData
</code></pre>
",https://stackoverflow.com/questions/54588089/mocking-of-blazeclientbuilderio-to-return-mock-clientio,"['scala', 'mockito', 'scala-cats', 'io-monad']",1508,True,5,2
flink unit testing - cannot set the context to process all function,"<p>assuming that I have this </p>

<pre><code>class FooProcess extends ProcessAllWindowFunction[String,String, TimeWindow]{
override def process(context: Context, elements: Iterable[String], out: Collector[String]): Unit = ???
}
</code></pre>

<p>I want to write some unit tests to the process method but I am having issues mocking the context </p>

<pre><code>val context =  mock[Context[FooProcess]]
</code></pre>

<p>This import fails (<code>cannot resolve symbol Context</code>) </p>

<pre><code>import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction.Context
</code></pre>

<p>Any idea / best practices for unit testing in flink ?</p>
",https://stackoverflow.com/questions/56315595/flink-unit-testing-cannot-set-the-context-to-process-all-function,"['apache-flink', 'flink-streaming']",770,True,1,1
"Powermock, failed to transform class","<p>I am using Powermock with Spock.  Code I am testing is Java.  Using it to mock a static method.</p>

<pre><code>testCompile group: 'org.mockito', name: 'mockito-core', version: '2.8.9'
testCompile group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.2'
testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.2'
testCompile group: 'org.powermock', name: 'powermock-module-junit4-rule-agent', version: '2.0.2'
</code></pre>

<p>I am unit testing class called: Serializer. 
I am mocking a method getInstance() in MySingleton.</p>

<pre class=""lang-groovy prettyprint-override""><code>@RunWith(PowerMockRunner.class)
@PrepareForTest(MySingleton.class)
class SerializerSpec extends BaseSpecification {

    @Rule
    PowerMockRule mPowerMockRule = new PowerMockRule();

    def ""some test""() {
         // ...
    } 
}
</code></pre>

<p>I get: </p>

<pre><code>java.lang.RuntimeException: java.lang.IllegalStateException: Failed to transform class with name com.MySingleton. Reason: cannot find org.reflections.util.FilterBuilder$Include
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.getTestMethods(PowerMockJUnit44RunnerDelegateImpl.java:105)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.&lt;init&gt;(PowerMockJUnit44RunnerDelegateImpl.java:85)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl.&lt;init&gt;(PowerMockJUnit47RunnerDelegateImpl.java:42)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit49RunnerDelegateImpl.&lt;init&gt;(PowerMockJUnit49RunnerDelegateImpl.java:25)
    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.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:165)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:47)
    at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.createTestDelegators(AbstractTestSuiteChunkerImpl.java:107)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.&lt;init&gt;(JUnit4TestSuiteChunkerImpl.java:69)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.&lt;init&gt;(AbstractCommonPowerMockRunner.java:36)
    at org.powermock.modules.junit4.PowerMockRunner.&lt;init&gt;(PowerMockRunner.java:34)
    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.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.IllegalStateException: Failed to transform class with name com.MySingleton. Reason: cannot find org.reflections.util.FilterBuilder$Include
    at org.powermock.core.classloader.javassist.JavassistMockClassLoader.defineAndTransformClass(JavassistMockClassLoader.java:119)
    at org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java:174)
    at org.powermock.core.classloader.MockClassLoader.loadClassByThisClassLoader(MockClassLoader.java:102)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:147)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:98)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114)
    at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125)
    at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
    at sun.reflect.annotation.AnnotationParser.parseSig(AnnotationParser.java:439)
    at sun.reflect.annotation.AnnotationParser.parseClassValue(AnnotationParser.java:420)
    at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:724)
    at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:531)
    at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:355)
    at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:286)
    at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
    at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)
    at java.lang.Class.createAnnotationData(Class.java:3521)
    at java.lang.Class.annotationData(Class.java:3510)
    at java.lang.Class.getAnnotation(Class.java:3415)
    at org.junit.internal.MethodSorter.getDeclaredMethods(MethodSorter.java:52)
    at org.junit.internal.runners.TestClass.getAnnotatedMethods(TestClass.java:45)
    at org.junit.internal.runners.TestClass.getTestMethods(TestClass.java:31)
    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.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1854)
    at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:816)
    at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:681)
    at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.getTestMethods(PowerMockJUnit44RunnerDelegateImpl.java:103)
    ... 30 more
Caused by: javassist.CannotCompileException: cannot find org.reflections.util.FilterBuilder$Include
    at javassist.expr.NewExpr.replace(NewExpr.java:236)
    at org.powermock.core.transformers.javassist.support.PowerMockExpressionEditor.edit(PowerMockExpressionEditor.java:73)
    at javassist.expr.ExprEditor.loopBody(ExprEditor.java:217)
    at javassist.expr.ExprEditor.doit(ExprEditor.java:96)
    at javassist.CtClassType.instrument(CtClassType.java:1541)
    at org.powermock.core.transformers.javassist.InstrumentMockTransformer.transform(InstrumentMockTransformer.java:41)
    at org.powermock.core.transformers.javassist.AbstractJavaAssistMockTransformer.transform(AbstractJavaAssistMockTransformer.java:40)
    at org.powermock.core.transformers.support.DefaultMockTransformerChain.transform(DefaultMockTransformerChain.java:43)
    at org.powermock.core.classloader.MockClassLoader.transformClass(MockClassLoader.java:184)
    at org.powermock.core.classloader.javassist.JavassistMockClassLoader.defineAndTransformClass(JavassistMockClassLoader.java:102)
    ... 63 more
Caused by: javassist.NotFoundException: org.reflections.util.FilterBuilder$Include
    at javassist.ClassPool.get(ClassPool.java:422)
    at javassist.expr.NewExpr.replace(NewExpr.java:210)
    ... 72 more
</code></pre>
",https://stackoverflow.com/questions/56883567/powermock-failed-to-transform-class,"['mockito', 'spock', 'powermock', 'powermockito']",708,False,1,0
How make code that uses global dynamic properties unit testable?,"<p>A lot of code needs to use some global flag or properties to control the flow of the application. It is necessary for a lot of scenarios to maintain a Dynamic Cache which will have a flag to lock/unlock a particular piece of (new)code.</p>

<p>For all such scenarios I usually write this way:</p>

<pre><code>''' 
void someMethod(Data data){
  if(DynamicProperty.getValue(""OK""))
    // Do Something

}
</code></pre>

<p><code>DynamicPropery</code> is a Singleton which periodically refreshes the cache from the DB.<br/>
The problem with this is Unit testing is little tricky, so far I've used <em>Jmockit</em> to get around that - and it works fine. <br/>But I was wondering if there can be a better way to write a method like that that can be easier for Unit testing.</p>
",https://stackoverflow.com/questions/56505058/how-make-code-that-uses-global-dynamic-properties-unit-testable,"['java', 'unit-testing', 'junit', 'dependency-injection', 'testability']",279,True,2,3
How to unit test a button within an ngfor,"<p>I have a button within a nav tag, which is rendered by looping over a list</p>

<pre><code>&lt;nav *ngFor=""let test of getTests(); let last = last""&gt;
    &lt;button (click)=""clickFunction() &gt;&lt;/button&gt;
&lt;/nav&gt;
</code></pre>

<p>How do I get the click event for the button while unit testing?</p>

<p>This does not work:</p>

<pre><code>let button = fixture.debugElement.query(By.css('button'));
button.nativeElement.click();
</code></pre>

<p>This gives me an error saying that <code>button</code> is null.</p>
",https://stackoverflow.com/questions/56026259/how-to-unit-test-a-button-within-an-ngfor,"['angular', 'unit-testing']",2358,True,6,1
Unable to mock node-fetch using fetch-mock,"<p>I am trying to do unit testing for a simple function which sends a get request, receives a response and then returns a promise object with the success or the failure message. Following is the function:</p>

<pre><code>module.exports.hello = async (event, context) =&gt; {
  return new Promise((resolve, reject) =&gt; {
    fetch(""https://httpstat.us/429"", { headers: { 'Content-Type': 'application/json' } }).then(response =&gt; {
      console.log(response);
      if (response.status == 200) {
        return response;
      } else {
        throw Error(response.status + "": "" + response.statusText);
      }
    }).then(tokenData =&gt; {
      resolve({ status: 200, body: JSON.stringify({ statusText: 'Success' }) });
    }).catch(error =&gt; {
      reject(error.message);
    });
  });
};
</code></pre>

<p>While unit testing, I am using fetch-mock to mock the call to the api and have a custom response. Following is the code:</p>

<pre><code>it('hello returns failure message', (done) =&gt; {
    fetchMock.get('*',  {
        status: 429,
        statusText: ""Too Many Nothings"",
        headers: { 'Content-type': 'application/json' }
     });

    edx.hello(null, null).catch(error =&gt; {
        expect(error).to.equal('429: Too Many Requests');
    }).then(() =&gt; {
        done();
    }).catch(error =&gt; {
        done(error);
    });
});
</code></pre>

<p>But this code is not mocking the fetch request as when I print the response text it is ""Too Many Requests"" which is being sent as a response by the API and not ""Too Many Nothings"" which is being mocked. I am new to NodeJS. Please tell me what am I doing wrong.</p>
",https://stackoverflow.com/questions/54679421/unable-to-mock-node-fetch-using-fetch-mock,"['javascript', 'node.js', 'sinon-chai', 'fetch-mock']",5390,False,2,2
Authenticate user without using factory in unit testing,"<p>I am new to unit testing. I want to authenticate a user without using Factory. I want my testing code to be simple. I don't know how to use the Factory. Here is my code : </p>

<pre><code>public function loginVerify()
{
     $user = factory('App\User')-&gt;create();
}
</code></pre>
",https://stackoverflow.com/questions/55471425/authenticate-user-without-using-factory-in-unit-testing,['laravel'],58,True,0,1
What assert I should use instead &quot;Assert.DoesNotThrow....&quot;?,"<p>I`m following some tutorials about unit testing. The problem is that older versions of xUnit.net provided an ""Assert.DoesNotThrow"" which now is removed. What I should use instead? <br/>(in following tutorial this old assert is used) </p>

<pre><code>   [Fact]
    public void returns_json_response()
    {
        string results = execute(""Batman"");

        Assert.Throws.Nothing((new JavaScriptSerializer().Deserialize&lt;dynamic&gt;(results)));
    }
</code></pre>
",https://stackoverflow.com/questions/56812918/what-assert-i-should-use-instead-assert-doesnotthrow,"['c#', 'xunit.net']",186,True,1,2
Stubbing is not covering my method in unit testing,"<p>I am trying to implementing unit testing by using the stubbing methodology. 
However, when I stub the method, there is no line coverage of the tested class. </p>

<p>Service Class</p>

<pre><code>@Service
@Slf4j
public class Service {

    @Autowired
    private Client client;

    private String doclinkUrl = ""www.website.com""

    public byte[] downloadContent(String objectId) {
        String url = doclinkUrl + ""documents/"" +objectId + ""/binary"";
        return client.target(url).request().get(byte[].class);
    }
}
</code></pre>

<p>Stubbed Service Class</p>

<pre><code>public class ServiceStub extends Service {

    @Override
    public byte[] downloadContent(String objectId) {
        return ""test"".getBytes();
    }

}
</code></pre>

<p>Testing Service Class</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @InjectMocks
    private Service testee;

    @Test
    public void testDownloadContent(){
        testee = new ServiceStub();
        Assert.assertNotNull(testee.downloadContent(""objectId""));
    }

}
</code></pre>
",https://stackoverflow.com/questions/55049258/stubbing-is-not-covering-my-method-in-unit-testing,"['java', 'unit-testing', 'junit', 'mockito', 'stubbing']",1056,True,0,2
How to make Spring Security work in unit-tests?,"<p>I struggle to understand how to test the <code>Spring Boot</code> application with the <code>Spring Security</code> layer.</p>

<p>I have asked similar questions <a href=""https://stackoverflow.com/questions/58401388/how-to-enforce-mockitojunitrunner-fail-without-basic-http-authentication"">How to enforce <code>Spring Security</code> with <code>MockitoJUnit</code> runner?</a> and <a href=""https://stackoverflow.com/questions/58353403/how-to-mock-custom-userservicedetails-in-springsecurity-bean-for-unit-testing"">How to mock customer user service details in <code>Spring Security</code> layer?</a></p>

<ol>
<li><p>I have a custom implementation for <a href=""https://docs.spring.io/spring-security/site/docs/3.2.3.RELEASE/apidocs/org/springframework/security/core/userdetails/UserDetailsService.html"" rel=""nofollow noreferrer""><code>UserDetailsService</code></a> which take data from the database, so naturally, I want to take it from somewhere else during unit-testing phase</p></li>
<li><p>I want to test my web-layer to see if <code>Spring Security</code> works and if all other use-cases work as well.</p></li>
</ol>

<p>How can I achieve both tasks above?</p>

<p><code>SecurityConfig</code> class:</p>

<pre><code>@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            ""/"",
            ""/csrf"",
            ""/swagger-resources"",
            ""/swagger-resources/**"",
            ""/configuration/ui"",
            ""/configuration/security"",
            ""/swagger-ui.html"",
            ""/webjars/**""
    };

    @Autowired
    @Qualifier(""customUserDetailsService"")
    private UserDetailsService userDetailsService;

    private final static Integer bCryptEncryptionLevel = 8;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder(bCryptEncryptionLevel);
    }

    public SecurityConfig() {
        super();
    }

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder.authenticationProvider(authenticationProvider());
        authManagerBuilder.userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
        return authenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                    .antMatchers(AUTH_WHITELIST).permitAll()
                    // allow default swagger docket
                    .regexMatchers(""\\A/v2/api-docs\\Z"").permitAll()
                    // require auth for any other swagger docket
                    .regexMatchers(""\\A/v2/api-docs?.*\\Z"").authenticated()
                    .antMatchers(""/**"").authenticated()
                .and()
                .httpBasic()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
</code></pre>

<p><code>CustomUserDetailsService</code> class:</p>

<pre><code>@Service(""customUserDetailsService"")
@Profile(""!test"")
public class CustomUserDetailsService implements UserDetailsService {
    private final static Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);

    private StringRedisTemplate redisTemplate;
    private RedisProperties redisProperties;

    @Autowired
    public CustomUserDetailsService(RedisProperties redisProperties, StringRedisTemplate redisTemplate) {
        this.redisProperties = redisProperties;
        this.redisTemplate = redisTemplate;
    }


    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        // Do queries to DB and return user if such user exists
    }
}
</code></pre>

<p>I also added <code>CustomUserDetailsServiceTest</code> class for the unit-testing purpose only into the same package but under <code>src/test/java</code>:</p>

<pre><code>@Service(""customUserDetailsService"")
@Profile(""test"")
public class CustomUserDetailsServiceTest implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        @SuppressWarnings(""serial"")
        Map&lt;Object, Object&gt; entries = new HashMap&lt;Object, Object&gt;(){{
            put(""username"", username);
            put(""password_hash"", ""$2a$08$YjMcOsLmbbUB4DYPxqSAxOa3STLjEDovwd2..Uidwp.asyhSi8Y5u"");
            put(""role"", ""ADMIN"");
        }};
        UserEntity user = new UserEntity(entries);
        return new HiccasoftApiUser(user);
    }
}
</code></pre>

<p>How can I use custom implementation for <code>customUserDetailsService</code> in unit-tests while testing web-layer?</p>
",https://stackoverflow.com/questions/58579121/how-to-make-spring-security-work-in-unit-tests,"['java', 'spring', 'spring-boot', 'unit-testing', 'spring-security']",316,False,2,0
Java Simulate Scanner input on console failing with multiple inputs,"<p>I am trying to <strong>simulate</strong> multiple inputs in Java console with the help of Scanner. I need them for Unit testing but its failing only first few values are correctly taken but rest of them are ignored. Please have a look at the following code</p>

<pre><code>String simulatedInput = ""1\n"" + ""2\n"" + ""James\n"" + ""Snow\n"" + ""5\n"" + ""Mango\n"" + ""6\n"";
InputStream in = new ByteArrayInputStream(simulatedInput.getBytes());
Scanner scanner = new Scanner(in);
int index = 0;
if (scanner.hasNextInt()) {
    index = scanner.nextInt();
}
if (index != 1) {
    System.out.println(""#1) Should be 1"");
}

if (scanner.hasNextInt()) {
    index = scanner.nextInt();
}

if (index != 2) {
    System.out.println(""#2) Should be 2"");
}
index = -1;
String value = null;
if (scanner.hasNextLine()) {
    value = scanner.nextLine();
}
if (!""James"".equals(value)) {
    System.out.println(""#3) Should be 'James' but |"" + value + ""|"");
}
if (scanner.hasNextLine()) {
    value = scanner.nextLine();
}
if (!""Snow"".equals(value)) {
    System.out.println(""#4) Should be 'Snow' but |"" + value + ""|"");
}

if (scanner.hasNextInt()) {
    index = scanner.nextInt();
}
if (index != 5) {
    System.out.println(""#5) Should be 5 but "" + index);
}

if (scanner.hasNextLine()) {
    value = scanner.nextLine();
}
if (!""Mango"".equals(value)) {
    System.out.println(""#6) Should be 'Mango' but |"" + value + ""|"");
}

if (scanner.hasNextInt()) {
    index = scanner.nextInt();
}
if (index != 6) {
    System.out.println(""#7) Should be 6 but "" + index);
}

System.out.println(""*** There should be the only line ***"");
</code></pre>

<p>and the result is as follows, test # 1 and 2 passed but rest are failing from input that is expected to be <code>James</code></p>

<pre><code>#3) Should be 'James' but ||
#4) Should be 'Snow' but |James|
#5) Should be 5 but -1
#6) Should be 'Mango' but |Snow|
#7) Should be 6 but 5
*** There should be the only line ***
</code></pre>

<p>Please note I cannot change code, as I am unit testing this code, I can only change my simulated input. Can this be fixed?</p>

<h2>Response to possible duplicate</h2>

<p>This is not a duplicate question, I cannot change the code to consume
extra \n, I can only make changes in simulated input only.</p>
",https://stackoverflow.com/questions/56820225/java-simulate-scanner-input-on-console-failing-with-multiple-inputs,"['java', 'java.util.scanner', 'system.in']",271,False,2,0
Error parsing alert &quot;expr&quot; with regular expression in it,"<p>I'm trying to define an alert rule with ""<strong>expr</strong>"" containing regular-expression</p>

<pre><code>Metric: XYZ-POST-failure-400-1min-rate

- alert: alert_name_here
  expr: __name__=~""(.*)-POST-failure-\d{3}-1min-rate"" &gt; 0
</code></pre>

<p>Unit testing this using ""<strong>promtool</strong>""</p>

<pre><code>Error
group ""group_name"", rule 1, ""alert_name_here"": could not parse expression: parse error at char 10: unexpected character after '=': '~'
</code></pre>

<p>Is this even supported by Prometheus alert manager?
Can someone guide me on what is the correct way to achieve this?</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/58597467/error-parsing-alert-expr-with-regular-expression-in-it,"['prometheus', 'prometheus-alertmanager']",2707,True,4,2
Unit test for if() return; in a function,"<p>html:</p>

<pre><code>&lt;button [disabled]=""isFormValid()""&gt;&lt;/button&gt;
</code></pre>

<p>.ts:</p>

<pre><code>isFormValid() {
    if (this.data.dataForm.valid &amp;&amp; this.flag) {
      if (!!this.testData.data) {
       return !this.testData.data.dataForm.valid;
      } else {
        return true;
      }
    } else {
      return !this.data.dataForm.valid;
    }
  }
</code></pre>

<p>I had a method like this with nested if conditions and multiple return statements. I'm learning unit testing and what could be the best approach to handle this method with multiple unit test cases.</p>
",https://stackoverflow.com/questions/55465362/unit-test-for-if-return-in-a-function,"['angular', 'typescript', 'karma-jasmine']",408,False,0,1
How to unit test guice createinjector method,"<p>I have following main method call where I initialize guice modules using static createInjector method</p>

<pre><code>public static void main(String[] args) {

    Injector injector = Guice.createInjector(Stage.PRODUCTION, new MyServiceModule());
    MyService component = injector.getInstance(MyService.class);
    component.doSomething();
}
</code></pre>

<p>Is there any other way of unit testing below code apart from using power-mockito? Do people test main method like this?</p>
",https://stackoverflow.com/questions/56698406/how-to-unit-test-guice-createinjector-method,"['java', 'unit-testing', 'mocking', 'mockito', 'guice']",377,True,1,1
How to mock laravel HasOne relation from eloquent?,"<p>I have an issue with mocking eloquent HasOne relation for unit testing purposes. </p>

<p>This is the tricky part:</p>

<pre class=""lang-php prettyprint-override""><code>$save-&gt;relationTable()-&gt;create([
    'field_1' =&gt; 'value_1',
    'field_2' =&gt; 'value_2',
    'field_3' =&gt; 'value_3',
]);
</code></pre>

<p>Relation in the model:</p>

<pre class=""lang-php prettyprint-override""><code>public function relationTable(): HasOne
{
    return $this-&gt;hasOne(RelationTable::class);
}
</code></pre>

<p>Particularly error is:</p>

<blockquote>
  <p>Received  Mockery_4_Illuminate_Database_Eloquent_Relations_HasOne::create(), but no expectations were specified</p>
</blockquote>

<p>If anyone knows...</p>
",https://stackoverflow.com/questions/58627366/how-to-mock-laravel-hasone-relation-from-eloquent,"['laravel', 'unit-testing', 'mocking', 'has-one', 'eloquent-relationship']",595,False,0,1
How to mock &quot;this&quot; keyword in Jest Unit Testing,"<p>I need to this code using Jest Unit Testing:</p>

<pre><code>componentDidUpdate(prevProps) {
    if (prevProps.socialMediaId !== this.props.socialMediaId) {
      if (typeof this.window.FB !== 'undefined') {
        this.window.FB.XFBML.parse();
      }
    }
  }
</code></pre>

<p>using the test case:</p>

<pre><code>it('should test componentDidUpdate', () =&gt; {
    props.socialMediaId = '/old_id/';
    const component = mount(&lt;MyComponent {...props} /&gt;);
    this.window.FB = {
      XFBML: {
        parse: () =&gt; {}
      }
    };
    props.socialMediaId = '/new_id/';
    component.setProps(props);
    expect(this.window.FB.XFBML.parse).toHaveBeenCalled();
  });
</code></pre>

<p>But, I'm getting the error:</p>

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

<p>How to fix this issue with ""<strong>this</strong>"" keyword in this case?</p>
",https://stackoverflow.com/questions/54568373/how-to-mock-this-keyword-in-jest-unit-testing,"['javascript', 'reactjs', 'unit-testing', 'this', 'jestjs']",4551,True,0,1
What is the operating principle of IOS Unit Testing Bundle in Xcode 10?,"<p>please ask the operating principle of IOS Unit Testing Bundle in Xcode 10, such as how the unit test Bundle is compiled? How does the test cases execute? What is the relationship with the tested APP?</p>
",https://stackoverflow.com/questions/54059675/what-is-the-operating-principle-of-ios-unit-testing-bundle-in-xcode-10,"['unit-testing', 'xctest']",34,True,0,1
Mocking of extension method result in System.NotSupportedException,"<p>I'm unit testing a ClientService that uses the <code>IMemoryCache</code> interface:</p>

<p>ClientService.cs:</p>

<pre><code>public string Foo()
{        
    //... code

    _memoryCache.Set(""MyKey"", ""SomeValue"", new TimeSpan(0, 0, 60));
}
</code></pre>

<p>When I try to mock the <code>IMemoryCache</code>'s <code>Set</code> extension with:</p>

<pre><code>AutoMock mock = AutoMock.GetLoose();

var memoryCacheMock = _mock.Mock&lt;IMemoryCache&gt;();

string value = string.Empty;

// Attempt #1:
memoryCacheMock
     .Setup(x =&gt; x.Set&lt;string&gt;(It.IsAny&lt;object&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;TimeSpan&gt;()))
     .Returns("""");

// Attempt #2:
memoryCacheMock
    .Setup(x =&gt; x.Set(It.IsAny&lt;object&gt;(), It.IsAny&lt;object&gt;(), It.IsAny&lt;TimeSpan&gt;()))
    .Returns(new object());
</code></pre>

<p>It throw an exception of:</p>

<blockquote>
  <p>System.NotSupportedException: Unsupported expression: x =>
  x.Set(It.IsAny(), It.IsAny(),
  It.IsAny())
      Extension methods (here: CacheExtensions.Set) may not be used in setup / verification ex</p>
</blockquote>

<p>This is the Cache extension of the namespace <code>Microsoft.Extensions.Caching.Memory</code></p>

<pre><code>public static class CacheExtensions
{
   public static TItem Set&lt;TItem&gt;(this IMemoryCache cache, object key, TItem value, TimeSpan absoluteExpirationRelativeToNow);
}
</code></pre>
",https://stackoverflow.com/questions/57705394/mocking-of-extension-method-result-in-system-notsupportedexception,"['c#', '.net-core', 'mocking', 'moq', 'extension-methods']",17737,True,14,1
how to fix unexpected component declaration by module while running test?,"<p>I am trying to perform unit testing on my angular application which has two components. root AppComponent and a myFormComponent. I want to perform unit testing on the form fields available in the myFormComponent. </p>

<p>I have went through all the answers provided here but none seems to work for me. The answers provided are for problems while running the application but my problem is when i run the test using ""npm run test"".</p>

<p>//app.module.ts</p>

<pre><code>  import { BrowserModule } from ""@angular/platform-browser"";
    import { NgModule } from ""@angular/core"";

    import { AppComponent } from ""./app.component"";
    import { MyFormComponent } from ""./my-form/my-form.component"";
    import { FormsModule, ReactiveFormsModule } from ""@angular/forms"";

    @NgModule({
    declarations: [AppComponent, MyFormComponent],
    imports: [BrowserModule, FormsModule, ReactiveFormsModule],
    providers: [],
    bootstrap: [AppComponent]
    })
    export class AppModule {}
</code></pre>

<p>//my-form.component.spec.ts</p>

<pre><code>    import { async, ComponentFixture, TestBed } from 
    ""@angular/core/testing"";

    import { MyFormComponent } from ""./my-form.component"";
    import { DebugElement } from ""@angular/core"";
    import { By } from ""@angular/platform-browser"";
    import { AppComponent } from ""../app.component"";

    describe(""MyFormComponent"", () =&gt; {
    let component: MyFormComponent;
    let fixture: ComponentFixture&lt;MyFormComponent&gt;;

    let debugElement: DebugElement;
    let htmlElement: HTMLElement;

    beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
    declarations: [MyFormComponent]
    }).compileComponents();
    }));

    beforeEach(() =&gt; {
    fixture = TestBed.createComponent(MyFormComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();

    // debugElement = fixture.debugElement.query(By.css(""p""));
    // htmlElement = debugElement.nativeElement;
    });

    test(""check dummy"", () =&gt; {
    const res = 2 * 3;
    expect(res).toBe(6);
  });
});
</code></pre>

<p>Actually the test case should pass but its not happening. I am getting an error ""Unexpected value 'MyFormComponent' declared by the module 'DynamicTestModule'. Please add a @Pipe/@Directive/@Component annotation."". When I remove the first ""beforeEach"" method, it seems to work.</p>
",https://stackoverflow.com/questions/56664001/how-to-fix-unexpected-component-declaration-by-module-while-running-test,"['angular', 'jestjs']",31,False,1,0
How to test logic in ComponenWillMount using Enzyme/Jest,"<p>I am beginner in react unit testing with enzyme/jest,
I want to test my logic inside componentWillMount method.
I want to test based on my context object whether redirect happens or not based on my business logic</p>

<pre><code>class ActivateSF extends Component {
  constructor(props) {
    super(props);
    this.className = 'ActivateSF.js'
    this.state = {
      messages: null,
     }
  }

  render() {
    return (
      &lt;SDPActivateInterstitialUI
        context={this.props.context}
        messages={this.state.messages}
      /&gt;
    );
  }

  componentWillMount() {
    let context = this.props.context

    if(!context.userInfo){      
      return this.callIdentify(context)
    }

    let externalLP = ExternalLandingPageUtil.getExternalLandingPageUrl(context);
if (externalLP) {
      window.location.replace(`${externalLP}`);
      return;
    }

    if (context.userInfo)
    {
      console.log(""user identified prior to activation flow"")

        if (UserInfoUtil.isSubsribedUser(context))
        {
           window.location = '/ac'
        }

        else
        {
            this.callPaymentProcess(context)
        }
    }

  }
</code></pre>
",https://stackoverflow.com/questions/57628047/how-to-test-logic-in-componenwillmount-using-enzyme-jest,"['javascript', 'reactjs', 'jestjs', 'enzyme']",199,False,1,1
Ionic 4: Error: Can&#39;t resolve all parameters for StateObservable: (?),"<p>I'm trying to run a particular spec file i am facing issue give as given below </p>

<p><a href=""https://i.stack.imgur.com/Nu3Hg.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Nu3Hg.png"" alt=""image""></a></p>

<p>I'm new to Unit Testing I'm not sure Why i'm getting this issue. any suggestion will help me to solve this issue</p>
",https://stackoverflow.com/questions/58968540/ionic-4-error-cant-resolve-all-parameters-for-stateobservable,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'ionic4']",49,False,1,0
Not success trying to test my catch block inside of then,"<p>I'm new on the unit testing code and lost! I'm trying throws an error for the following function to cover the catch block, but not having success and I don't know why.</p>

<p>Function:</p>

<pre class=""lang-js prettyprint-override""><code>public initialize(): Promise&lt;this&gt; {
    return Promise.resolve()
      .then(() =&gt; this.getQueries())
      .catch((error: Error) =&gt; {
        this.connector.localLog.error(error, 'Failed to initialize Rest Poller Launcher:');
        throw error;
      });
  }
</code></pre>

<p>Unit test:</p>

<pre class=""lang-js prettyprint-override""><code>it('should getQueries return error', () =&gt; {
  launcher.initialize()
    .then(() =&gt; {
      this.getQueries = stub().throws('TypeError');
    })
    .catch((error: Error) =&gt; {
      expect(error.message).equals('Failed to initialize Rest Poller Launcher:');
    });
});
</code></pre>

<p>Please help me</p>
",https://stackoverflow.com/questions/55578973/not-success-trying-to-test-my-catch-block-inside-of-then,"['javascript', 'node.js', 'typescript', 'unit-testing']",133,True,1,1
How Mock throw from axios,"<p>How I can to mock in my unit testing the throw exception.</p>

<p>I try to test like this : <code>expect(service.methodA).toThrowError('error');</code> </p>

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

<p>Expected the function to throw an error matching:
      <code>""error""</code>. But it didn't throw anything.</p>

<pre><code>return this.service.post(
            URL,
        ).pipe(
            map(response =&gt; response.data),
            catchError(error =&gt; {
              throw new Error('error');
             })
        ).toPromise();
</code></pre>

<p>Thank you</p>
",https://stackoverflow.com/questions/57300345/how-mock-throw-from-axios,"['javascript', 'typescript', 'unit-testing', 'vue.js']",1449,True,0,1
Data is not displaying using Jest,"<p>I am doing unit testing for the following <code>react</code> component:</p>

<pre class=""lang-js prettyprint-override""><code>var userData=null;
class Login extends React.Component 
{
    getData() {
        $.ajax({
            type: ""GET"",
            url: myURL,
            success: function(data) {
               console.log(data);
               userData=data;
            },
            error: function(){
                console.log(""ERROR"");
            }
        });
        console.log(userData);
    }

    render() {
        return(
            //some stuff
        );
    }
}
export default Login;

</code></pre>

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

<pre class=""lang-js prettyprint-override""><code>test(""Data should load"",()=&gt;{
  const wrapper = mount(&lt;Login/&gt;);
  const instance = wrapper.instance();
  instance.getData();
})

</code></pre>

<p>When I run this test file using <code>npm run test</code>, <code>userData is</code> coming as <code>null</code> and success function of ajax is not executing.
Where I did mistake?
Thanks in advance.</p>
",https://stackoverflow.com/questions/58489318/data-is-not-displaying-using-jest,"['reactjs', 'jestjs']",492,True,0,1
"WARN [middleware:karma]: Invalid file type, defaulting to js. ts","<p>When I run unit testing via karma, I got those warning:</p>

<pre><code>12 02 2019 14:01:05.740:WARN [middleware:karma]: Invalid file type, defaulting to js. ts
12 02 2019 14:01:05.741:WARN [middleware:karma]: Invalid file type, defaulting to js. ts
</code></pre>

<p>I assumed that the type of the <code>karma.conf.js</code> file caused the issue, so I changed it to <code>karma.conf.ts</code>.</p>

<p>However the issue still happened, so it would be great if someone can tell me how to disable this warning.</p>

<p>Below is my karma.conf.ts file</p>

<pre><code>module.exports = function karmaConfig(config) {
    config.set({

        singleRun: true,

        frameworks: [
            'jasmine'
        ],

        files: [
            'sdk/**/*.spec.ts'
        ],

        preprocessors: {
            'sdk/**/*.spec.ts': ['webpack', 'sourcemap'],
            'sdk/**/!(*.spec).ts': ['coverage']
        },

        browsers: [
            'PhantomJS'
        ],

        reporters: [
            'progress',
            'coverage',
            'junit'
        ],

        coverageReporter: {
            dir: 'coverage/',
            reporters: [
                { type: 'text-summary' },
                { type: 'html' },
                {
                    type: 'lcov',
                    dir: 'reports',
                    subdir: 'coverage'
                }
            ]
        },

        junitReporter: {
            outputFile: 'reports/junit/TEST-karma.xml',
            useBrowserName: false
        },

        transports: ['polling'],

        webpack: require('./webpack.config'),

        webpackMiddleware: {
            stats: 'errors-only'
        },

        logLevel: config.LOG_INFO,

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

<p>I use webpack <code>4.16.5</code> and karma <code>4.0.0</code></p>
",https://stackoverflow.com/questions/54650812/warn-middlewarekarma-invalid-file-type-defaulting-to-js-ts,"['typescript', 'webpack', 'karma-jasmine', 'karma-runner']",7196,True,16,2
How would I go about unit testing this function in Kotlin?,"<p>I'm pretty new to unit testing. I've been given the task of testing this code. I understand that I have to use assertEquals to check if for example if 
RegionData.Key.DEV returns VZCRegion.Development. 
Any help would be appreciated.     </p>

<pre><code>fun fromCakeSliceRegion(cakeSliceIndex: RegionData.Key): VZCRegion {

    return when (cakeSliceIndex) {
        RegionData.Key.DEV -&gt; VZCRegion.Development
        RegionData.Key.EU_TEST -&gt; VZCRegion.EuropeTest
        RegionData.Key.US_TEST -&gt; VZCRegion.UnitedStatesTest
        RegionData.Key.US_STAGING -&gt; VZCRegion.UnitedStatesStage
        RegionData.Key.EU_STAGING -&gt; VZCRegion.EuropeStage
        RegionData.Key.LOCAL, RegionData.Key.EU_LIVE -&gt; VZCRegion.Europe
        RegionData.Key.AP_LIVE, RegionData.Key.US_LIVE -&gt; VZCRegion.UnitedStates
        RegionData.Key.PERFORMANCE, RegionData.Key.PERFORMANCE -&gt; VZCRegion.Performance
    }
</code></pre>
",https://stackoverflow.com/questions/58727442/how-would-i-go-about-unit-testing-this-function-in-kotlin,"['unit-testing', 'kotlin', 'junit4']",140,True,0,2
Precommit hook not triggering even after failures,"<pre><code>""scripts"": {
   ""precommit"": ""pretty-quick --staged &amp; npm run lint &amp; npm run test"",
   ""lint"": ""eslint 'src/**/*.{js,jsx}' --quiet --fix"",
   ""test"": ""cross-env CI=true react-scripts test --env=jsdom --coverage""
}
</code></pre>

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

<p>Even after the failure of lint, the code gets committed. How to prevent this?</p>

<p>If i dont add <code>cross-env CI=true</code>, the jest test cases wont break. I am trying to perform for both linting and unit testing for clean code. </p>
",https://stackoverflow.com/questions/57314400/precommit-hook-not-triggering-even-after-failures,"['javascript', 'reactjs', 'git', 'eslint', 'husky']",590,False,0,2
Failed to create Environment bean in SpringRunner,"<p>I need to read properties for unit testing in one of the test class using Environment bean but spring is failed to create environment bean.</p>

<pre class=""lang-java prettyprint-override""><code>@RunWith(SpringRunner.class)
@TestPropertySource(locations = ""/application-test.properties"")
public class CardTest {

  @Autowired
  Environment environment;

  @Test
  public void givenPropertyFetchesAndValidatesTheValue() {
    String output = environment.getProperty(""test"");
    assertThat(output).isEqualTo(""502123"");
  }
}
</code></pre>

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

<blockquote>
  <p>Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.core.env.Environment]: Specified class is an interface. </p>
</blockquote>

<p>Please help</p>
",https://stackoverflow.com/questions/57449210/failed-to-create-environment-bean-in-springrunner,"['java', 'springrunner']",246,False,2,0
Unit testing SQL scripts,"<p>For below script written in <code>.sql</code> files:</p>

<pre><code>if not exists (select * from sys.tables where name='abc_form')
    CREATE TABLE abc_forms (
        x BIGINT IDENTITY, 
        y VARCHAR(60), 
        PRIMARY KEY (x)
    )
</code></pre>

<hr>

<p>Above script has a bug in table name.</p>

<p>For programming languages like Java/C, compiler help resolve most of the name resolutions</p>

<p>For any SQL script, How should one approach unit testing it? static analysis...</p>
",https://stackoverflow.com/questions/55183385/unit-testing-sql-scripts,"['database', 'unit-testing', 'tsql', 'sonarqube']",426,True,2,2
Get HTTP status from IHttpActionResult Return Value,"<p>In C#, how in the world do I get the HTTP status number (200) and return text (""ok"") in this case for unit testing for an API controller? I think I've tried everything. Surely this is a common need. Thanks. </p>

<pre><code>public IHttpActionResult Get(string appServer, string action)
{
   return Ok(""ok"");
}
</code></pre>

<hr>

<pre><code>[TestMethod]
public void AppPoolTestStart()
{
   AppPoolController controller = new AppPoolController();
   IHttpActionResult result = controller.Get(""MyServer"", ""start"");
   Assert.??? ; // check for 200 or ""ok"" 
}
</code></pre>
",https://stackoverflow.com/questions/54316798/get-http-status-from-ihttpactionresult-return-value,"['http', 'get', 'status']",6181,True,2,1
How to unit test $uibModal in Jasmine? (unit testing injected library),"<p>So I am using $uibModal from bootstrap and I have the following code in my AngularJS controller:</p>

<pre><code>vm.openPopup = function() {
  $uibModal.open({
    templateUrl: 'popup.html',
    controller: function() {
       var modal = this;

       modal.hi = function() {
         // some code here
       }
    }
  });
};
</code></pre>

<p>How would I go about calling the modal.hi function in Jasmine and unit testing it to make sure it works correctly?</p>
",https://stackoverflow.com/questions/57319381/how-to-unit-test-uibmodal-in-jasmine-unit-testing-injected-library,"['angularjs', 'unit-testing', 'jasmine', 'karma-jasmine', 'angular-ui-bootstrap']",542,True,0,1
Unit test cases for a method which checks the device type,"<p>I am very new to unit testing. I have the following method for which I need to writes a test Method. Please help me with this.</p>

<p>Following is my method:</p>

<pre><code>    private bool IsMobile()
    {
        var userAgent = _httpContextAccessor.HttpContext.Request.Headers[""User-Agent""].ToString() ?? """";
        return new Regex(@""Android|BlackBerry|iPhone|iPad|iPod|IEMobile"", RegexOptions.IgnoreCase | RegexOptions.Multiline).IsMatch(userAgent);
    }


    public DeviceTypesEnum CheckDevice()
    {
        string userAgent = _httpContextAccessor.HttpContext.Request.Headers[""User-Agent""].ToString() ?? """";
        var tabletDevices = new Regex(@""ipad|android|android 3.0|xoom|sch-i800|playbook|tablet|kindle|nexus"",
            RegexOptions.IgnoreCase | RegexOptions.Multiline);

        //Tablet Pc
        if (userAgent.ToLower().Contains(""tablet pc""))
        {
            return DeviceTypesEnum.TabletPc;
        }

        var isMobile = IsMobile();
        // is desktop/ tablet block
        if (!isMobile)
        {
            return tabletDevices.IsMatch(userAgent) ? DeviceTypesEnum.Tablet : DeviceTypesEnum.Desktop;
        }

        // is mobile section block 
        var isPad = new Regex(@""ipad"", RegexOptions.IgnoreCase | RegexOptions.Multiline).IsMatch(userAgent) ||
                    !(userAgent.ToLower().Contains(""android"") &amp;&amp; userAgent.ToLower().Contains(""mobile""));
        return isPad ? DeviceTypesEnum.Tablet : DeviceTypesEnum.Mobile;
    }
</code></pre>

<p>I have tried this which is failing though:</p>

<pre><code>public class DetetctDeviceTest
{
    protected IDetectDevice Target;

    [TestInitialize]
    public virtual void Initialize()
    {

        Target = AutoMocker.CreateInstance&lt;DetectDevice&gt;();            
    }

    [TestMethod]
    public void CheckDeviceTest()
    {
        var obj = Target.CheckDevice();

        Assert.IsNotNull(obj);           

    }
}
</code></pre>
",https://stackoverflow.com/questions/56185007/unit-test-cases-for-a-method-which-checks-the-device-type,"['c#', 'unit-testing']",202,True,0,1
How do I get mock-fs to properly mock the filesystem,"<p>I have a <code>File</code> class that basically is a wrapper for <code>fs.readFileSync</code> and <code>fs.writeFile</code>. I'm trying to mock the filesystem for unit testing, but am unable to make it work. Any help is much appreciated.</p>

<p>My <code>File</code> class:</p>

<pre><code>'use strict'
const fs = require('fs')
module.exports = class File {
    constructor() {}
    async savePicture(filename, imageData) {
        if (filename === undefined || filename === '') throw new Error(`filename can't be empty`)
        if (imageData === undefined || imageData === '') throw new Error(`imageData can't be empty`)
        fs.writeFile(filename, imageData, 'binary', (err) =&gt; {
            if (err) throw new Error(err)
            console.log('File saved.')
        })
    }
    readPicture(filename) {
        if (filename === undefined || filename === '') throw new Error(`filename can't be empty`)
        try {
            fs.readFileSync(filename, 'binary')
        } catch(err) {
            throw new Error(`file doesn't exist`)
        }
    }
}
</code></pre>

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

<pre><code>'use strict'

const mock = require('mock-fs')

const File = require('../modules/file')
const fs = require('fs')

beforeAll( async() =&gt; {
})

afterAll( async() =&gt; {
})

describe('savePicture()', () =&gt; {
    beforeEach( async() =&gt; {
        mock({
            'test': {
                'foo': 'bar'
            }
        });
    })
    afterEach( async() =&gt; {
        afterEach(mock.restore);
    })

    test(`binary information has to be correctly saved`, async done =&gt; {
        expect.assertions(1)
        try {
            const file = new File()
            file.savePicture('test/foobar', 'raboof')
            fs.readFile('test/foobar', 'binary', (err, data) =&gt; {
                if (err) throw new Error(err)
                expect(data).toBe('raboof')
            })
        } catch(err) {
            done.fail('test failed')
        } finally {
            done()
        }
    })
})

describe('readPicture()', () =&gt; {
    beforeEach( async() =&gt; {
        mock({
            '/test': {
                'foo': 'bar'
            }
        });
    })
    afterEach( async() =&gt; {
        afterEach(mock.restore);
    })

    test(`binary information has to be correctly read`, async done =&gt; {
        expect.assertions(1)
        try {
            const file = new File()
            expect(file.readPicture('test/foo')).toBe('bar')
        } catch(err) {
            done.fail('test failed')
        } finally {
            done()
        }
    })
})
</code></pre>
",https://stackoverflow.com/questions/58686671/how-do-i-get-mock-fs-to-properly-mock-the-filesystem,"['javascript', 'node.js']",474,False,0,1
Triangle javascript problem/ Unit testing not working (Jasmine),"<p>I written code to determine if a triangle is equilateral, isosceles, or scalene. Next, I'm suppose to test it using Jasmine but my code keep failing. I am very new to unit testing. Please help me!</p>

<p>TriangleSpec:</p>

<pre><code>describe('Determine if a triangle is equilateral, isolene, scalene', 
function () {
  it('equilateral triangles have equal sides', function () {
    var triangle = new isTriangle (5, 5, 5)
    expect(triangle).toEqual(""Equilateral"");
  });
</code></pre>

<p>Triangle.js:</p>

<pre><code>function isTriangle(side1, side2, side3){
  if (side1 === 0 || side2 === 0 || side3 === 0) {
      console.log(""Error"");
  } else if (side1 &lt; 0 || side2 &lt; 0 || side3 &lt; 0) {
      console.log(""Error"");
  } else if (side1 + side2 &lt;= side3 || side1 + side3 &lt;= side2 || side2 +
    side3 &lt;= side1) {
    console.log(""Error"");
  }
  else if (side1 == side2 &amp;&amp; side2 == side3) {
    console.log(""Equilateral"");
  } else if (side1 === side2 || side2 === side3 || side1 === side3) {
    console.log(""Isosceles"");
  } else {
    console.log(""Scalene"");
  }
};

isTriangle(6, 6, 5);
</code></pre>
",https://stackoverflow.com/questions/56924241/triangle-javascript-problem-unit-testing-not-working-jasmine,"['javascript', 'unit-testing', 'jasmine']",202,False,0,1
JUnit to check if new API contains enum,"<p>Im new to unit testing and I want to check if new API contains specified enum. What should I change instead of <code>is(true)</code> because now it's returning boolean but I need List?</p>

<p>Enum class: </p>

<pre><code>public enum SupportingColor
{
    GREEN,
    BLACK
}
</code></pre>

<p>Supporting color method:</p>

<pre><code>public List&lt;SupportingColor&gt; supportingColor() {
    return configuration.supportingColor();
}
</code></pre>

<p>Test case:</p>

<pre><code>    @Test
    public void NEW_API_hasBlack() {
        ApiVersionFeatures features = ApiVersionFeatures.getByApiVersion(ApiVersion.NEW_API);

        assertThat(features.supportingColor(), is(true));
    }
</code></pre>
",https://stackoverflow.com/questions/55121647/junit-to-check-if-new-api-contains-enum,"['java', 'junit', 'enums']",316,True,0,2
Cannot access includeAndroidResource It is private in UnitTestOptions,"<p>I was trying <strong>Kotlin Gradle Script</strong> and <strong>Android Testing</strong>.</p>

<p>When I try to configure android resource for Testing I get the following error : </p>

<blockquote>
  <p>Cannot access includeAndroidResource It is private in UnitTestOptions.</p>
</blockquote>

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

<p>What is the proper way to <strong>enable</strong> using <strong>android Resource in Android Unit testing?</strong> </p>
",https://stackoverflow.com/questions/56107180/cannot-access-includeandroidresource-it-is-private-in-unittestoptions,"['android', 'android-gradle-plugin', 'build.gradle', 'android-testing', 'gradle-kotlin-dsl']",1534,True,5,1
Export pure functional component without decorators,"<p>I'm trying to export a component without the decorators (connect() in this case)
for unit testing with <code>jest</code>.</p>

<p>So, how could I do this:</p>

<pre><code>import React, { Component } from 'react';
import { connect } from 'react-redux';

export class Header extends Component {
    render(){
        return &lt;pre&gt;Header&lt;/pre&gt;
    }
}

export default connect()(Header);
</code></pre>

<p>With this component (the export at the beginning doesn't work, it stills exports the connected component)</p>

<pre><code>export let Header = props =&gt; {
    render(){
        return &lt;pre&gt;Header&lt;/pre&gt;
    }
}

Header = connect()(Header);

export default Header;
</code></pre>
",https://stackoverflow.com/questions/56071594/export-pure-functional-component-without-decorators,"['javascript', 'reactjs', 'unit-testing', 'redux', 'jestjs']",507,True,1,2
Testing callback function with big arrow function,"<p>I've got a function that is a callback and receives another callback .</p>

<pre><code>const filterDays = (daysLimit, cb)=&gt; {
   return (err, items) =&gt; {
      if(err) return cb(err);
      return cb(undefined, items.filter(item =&gt; item.daysOld &lt; daysLimit));
   };
};
</code></pre>

<p>The function is working but I want to do some unit testing and I wonder how to pass directly some predefined data to test it. Something like...?</p>
",https://stackoverflow.com/questions/59034638/testing-callback-function-with-big-arrow-function,"['node.js', 'unit-testing', 'callback', 'arrow-functions']",70,False,0,1
Unittest that every element matches in 2 lists,"<p>Unit testing that 2 lists are the same in Python. Seems like it fails if they're not in order. Thought about sorting them first or converting to a set. But the set method isn't true, if there's duplicate etc</p>

<pre><code>l1 = ['c-00355', 'b-0ae53', 'c-07d32']
l2 = ['b-0ae53', 'c-07d32' ,'c-00355']

l1 == l2
False

set(l1) == set(l2)
True

sorted(l1) == sorted(l2)
True

</code></pre>
",https://stackoverflow.com/questions/55698300/unittest-that-every-element-matches-in-2-lists,"['python', 'list', 'unit-testing', 'comparison']",34,True,0,1
how to run test on img tag while doing unit testing with enzyme on react component,"<p>i am doing unit testing with enzyme, and i am not able to select the image tag into the find()....so i am getting this error
""TypeError: Cannot read property 'have' of undefined</p>

<pre><code>  34 |         //const sb = shallow(&lt;sliderBanner store={store} /&gt;);
  35 |         //expect(Wrapper.find(&lt;img /&gt;)).to.have.property(""img"");
&gt; 36 |         expect(Wrapper.getElement(""img"")).to.have.property(""src"");
     |         ^
  37 |     });
  38 | });""
</code></pre>

<p>i have written this test case....</p>

<pre><code>test(""imgage source is valid"", () =&gt; {
        const Wrapper = shallow(&lt;MainBanner store={store} /&gt;);
        //const sb = shallow(&lt;sliderBanner store={store} /&gt;);
        //expect(Wrapper.find(&lt;img /&gt;)).to.have.property(""img"");
        expect(Wrapper.getElement(""img"")).to.have.property(""src"");
</code></pre>
",https://stackoverflow.com/questions/57003574/how-to-run-test-on-img-tag-while-doing-unit-testing-with-enzyme-on-react-compone,"['reactjs', 'jestjs', 'enzyme']",98,False,0,1
Test coverage for many AND/OR conditions in one statement,"<p>Example statement:</p>

<pre><code>if (conditionA &amp;&amp; conditionB &amp;&amp; conditionC &amp;&amp; conditionD) {
    return true;
}
</code></pre>

<p>I could write unit tests for all 2^4 combinations, but that would easily go out of hand if more conditions are added. </p>

<p>What should be my unit testing strategy to cover all conditions for a statement like this? Is there any other way to make the code more robust?</p>
",https://stackoverflow.com/questions/54155711/test-coverage-for-many-and-or-conditions-in-one-statement,"['java', 'unit-testing', 'junit', 'code-coverage', 'mc-dc']",17476,True,11,5
"QTest, and void Functions","<p>I'm approaching to Unit testing for the first time in QtCreator, and I wonder how I can Test functions that does not have a return type.
Like:</p>

<p>rgb_process.h:</p>

<pre><code>class RGB_process : Process
{
public:
    RGB_process(cv::Mat&amp; src, cv::Mat&amp; dst, int exp = 0, double c = 1, int r = 0, int g = 0, int b = 0);

    virtual void doProcess() override;

private:
    int exposure_Val;
    double contrast_Val;
    int red_Val;
    int green_Val;
    int blue_Val;
};
</code></pre>

<p>rgb_process.cpp:</p>

<pre><code>#include ""rgb_process.h""

RGB_process::RGB_process(cv::Mat&amp; src, cv::Mat&amp; dst, int exp, double c, int r, int g, int b)
    : Process (src, dst), exposure_Val(exp), contrast_Val(c), red_Val(r), green_Val(g), blue_Val(b){
}

void RGB_process::doProcess(){

    for(int i = 0; i &lt; src.rows; i++)
        for(int j = 0; j &lt; src.cols; j++)
            for(int k = 0; k &lt; 3; k++){
                if(k == 0)  //_R
                    dst.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;((src.at&lt;cv::Vec3b&gt;(i,j)[k] + exposure_Val + red_Val )*(259 * (contrast_Val + 255) / (255 * (259 - contrast_Val))));
                if(k == 1)  //_G
                    dst.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;((src.at&lt;cv::Vec3b&gt;(i,j)[k] + exposure_Val + green_Val )*(259 * (contrast_Val + 255) / (255 * (259 - contrast_Val))));
                if(k == 2)  //_B
                    dst.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;((src.at&lt;cv::Vec3b&gt;(i,j)[k] + exposure_Val + blue_Val )*(259 * (contrast_Val + 255) / (255 * (259 - contrast_Val))));
            }
}
</code></pre>

<p>I can't find any kind of examples on the net, similar to my needs.</p>
",https://stackoverflow.com/questions/57004156/qtest-and-void-functions,"['c++', 'qt', 'unit-testing', 'testing', 'qt-creator']",407,True,2,1
How to write unit test case for below TS function using jasmine,"<p>I am trying to write unit testing for the below function (comparevalues). But I could not mock the data to cover the branch.
TS :</p>

<pre><code>  public sortChange(sort: SortDescriptor[]): void {
    this.sort = sort;
    this.SelectedData.sort(this.compareValues(this.sort[0].field, this.sort[0].dir));
}

public compareValues(key: any, order: any) {
  return function(a, b) {
      if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
          // property doesn't exist on either object
          return 0;
      }

      const varA = (typeof a[key] === 'string') ?
          a[key].toUpperCase() : a[key];
      const varB = (typeof b[key] === 'string') ?
          b[key].toUpperCase() : b[key];

      let comparison = 0;
      if (varA &gt; varB) {
          comparison = 1;
      } else if (varA &lt; varB) {
          comparison = -1;
      }
      return (
          (order === 'desc') ? (comparison * -1) : comparison
      );
  };
}
</code></pre>

<p>kindly help me to write unit test case for the <strong>'if', 'else'</strong> condition in ""comparevalues"" function</p>
",https://stackoverflow.com/questions/58932054/how-to-write-unit-test-case-for-below-ts-function-using-jasmine,"['unit-testing', 'angular7']",268,False,0,1
How to display consol.log() result in browser terminal or other,"<p>I use Jest framework for unit testing,when i use consol.log() for debugging purpose like below:</p>

<pre><code>  it('should create', () =&gt; {
    console.log(component.selectComponentRef);
    expect(component).toBeTruthy();
  });
</code></pre>

<p>it displays in visual-studio terminal,i would like to display console.log() results in browser terminal or other,do you know how to achive that?</p>
",https://stackoverflow.com/questions/57843108/how-to-display-consol-log-result-in-browser-terminal-or-other,"['angular', 'visual-studio', 'unit-testing', 'debugging']",119,False,0,1
Interactive debugger for react&#39;s react-scripts test,"<p>Is there an interactive debugger for <code>react-scripts tests</code>, (unit testing on the terminal, not the browser) I've seen some examples with VSCode, yet I don't want to switch editors just for this. I've in my mind something like pdb for Python. Any ideas?</p>
",https://stackoverflow.com/questions/55541451/interactive-debugger-for-reacts-react-scripts-test,"['reactjs', 'debugging', 'jestjs', 'ipdb']",76,False,0,0
How to unit test React components with &#39;react-testing-library&#39;,"<p>I'm using <code>react-testing-library</code> for unit testing React components.</p>

<pre><code>import React from 'react'
import 'react-testing-library/cleanup-after-each'
import {fireEvent, render, cleanup} from 'react-testing-library'
import MyComponent from '../MyComponent';

const translations = require('../../translations');

afterEach(cleanup);

describe('test MyComponent', () =&gt; {
   it('render functional component', () =&gt; {
       // extract container which is 'HTMLDivElement'
        const {container} = render(&lt;MyComponent translations={translations} /&gt;)
})
</code></pre>

<p>How do I manipulate the container element as a DOM element? E.g. </p>

<pre><code>console.log(container.classList, container.id, container.innerHTML);
</code></pre>

<p>using the props and methods listed at: <a href=""https://developer.mozilla.org/en-US/docs/Web/API/Element"" rel=""nofollow noreferrer"">https://developer.mozilla.org/en-US/docs/Web/API/Element</a>. I can't get any values so far.</p>
",https://stackoverflow.com/questions/55666873/how-to-unit-test-react-components-with-react-testing-library,"['javascript', 'reactjs', 'jestjs', 'enzyme', 'react-testing-library']",189,False,0,0
Not sending test folder to production in node express app,"<p>I am building a node express app, We ship package.json to production but that includes code for unit testing as well. So should i make two package.json one for production and one for development? How can this problem be solved?</p>
",https://stackoverflow.com/questions/55606535/not-sending-test-folder-to-production-in-node-express-app,"['node.js', 'express', 'mean-stack', 'mean']",42,False,0,1
Can i get the type of object for which new operator is used inside the overloaded new operator?,"<p>Well i have this function overload:</p>

<pre><code>static bool returnNull;    
void* operator new(const std::size_t size, const std::nothrow_t&amp;) noexcept
{
    void* address{ nullptr };
    if (!returnNull)
    {
        address = operator new(size);
    }
    return address;
}
</code></pre>

<p>And i want to make something like:</p>

<pre><code>void* operator new(const std::size_t size, const std::nothrow_t&amp;) noexcept
{
    if (typeObject == AnimalClass)
        return nullptr;
    void* address{ nullptr };
    if (!returnNull)
    {
        address = operator new(size);
    }
    return address;
}
</code></pre>

<p>So, i need this functionality for unit testing a builder that have many new calls, so i want to fail a specific allocation based on Class that should be alocated</p>
",https://stackoverflow.com/questions/55337149/can-i-get-the-type-of-object-for-which-new-operator-is-used-inside-the-overloade,"['c++', 'c++11', 'types', 'overloading', 'new-operator']",100,False,2,1
Null after @InjectMocks in Mockito Junit,"<p>I am having some troubles passing a dependancy while unit testing with JUnit.</p>

<p>Consider these pieces of code:</p>

<p>This is the dependacy injecton into the class which i want to test, lets call it Service.</p>

<h2>error log trace</h2>

<pre><code>  java.lang.NullPointerException
    at com.example.demo.service.ServiceClass.getCustomerById(ServiceClass.java:50)
    at com.example.demo.service.ServiceClassTest.getCustomerByIdTest(ServiceClassTest.java:46)
    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.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
</code></pre>

<h2>ServiceClass</h2>

<pre><code>@Service
public class ServiceClass {

    public static final String CRM_JPA_URI = ""http://localhost:9000/api/tickets/"";

    @Autowired
    RestTemplate restTemplate;


public Customer getCustomerById(int customerId) {
    ResponseEntity&lt;Customer&gt; entity = restTemplate.getForEntity(CRM_JPA_URI +""ticket/{customerId}"",
            Customer.class, customerId);
    return entity.getBody();
}
</code></pre>

<p>}</p>

<h2>ServiceClassTest</h2>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class ServiceClassTest {

    @Mock
   RestTemplate mockRestTemplate;

    @InjectMocks
    ServiceClass serviceClass;


    /**
     * getCustomerByIdTest
     */
    @Test
    public void getCustomerByIdTest(){

        Customer customer = new Customer();
        customer.setPassengerName(""Ramesh"");
        customer.setBookingDate(""09/09/2019"");
        customer.setDestStation(""pamur"");
        customer.setEmail(""r@gmail.com"");
        customer.setSourceStation(""ongole"");

        Mockito.lenient().when(mockRestTemplate.getForEntity(""http://localhost:9000/api/tickets/ticket/1"", Customer.class)).
        thenReturn(new ResponseEntity&lt;Customer&gt;(customer,HttpStatus.OK));

        System.out.println(""object is---&gt;""+serviceClass.getCustomerById(1));

        assertEquals(customer, serviceClass.getCustomerById(1));

    }

}
</code></pre>
",https://stackoverflow.com/questions/57760380/null-after-injectmocks-in-mockito-junit,"['spring-boot', 'junit', 'mockito']",87,False,-2,1
Creating unit tests for Xcode project results in error : Showing Recent Messages :-1: Undefined symbol: _OBJC_CLASS_$_FBSDKCodelessIndexer,"<p>When adding this to my pods file ( for unit testing purposes ) </p>

<pre><code>target 'MY_PROJECT_TITLE_Tests' do
inherit! :search_paths
pod 'Firebase'
end
</code></pre>

<p>I get the error when compiling: </p>

<pre><code>Undefined symbols for architecture x86_64:
""_OBJC_CLASS_$_FBSDKCodelessIndexer"", referenced from:
  objc-class-ref in FBSDKMarketingKit(FBSDKButtonIndexer.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see 
invocation)
</code></pre>

<p>there were no errors prior to the ""pod install"" of the above podfile change. Why is this / is there a fix? thank you. </p>
",https://stackoverflow.com/questions/56334460/creating-unit-tests-for-xcode-project-results-in-error-showing-recent-messages,"['ios', 'swift', 'iphone', 'xcode', 'cocoapods']",3611,True,0,1
How to unit test CRUD (Retrieve)?,"<p>Brand new both to .net core as well as for unit testing, so please be at my help pointing out where the problem lies in my code.</p>

<pre><code>[TestMethod]
public void RetrieveAsync_AddModel_ReturnsNotEmptyPersonList()
{
    // Arrange
    var data = new List&lt;Person&gt;();

    var mySet = new Mock&lt;DbSet&lt;Person&gt;&gt;();
    var defaultHttpContext = new DefaultHttpContext();
    var httpContextAccessorMock = new Mock&lt;IHttpContextAccessor&gt;();
    httpContextAccessorMock.Setup(m =&gt; m.HttpContext).Returns(defaultHttpContext);
    var myContextMock = new Mock&lt;MyContext&gt;(new DbContextOptions&lt;MyContext&gt;(), httpContextAccessorMock.Object);
    myContextMock.Setup(c =&gt; c.Set&lt;Person&gt;()).Returns(mySet.Object);
    var id = Guid.NewGuid();
    var service = new PersonService(myContextMock.Object);
    var model = new Person
    {
        Id = id
    };

    // Act
    var createdModel = service.CreateAsync(model).Result;
    data.Add(createdModel);
    var findModelById = data.Find(item =&gt; item.Id == createdModel.Id).Id;
    **var retrievedModel = service.RetrieveAsync(findModelById).Result; // null**

    // Assert
    **Assert.AreEqual(id, createdModel.Id); // correct, test passes
    Assert.AreEqual(id, retrievedModel.Id); // retrievedModel is null, test fails**
}
</code></pre>

<p>Generics methods I have to test are as follows:</p>

<pre><code>public async Task&lt;T&gt; CreateAsync(T model)
{
    _dbContext.Set&lt;T&gt;().Add(model);
    await _dbContext.SaveChangesAsync();
    return model;
}

public async Task&lt;T&gt; RetrieveAsync(Guid id)
{
    return await _dbContext.Set&lt;T&gt;().FindAsync(id);
}
</code></pre>

<p>The question is, why <code>retrievedModel</code> is <code>null</code>?</p>
",https://stackoverflow.com/questions/55794418/how-to-unit-test-crud-retrieve,"['c#', 'entity-framework', 'unit-testing', 'moq']",90,False,0,0
react fabric dropdown unit testing,"<p>I am new to unit testing and trying to write test cases for checking the ""text"" dropdown options. 
my code:</p>

<pre><code>const options = [
     {
        key: 'Select',
        text: 'value1',
     },
&lt;Dropdown
   placeholder=""dropdown value""
   options={options[0]}
   disabled={true}
   className=""style""
   /&gt;
</code></pre>

<p>my test file is:</p>

<pre><code>let wrapper = shallow(&lt;App /&gt;)
it('selected option text', () =&gt; {

    const dropdown= shallow(&lt;Dropdown options={options[0]} /&gt;)       
        const value= dropdown.find(Dropdown);

        expect(value.children()).toEqual('value1');

</code></pre>

<p>How can I pass the options text into children? or is there any better way to do?</p>
",https://stackoverflow.com/questions/58457685/react-fabric-dropdown-unit-testing,"['unit-testing', 'jestjs', 'enzyme']",50,False,0,0
Mock reactive return type Mono&lt;Void&gt;,"<p>I'm using Junit 5 and mockito for some unit testing.</p>

<p>method call to be mocked is as follows. It returns a Mono and takes in two String arguments.</p>

<pre><code>Mono&lt;Void&gt; doSomething(String id, String user);
</code></pre>

<p>I'm mocking it as follows</p>

<pre><code>@MockBeam MyServiceClass service;
when(service.doSomething(eq(ID), eq(USER_ID)).thenReturn(Mono.empty());
</code></pre>

<p>This results a null pointers as follows</p>

<pre><code>java.lang.NullPointerException
at com.cabonline.schooltransport.gateway.resource.TaskResourceTest.testAssignComplaintToMe(TaskResourceTest.java:117)
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:532)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:171)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:167)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:114)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:59)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:108)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
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$4(NodeTestTask.java:112)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
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$4(NodeTestTask.java:112)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
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:220)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
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/58837629/mock-reactive-return-type-monovoid,"['mockito', 'spring-webflux', 'reactive']",1937,True,0,1
How to mock a static function with Jasmine?,"<p>How can I spy on the focus() and select() functions within Jasmine (Unit testing)?</p>

<p>My function:</p>

<pre class=""lang-js prettyprint-override""><code>   static nextFieldOnAlt(e) {
        if (e.keyCode === 18) {
            const focusableFields = Array.prototype.slice.call(document.querySelectorAll('input, textarea'));
            const indexFocus = (focusableFields.indexOf(document.activeElement) + 1) % focusableFields.length;
            const input = focusableFields[indexFocus];

            input.focus();
            input.select();
        }
    }
</code></pre>

<p>The unit test:</p>

<pre class=""lang-js prettyprint-override""><code>    describe('nextFieldOnAlt function', function() {
        it('check', function() {
            const event = {
                type: 'keypress',
                keyCode: 18
            };
            const focusableFields = angular.element(['&lt;input type=""number""&gt;22&lt;/input&gt;', '&lt;textarea&gt;Test&lt;/textarea&gt;']);
            spyOn(document, 'querySelectorAll').and.returnValue(focusableFields);

            Utilities.nextFieldOnAlt(event);

            expect(event.keyCode).toEqual(13);
        });
    });
</code></pre>

<p>I get the error</p>

<blockquote>
  <p>focus is not a function</p>
</blockquote>

<p>Tried to add spy like the <code>querySelectorAll</code>, but that didn't work.</p>

<p>Any ideas, suggestions?</p>
",https://stackoverflow.com/questions/59376199/how-to-mock-a-static-function-with-jasmine,"['javascript', 'angularjs', 'unit-testing', 'testing', 'jasmine']",506,True,0,1
How to write unit test for cassandra execute query in nodejs using jest framework,"<p>I'm trying to write a unit test case against my code which fetches campaigns/data from the Cassandra DB.
I'm using the Jest framework for my unit testing. </p>

<pre><code>const db = require('../../db/client');
getCampaigns(req: express.Request, res: express.Response) {
      db.execute('select * from campaign_definitions', (err: any, 
result: any) =&gt; {
        if (err) {
          logger.error(`${err.status || 500} - ${err.message} - 
${req.originalUrl} - ${req.method} - ${req.ip}`);
          return res.status(500).send(err);
        }
        res.send(result.rows);
      });
    }
</code></pre>

<p>I don't know how to make the mock for 'db.execute' using jest. I appreciate your help, thanks</p>
",https://stackoverflow.com/questions/56468096/how-to-write-unit-test-for-cassandra-execute-query-in-nodejs-using-jest-framewor,"['node.js', 'typescript', 'jestjs', 'cassandra', 'cassandra-3.0']",952,True,3,1
How to test 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(""/applications"")
    public String deleteApplicationByObject(@RequestBody Application application) {
        applicationService.deleteById(application.getId());
        return ""Deleted"";
    }
</code></pre>

<p>// delete application
<strong>Service class</strong></p>

<pre><code>    @Override
    @Transactional
    public String removeById(Long id) {
        dao.deleteById(id);
        return ""SUCCESS"";
    }
</code></pre>

<p>// delete application
<strong>Dao class</strong></p>

<pre><code>    @Override
    public void deleteById(Long id) {
        Application application = findById(id);
        em.remove(application);
    }
</code></pre>

<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/58012029/how-to-test-delete-method-in-spring-boot-using-mockito-and-junit,"['java', 'spring-boot', 'mockito', 'junit4']",21566,True,3,1
How can I remove &quot;@oidc.login_required&quot; for unit testing from a view?,"<p>I use <a href=""/questions/tagged/flask-oidc"" class=""post-tag"" title=""show questions tagged &#39;flask-oidc&#39;"" rel=""tag"">flask-oidc</a> for user login and <a href=""/questions/tagged/pytest"" class=""post-tag"" title=""show questions tagged &#39;pytest&#39;"" rel=""tag"">pytest</a> for testing. For unit testing, I would like to ""remove"" <code>@oidc.require_login</code>. How can I do that?</p>

<h2>What I tried</h2>

<p>The way flask-o works is roughly:</p>

<pre><code>from flask import Flask, url_for, redirect
from flask_oidc import OpenIDConnect

app = Flask(__name__)
app.config['OIDC_CLIENT_SECRETS'] = 'client_secrets.json'
# Contents:
# Create client_id and client_secret at https://console.developers.google.com/apis/credentials
# {
#     ""web"": {
#         ""client_id"": ""123456789012-abc123hi09123.apps.googleusercontent.com"",
#         ""client_secret"": ""ab123456789ABCDEFGHIJKLM"",
#         ""redirect_uris"": [""http://localhost:5000""],
#         ""auth_uri"": ""https://accounts.google.com/o/oauth2/auth"",
#         ""token_uri"": ""https://accounts.google.com/o/oauth2/token"",
#         ""userinfo_uri"": ""https://www.googleapis.com/oauth2/v3/userinfo""
#     }
# }
app.config['SECRET_KEY'] = 'uq4aKjUvWXTPTIyfCz7mTtcG'
app.config['OIDC_ID_TOKEN_COOKIE_SECURE'] = False
app.config['OIDC_SCOPES'] = [""openid"", ""profile"", ""email""]
app.config['OIDC_CALLBACK_ROUTE'] = '/authorization-code/callback'
oidc = OpenIDConnect(app)


@app.route('/')
@oidc.require_login
def index():
    return redirect(url_for('personalized'))


@app.route('/personalized')
@oidc.require_login
def personalized():
    info = oidc.user_getinfo(['email', 'openid_id'])
    return 'Hello, {} ({})'.format(info.get('email'), info.get('openid_id'))


@app.route('/hello')
@oidc.require_login
def constant():
    return 'Hello'


if __name__ == '__main__':
    app.run(port=5000)
</code></pre>

<p>Then I hoped the unit test could mock the <code>@oidc.require_login</code> away:</p>

<pre><code># core modules
from unittest import mock

# 3rd party modules
import pytest

# internal modules
import exampleapp


@pytest.fixture
def client():
    app = exampleapp.app
    client = app.test_client()
    yield client


@mock.patch(""flask_oidc.OpenIDConnect"")
def test_private(mock_require_login, client):
    rv = client.get('/hello')
    assert rv.data == b'Hello'
</code></pre>
",https://stackoverflow.com/questions/57251349/how-can-i-remove-oidc-login-required-for-unit-testing-from-a-view,"['unit-testing', 'mocking', 'pytest', 'flask-oidc']",1134,True,3,1
Should @Autowired and @SpringBootTest be used in unit tests?,"<p>In a project where I work, we have been initializing Services for Unit testing in the following way: </p>

<ol>
<li>Mock dependencies that are needed for the Service.</li>
<li>Create the Service using a constructor.</li>
</ol>

<p>Something like this :</p>

<pre><code>@RunWith(SpringRunner.class)
public class ServiceTest extends AbstractUnitTest {

  @Mock private Repository repository;
  private Service service;

  @Before
  public void init() {
    service = new Service(repository);
    when(repository.findById(any(Long.class))).thenReturn(Optional.of(new Entity()));
  }
}
</code></pre>

<p>But our new developer proposed to use <code>@Autowired</code> and <a href=""https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/context/SpringBootTest.html"" rel=""nofollow noreferrer""><code>@SpringBootTest</code></a></p>

<pre><code>@SpringBootTest(classes = ServiceTest.class)
@MockBean(classes = Repository.class)
@RunWith(SpringRunner.class)
public class ServiceTest extends AbstractUnitTest {

  @MockBean private Repository repository;
  @Autowired private Service service;

  @Before
  public void init() {
    when(repository.findById(any(Long.class))).thenReturn(Optional.of(new Entity()));
  }
}
</code></pre>

<p>Before that, I supposed that <code>@Autowired</code> and <code>@SpringBootTest</code> should be used only in integration tests. But googled a lot and I see that some people use those two in Unit tests.
I read <a href=""https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html"" rel=""nofollow noreferrer"">boot-features-testing</a>. Also, I read this <a href=""https://stackoverflow.com/questions/281758/unit-tests-vs-integration-tests-with-spring"">Unit tests vs integration tests with Spring</a>.
For me, it still doesn`t feel well that we need to involve Spring to do dependency injection for unit tests, as we can do this by ourselves to do the unit testing. 
So, should <code>@Autowired</code> and <code>@SpringBootTest</code>  be used in unit tests?</p>
",https://stackoverflow.com/questions/58192035/should-autowired-and-springboottest-be-used-in-unit-tests,"['java', 'spring', 'spring-boot', 'unit-testing']",1865,True,4,2
How to calculate to second day of the next month?,"<p>For unit testing I need the duration, how long it is until the next second day of the month.
Example:
Today => 20. Jan 2018
Next second day of month => 2. Feb 2018</p>

<p>What I need: Time in milliseconds until 2. Feb 2018</p>
",https://stackoverflow.com/questions/57755925/how-to-calculate-to-second-day-of-the-next-month,"['javascript', 'unit-testing', 'mocha.js', 'sinon', 'chai']",320,True,1,2
DataService encountered a declaration exception FAILED-Angular Unit testing,"<p>I'm working on unit testing for a service layer. But I'm getting an error like 
DataService encountered a declaration exception FAILED
data.service.ts</p>

<pre><code> data: Data[];
  private url = ""http://localhost:8080/getdata"";

  constructor(
    private http: HttpClient,
     private processHTTPMsgService: ProcessHTTPMsgService
  ) {}

  getData(): Observable&lt;Data[]&gt; {
    return this.http
      .get&lt;Data[]&gt;(this.url)
      .pipe(map(data =&gt; (this.data = data)))
      .pipe(catchError(this.processHTTPMsgService.handleError));
  }
</code></pre>

<p>data.service.spec.ts</p>

<pre><code>describe(""DataService"", () =&gt; {
  let service: DataService;
  let httpMock: HttpTestingController;
  beforeEach(
    () =&gt;
      TestBed.configureTestingModule({
        imports: [HttpClientTestingModule, HttpClientModule],
        providers: [DataService,ProcessHTTPMsgService]
      }),
    (service = TestBed.get(DataService))(
      (httpMock = TestBed.get(HttpTestingController))
    )
  );
  afterEach(() =&gt; {
    httpMock.verify();
  });

  describe(""should retrieve data from the API"", () =&gt; {
    const dummyPosts: Data[] = [
      {
        effectivefrom: ""string"",
        effectiveto: ""string"",
        externalname: ""string"",
        id: 1,
        type: ""string"",
        name: ""string"",
        processstep: 1,
        status: ""string""
      }
    ];
    service.getData().subscribe(data =&gt; {
      expect(data.length).toBe(1);
      expect(data).toEqual(dummyPosts);
    });
    const request = httpMock.expectOne('http://localhost:8080/getdata');
    expect(request.request.method).toBe(""GET"");
    request.flush(dummyPosts);
  });

  describe(""should be created"", () =&gt; {
    const service: DataService = TestBed.get(DataService);
    expect(service).toBeTruthy();
  });
});
</code></pre>

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

<p>DataService encountered a declaration exception</p>

<p>Error: Cannot call Promise.then from within a sync test.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/55128813/dataservice-encountered-a-declaration-exception-failed-angular-unit-testing,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'angular7']",202,False,2,0
Should I put guard clauses in ASP.NET Core controllers?,"<p>From the perspective of unit testing, general development and code readability should I be putting guard clauses to check for null parameters injected to controllers?</p>

<p>Or should I rely on ASP.NET Core framework that it will not pass null or invalid parameters if everything is properly configured (eg. DI Container, model binding and other configurations)?</p>

<p>Here is the sample controller without guard clauses:</p>

<pre class=""lang-cs prettyprint-override""><code>[ApiController]
public class HomeController : ControllerBase
{
    private readonly IRepository _repository;
    private readonly IMapper _mapper;
    private readonly string _message;

    public HomeController(IRepository repository, IMapper mapper, string message)
    {
        _liveEventsRepository = repository;
        _mapper = mapper;
        _message = message;
    }

    [HttpGet]
    public IActionResult GetSomeData([FromQuery]QueryParameters parameters)
    {
        var result = _repository.GetData(parameters);
        var items = _mapper.Map&lt;IEnumerable&lt;MyItemDto&gt;&gt;(result.MyItems);
        return Ok(new
        {
            items,
            result.TotalItemsCount
        });
    }
}
</code></pre>

<p>If I add guard clauses like following:</p>

<pre class=""lang-cs prettyprint-override""><code>[ApiController]
public class HomeController : ControllerBase
{
    private readonly IRepository _repository;
    private readonly IMapper _mapper;
    private readonly string _message;

    public HomeController(IRepository repository, IMapper mapper, string message)
    {
        if (repository == null)
            throw new ArgumentNullException(""repository"");
        if (mapper == null)
            throw new ArgumentNullException(""mapper"");
        if (String.IsNullOrWhiteSpace(message))
            throw new ArgumentException(""text"");

        _liveEventsRepository = repository;
        _mapper = mapper;
        _message = message;
    }

    [HttpGet]
    public IActionResult GetSomeData([FromQuery]QueryParameters parameters)
    {
        if (parameters == null)
            throw ArgumentNullException(""parameters"");

        var result = _repository.GetData(parameters);
        var items = _mapper.Map&lt;IEnumerable&lt;MyItemDto&gt;&gt;(result.MyItems);
        return Ok(new
        {
            items,
            result.TotalItemsCount
        });
    }
}
</code></pre>

<p>does this add any value to my code base? Or should I completely skip guard clauses in ASP.NET Core controllers considering the underlying framework infrastructure and assuming everything is properly set?</p>

<p>Also from the perspective of unit testing, should I be testing controller constructor and actions by passing null/invalid parameters or is that unneeded overhead?</p>
",https://stackoverflow.com/questions/55419726/should-i-put-guard-clauses-in-asp-net-core-controllers,"['c#', 'unit-testing', 'asp.net-core']",2274,True,0,1
C# async Task - Unit testing,"<p>I am new to C# unit testing and have to test if the method is working properly.</p>

<p>Here is what I have so far:</p>

<pre><code>  public async Task&lt;IHttpActionResult&gt; Post(API_FIRM_LINK aPI_FIRM_LINK)
    {
        db.API_FIRM_LINK.Add(aPI_FIRM_LINK);
        await db.SaveChangesAsync();

        return Created(aPI_FIRM_LINK);
    }
</code></pre>

<p>test method: Not really sure if I am on the right path
If someone could provide an example based on my test </p>

<pre><code>     public async Task PostTest()

    {
        ////Arrange
        API_FIRM_LINKController controller = new API_FIRM_LINKController();

        API_FIRM_LINK aPI_FIRM_LINK = null;

        IHttpActionResult expectedResult = await controller.Post(aPI_FIRM_LINK);
        //act

        IHttpActionResult result = await controller.Post(API_FIRM_LINK, aPI_FIRM_LINK);


        ////Assert
        IComparer&lt;IHttpActionResult&gt; comparer = new IHttpActionResultComparer();
       // Assert.IsTrue(comparer.Equals(expectedResult, result));

        Assert.IsNotNull(result);
        Console.Write(result);
</code></pre>
",https://stackoverflow.com/questions/55107238/c-async-task-unit-testing,"['c#', 'unit-testing', 'async-await']",13981,True,4,2
Test rendering component with child props,"<p>I have component within I containment other components. In browser It looks like good but during unit testing I'm getting below an error. I don't know why. I have try render with <code>.map()</code> method but it didn't work. Thanks for help!</p>

<pre><code>Error: Uncaught [Invariant Violation: Objects are not valid as a React child (found
: object with keys {$$typeof, render, attrs, componentStyle, displayName, foldedComponentIds, styledComponentId, target, withComponent, warnTooManyClasses, toString}). If you meant to render a collection of children, use an array instead.
</code></pre>

<p>AppBarTop.js</p>

<pre><code>const AppBarTopWrapper = styled.div`
  background: ${props =&gt; props.theme.color.backgroundSecondary};
  border-bottom: 1px solid ${props =&gt; props.theme.color.line};
  padding: 2rem 2rem 0rem 2rem;
  color: ${props =&gt; props.theme.color.secondaryText};
`
const AppBarTop = ({ children }) =&gt; (
  &lt;AppBarTopWrapper&gt;{children}&lt;/AppBarTopWrapper&gt;
)

AppBarTop.propTypes = {
  children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
}

export default AppBarTop
</code></pre>

<p>Test</p>

<pre><code>const Head = styled.div
function renderTitle(props) {
  return renderWithRouter(
    &lt;AppBarTop&gt;
      &lt;Head&gt;
        &lt;UpwardButton level={2} /&gt;
        &lt;Title level={1} {...props.message} /&gt;
      &lt;/Head&gt;
    &lt;/AppBarTop&gt;,
    {
      withStore: true,
    },
  )
}

const testFormattedMessage = text =&gt; ({
  id: 'test',
  defaultMessage: text,
})

describe('&lt;Heading /&gt;', () =&gt; {
  it('Expect to not log errors in console', () =&gt; {
    const spy = jest.spyOn(global.console, 'error')
    console.log(renderTitle({ message: testFormattedMessage('test title') }))
    renderTitle({ message: testFormattedMessage('test title') })
    expect(spy).not.toHaveBeenCalled()
  })It looks like your post is mostly code; please add some more details.

})
</code></pre>
",https://stackoverflow.com/questions/58854090/test-rendering-component-with-child-props,"['javascript', 'reactjs', 'jestjs']",197,True,0,1
How to record parameter values of a method,"<p>I am currently developing a really big app. We are now facing the problem of Unit Testing everything in it.</p>

<p>I am trying to record all the interactions in methods and classes during execution time to have inputs and outputs to compare.</p>

<p>Yeah, i know it is not the properly way of doing Unit Testing but we need to do it quickly. We are already working with Mockito/PowerMockito/JUnit.</p>

<p>Already tried AOP and AspectJ but the problem is having to create new files for each class we have. </p>

<p>I was thinking in a way of intercepting the execution flow layer or somewhat to just write then dynamically in a Json file the input + dependencies values and output of method and classes invoked.</p>

<p>Any clues?</p>
",https://stackoverflow.com/questions/58007121/how-to-record-parameter-values-of-a-method,"['java', 'android', 'unit-testing']",53,False,-2,1
React (Unit &amp; Integration): Which framework to use for react unit testing and Integration testing,"<p>I have just started with development in Reactjs. I am looking for testing framework(Javascript). Which can be used to do both ""Unit Testing"", ""Integration Testing"" and ""e2e testing"". </p>

<p>Please, help me if we can do the the required testing using Javascript.</p>
",https://stackoverflow.com/questions/57039857/react-unit-integration-which-framework-to-use-for-react-unit-testing-and-in,"['javascript', 'reactjs', 'unit-testing', 'integration-testing']",204,True,0,3
Accessing properties of an object within a class,"<p>I have a class Car, which has a property Owner. Owner has two properties: FirstName and LastName</p>

<p>In my unit testing shown below, I can't get access to the two name fields,</p>

<p>""The name ""owner"" does not exist in the current context""</p>

<pre class=""lang-cs prettyprint-override""><code>namespace CodeExcercise
{
    [TestClass]
    public class TestClass
    {
        [TestMethod]
        public void Test()
        {
            var cars = new List&lt;Car&gt;()
            {
                new Car() { owner.Firstname = ""Brian"", Lastname = ""Badonde"", Cost = 5, Registered = DateTime.Now},

            };

            new PrintMethod().PrintReport(cars, ""CR.csv"");
            var outPut = File.ReadAllLines(""CR.csv"");
            Assert.AreEqual(1, outPut.Count());
        }
    }

    public class Owner
    {
        public string Firstname;
        public string Lastname;
    }

    public class Car
    {
        public Owner owner;
        public double Cost;
        public DateTime Registered;     
    }
</code></pre>
",https://stackoverflow.com/questions/58739959/accessing-properties-of-an-object-within-a-class,['c#'],42,True,0,3
Unit Test error for Angular using Karma / Jasmine for Router,"<p>I am getting the following error when unit testing my Angular application, which is: Error: Unexpected value 'Router' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.” Any idea's what it could be? Code so far is: </p>

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

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { HeaderComponent } from './header.component';
import { RouterModule, Router } from '@angular/router';
import { AppRoutingModule } from 'src/app/app-routing.module';

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ HeaderComponent],
      imports: [ 
        FontAwesomeModule, 
        RouterModule,
        Router
      ],
      providers: [ AppRoutingModule],
    })
    .compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

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

<pre><code>import { Component, OnInit, Input } from '@angular/core';
import { faHeadphones} from '@fortawesome/free-solid-svg-icons';
import { PlaylistService } from '../../../services/playlist.service';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {

  faHeadphones = faHeadphones;

  constructor(private list: PlaylistService) { }

  ngOnInit() {
  }
}
</code></pre>

<p><strong>app.module.ts</strong></p>

<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header/header.component';
import { FooterComponent } from './components/footer/footer/footer.component';
import { ContentComponent } from './components/content-area/content/content.component';
import { HomeViewComponent } from './views/home-view/home-view.component';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule, HttpClientXsrfModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { NgxPaginationModule } from 'ngx-pagination';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { Ng2SearchPipeModule } from 'ng2-search-filter';
import { PlaylistViewComponent } from './views/playlist-view/playlist-view/playlist-view.component';
import { NewsComponent } from './components/news/news/news.component';
import { CarouselModule } from 'ngx-owl-carousel-o';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    ContentComponent,
    HomeViewComponent,
    PlaylistViewComponent,
    NewsComponent,
    ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    HttpClientXsrfModule,
    FormsModule,
    NgxPaginationModule,
    FontAwesomeModule,
    Ng2SearchPipeModule,
    CarouselModule,
    BrowserAnimationsModule,
    RouterModule,
    ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>

<p>Any idea's?</p>
",https://stackoverflow.com/questions/59240709/unit-test-error-for-angular-using-karma-jasmine-for-router,"['javascript', 'angular', 'typescript', 'unit-testing']",153,True,-1,1
"CSRF Cookie Not Set error, Django Rest Framework Request Factory","<p>I am unit testing a post method of a VIEW and getting a 403 response with the below error.</p>

<pre><code>`def single_plate_pri(self):
    u = User.objects.get(username = 'c269880')
    self.client.force_authenticate(u)
    data = copy.deepcopy(self.valid_pri_data)
    factory = RequestFactory()
    post_url = '/sequence-request/confirm/'
    request = factory.post(post_url, data, user= u, 
    simulation_mode = True, enforce_csrf_checks=True)
    request.user = User.objects.get(username='c269880')
    view = csrf_exempt(SequencingRequestSpreadsheetView().as_view())
    resp = view(request)
    self.assertEqual(resp.status_code, 200)`
</code></pre>

<p>Error :</p>

<blockquote>
  <p>{'detail': ErrorDetail(string='CSRF Failed: CSRF cookie not set.',
  code='permission_denied')}</p>
</blockquote>

<p>I even tried csrf on the view but it did not work.</p>
",https://stackoverflow.com/questions/56247947/csrf-cookie-not-set-error-django-rest-framework-request-factory,"['django', 'python-3.x', 'django-rest-framework']",363,False,0,1
How to set up Googletest in VSCodium in Ubuntu,"<p>I am trying to set up googletest for unit testing on my c++ project in vscodium. Though every tutorial I've seen hasn't shown how to actually set it up. So I am hoping one of you know how to set it up.</p>
",https://stackoverflow.com/questions/56977621/how-to-set-up-googletest-in-vscodium-in-ubuntu,"['c++', 'unit-testing', 'visual-studio-code', 'googletest']",122,False,0,0
Jest mocking document.referrer,"<p>I have the following method in a react app service which requires Unit Testing.</p>

<pre><code>onDeclineCallback = () =&gt; {
    console.log(""boom "" + document.referrer);

    if (document.referrer === """") {
      console.log(""redirect to our age policy page"");
    } else {
      history.back();
    }
  };
</code></pre>

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

<pre class=""lang-js prettyprint-override""><code>history.back = jest.fn(); // Mocking history.back as jest fn

describe('age verifiction service test', () =&gt; {
  it('returns user to referrer if declined and referrer is available', () =&gt; {
    document = {
      ...document,
      referrer: 'Refferer Test', // My hacky attempt at mocking the entire document object
    };

    ageVerification.onDeclineCallback();
    expect(history.back).toHaveBeenCalledTimes(1);
  });
});
</code></pre>

<p>I am trying to find a way of mocking <code>document.referrer</code> in order to write a unit test for each case. Can anyone provide an approach for this?</p>
",https://stackoverflow.com/questions/59198002/jest-mocking-document-referrer,"['unit-testing', 'jestjs']",3591,True,3,3
How to mock date in php unit test?,"<p>I'm new to php unit testing. How do I mock the date in the function below. Currently it is getting the current date. But I want to change the date in the mock to the first day of a month.  </p>

<pre><code>function changeStartEndDate() {

    if (date('j', strtotime(""now"")) === '1') {

        $this-&gt;startDate = date(""Y-n-j"", strtotime(""first day of previous month""));

        $this-&gt;endDate = date(""Y-n-j"", strtotime(""last day of previous month"")) . ')';
    } else {

        $this-&gt;startDate = date(""Y-n-j"", strtotime(date(""Y-m-01"")));
        $this-&gt;endDate = date(""Y-n-j"", strtotime(""yesterday""));
    }
}
</code></pre>

<p>I've tried doing this but its not working. </p>

<pre><code>public function testServicesChangeStartEndDate() {
    $mock = $this-&gt;getMockBuilder('CoreFunctions')
        -&gt;setMethods(array('changeStartEndDate'))
        -&gt;getMock();

    $mock-&gt;method('changeStartEndDate')
        -&gt;with(date(""Y-n-j"", strtotime(date(""Y-m-01""))));

    $this-&gt;assertSame(
        '1',
        $this-&gt;core-&gt;changeStartEndDate()
    );

}
</code></pre>
",https://stackoverflow.com/questions/59304228/how-to-mock-date-in-php-unit-test,"['php', 'phpunit']",5974,True,5,2
Laravel unit tests not running on windows,"<p>I was trying to do unit testing with laravel framework.</p>

<p>I followed all the steps described in laravel documentation but it doesn't work when I do ""phpunit"" command.</p>

<p>Tried the same command on a linux machine, it ran perfectly....</p>

<pre><code>Desktop\space-bubble\phpunit.xml


Time: 0 seconds, Memory: 6.00Mb
</code></pre>

<p>No tests executed!</p>
",https://stackoverflow.com/questions/56345650/laravel-unit-tests-not-running-on-windows,"['php', 'laravel', 'unit-testing', 'laravel-5', 'eloquent']",69,True,0,1
Write unit test cases for Servlet,"<p>I want to write the testcase to fetch the real path of this application-jars and procedd further. Can someone please help to write the testcase.</p>

<p>I am new to unit testing so not sure how to write test cases for servlets . </p>

<pre><code>public void init(ServletConfig config) throws ServletException {
        try {
            Properties props = loadProperties();    
            info(""Loaded properties: "" + jnlpprops);

            String appsStr = checkAppsExists(props);
            supportedApps = Arrays.asList(appsStr.split("",""));

            applicationjars = config.getServletContext().getRealPath(""application-jars"");
            if (applicationjars == null) {
                throw new ServletException(""Cannot find path for application jars"");
            }

            populateJarFileNames(applicationjars);

        } catch (ServletException e) {
            throw e;
        } finally {

        }
    }
</code></pre>
",https://stackoverflow.com/questions/57111063/write-unit-test-cases-for-servlet,"['servlets', 'junit', 'init']",50,False,0,0
Unable to set &#39;valid&#39; property of Formgroup for reactive form in Angular Unit testing,"<p>I am using reactive form. This property: <code>getattributeForm: FormGroup;</code>
is set invalid. So I am not able to cover all testcase.</p>

<pre><code>if (!this.getattributeForm.valid) {return}
</code></pre>

<p>This is always true. Can we make it true, so that I can cover other scenario? <code>this.getattributeForm.valid</code> to be set true in angular unit testing.</p>
",https://stackoverflow.com/questions/55869005/unable-to-set-valid-property-of-formgroup-for-reactive-form-in-angular-unit-te,['angular'],1661,False,0,1
unit testing with ArgumentValidator.VerifyNotNullOrEmpty,"<p>I am doing unit testing. And I have the following method:</p>

<pre><code>  public PortfolioFileGetListDto(string documentsCaseNumber)
        {
            ArgumentValidator.VerifyNotNullOrEmpty(documentsCaseNumber, nameof(documentsCaseNumber));

            CaseNumber = documentsCaseNumber;
        }
</code></pre>

<p>and I try to unit test this method like so:</p>

<pre><code> [TestMethod]
        public void PortfolioFileGetListDto_Constructor_ShouldValidateParameters()
        {
            // Portfolio           
            Action act = () =&gt; new PortfolioFileGetListDto(null);
            act.Should().Throw&lt;ArgumentNullException&gt;().WithMessage(""Value cannot be null.\n\rParameter name: portfolio"");
        }
</code></pre>

<p>But if I debug the unit test, I get the following exception:</p>

<pre><code>System.ArgumentNullException: 'Value cannot be null.
Parameter name: documentsCaseNumber'
</code></pre>

<p>So how to pass this unit test?</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/54779513/unit-testing-with-argumentvalidator-verifynotnullorempty,"['c#', 'unit-testing']",118,True,0,2
Unit Testing xunit The following constructor parameters did not have matching fixture data,"<p>The following constructor parameters did not have matching fixture data for unit testing using moq and xunit. </p>

<p>Already using dependency injection and mock to test the class. </p>

<pre><code>//this is how i register the DI.
services.AddScoped&lt;IWaktuSolatServiceApi, WaktuSolatServiceApi&gt;(); 


 public interface IWaktuSolatServiceApi
 {
    Task&lt;Solat&gt; GetAsyncSet();
 }


// the unit test. 
public class UnitTest1 
{
    Mock&lt;IWaktuSolatServiceApi&gt; waktu;

    public UnitTest1(IWaktuSolatServiceApi waktu)
    {
        this.waktu = new Mock&lt;IWaktuSolatServiceApi&gt;();
    }

    [Fact]
    public async Task ShoudReturn()
    {
        var request = new Solat
        {
            zone = ""lala""
        };

        var response = waktu.Setup(x =&gt; 
        x.GetAsyncSet()).Returns(Task.FromResult(request));
    }
}
</code></pre>

<p>But i got this error The following constructor parameters did not have matching fixture data.</p>
",https://stackoverflow.com/questions/56754176/unit-testing-xunit-the-following-constructor-parameters-did-not-have-matching-fi,"['c#', 'testing', 'moq', 'xunit']",7721,True,-1,1
Mock an object in a method,"<p>I am having trouble unit testing below method. I cant mock <code>MyClass</code> but I need to fill up the props in it to be able to unit test the rest of the method. Is it possible to create <code>MyClass</code> instance and evaluate in a unit test?</p>

<pre><code>public async Task&lt;MyResponse&gt; Handle(MyRequest request, CancellationToken cancellationToken)
{
    MyClass obj = new MyClass();

    _dependecy.Execute(obj);

    foreach(var o in obj.Props)
    {
        //do some processing
    }

}
</code></pre>
",https://stackoverflow.com/questions/56866991/mock-an-object-in-a-method,"['c#', 'unit-testing', 'mocking']",52,True,1,1
Uncaught TypeError: Cannot read property &#39;_id&#39; of undefined,"<p>I am getting TypeError: Cannot read property '_id' of undefined while trying to get users according to a User ID. </p>

<p>My routes and controllers looks like this :</p>

<p>//routes.js </p>

<pre><code>var AuthenticationController = require('./controllers/authentication');

module.exports = function (app){
    var apiRoutes = express.Router();
    apiRoutes.get('/user/:_id', AuthenticationController.getUserById);
    app.use('/api', apiRoutes);
};
</code></pre>

<p>// controllers</p>

<pre><code> exports.getUserById = function (req, res, next){
        User.findById(
            {_id: req.params._id}, function(err,users){
                if (err){
                    res.send(err);
                }
                res.status(200).json({
                    Success: true,
                    user: users
                });
            });
};
</code></pre>

<p>Below is my unit testing code for get user by ID.</p>

<p>//user-test.spec.js</p>

<pre><code>describe('/GET/:_id user', () =&gt; {
    it('it should get a user by the given ID', (done) =&gt; {
        var user = new User({ email: ""mjn.nilesh12@gmail.com"", password: ""gunners"", fullname: ""Nilesh Maharjan""});
        user.save((err, user) =&gt; {
            chai.request(server)
            .get('api/user/' + user._id)
            .send(user)
            .end((err, res) =&gt; {
                res.should.have.status(200);
            done();
            });
        });
    });
});
</code></pre>

<p>// Full error</p>

<pre><code>Uncaught TypeError: Cannot read property '_id' of undefined
      at user.save (test/user-test.spec.js:73:38)
      at /Users/seva/Desktop/project1/node_modules/mongoose/lib/model.js:4670:16
      at /Users/seva/Desktop/project1/node_modules/mongoose/lib/utils.js:250:11
      at $__save.error (node_modules/mongoose/lib/model.js:476:16)
      at /Users/seva/Desktop/project1/node_modules/kareem/index.js:246:48
      at next (node_modules/kareem/index.js:167:27)
      at next (node_modules/kareem/index.js:169:9)
      at Kareem.execPost (node_modules/kareem/index.js:217:3)
      at _handleWrapError (node_modules/kareem/index.js:245:21)
      at _cb (node_modules/kareem/index.js:304:16)
      at /Users/seva/Desktop/project1/node_modules/mongoose/lib/model.js:329:9
      at /Users/seva/Desktop/project1/node_modules/kareem/index.js:135:16
      at _combinedTickCallback (internal/process/next_tick.js:132:7)
      at process._tickCallback (internal/process/next_tick.js:181:9)
</code></pre>
",https://stackoverflow.com/questions/54826899/uncaught-typeerror-cannot-read-property-id-of-undefined,"['javascript', 'node.js', 'unit-testing', 'express', 'mocha.js']",320,False,1,0
How can I generate test coverage of untested files on my flutter tests?,"<p>I'm making Widget and Unit testing on my app, I make the tests normally, according to the <a href=""https://flutter.io/docs/testing"" rel=""noreferrer"">basic guides</a>, and to generate the coverage I use:</p>

<p><code>flutter test --coverage</code></p>

<p>However I just can see the coverage of the files <strong>directly tested</strong>, I'd like to see the other files (with 0% of coverage), then I could check the real coverage of my code.</p>

<p>Is there a way for doing that?</p>
",https://stackoverflow.com/questions/54602840/how-can-i-generate-test-coverage-of-untested-files-on-my-flutter-tests,"['flutter', 'flutter-test']",3438,True,17,1
How to setup jest with angular in stackblitz,"<p>Is it possible to setup <a href=""https://stackblitz.com"" rel=""nofollow noreferrer"">stackblitz</a> project to run angular unit-testing with jest?</p>

<p><strong>Update:</strong></p>

<p>Got it working with codesandbox(it's already running on jest) but have yet not been able to make it run with stackblitz, taken in consideration they work differently.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/56943261/how-to-setup-jest-with-angular-in-stackblitz,"['angular', 'unit-testing', 'jestjs', 'stackblitz']",1536,True,2,1
After migrating from App Engine Java 8 to Java 11 what local development and unit testing tools work well?,"<p>I am reviewing the <a href=""https://cloud.google.com/appengine/docs/standard/java11/java-differences#datastore"" rel=""noreferrer"">migration path from Java 8 to Java 11 on Google App Engine</a>, in the past the GAE environment offered <a href=""https://cloud.google.com/appengine/docs/standard/java/tools/localunittesting"" rel=""noreferrer"">excellent unit testing support</a> and a <a href=""https://cloud.google.com/appengine/docs/standard/java/tools/using-local-server"" rel=""noreferrer"">local development environment</a>.</p>

<p>But in the new Java 11 runtime, these seem to be missing, are they just not ready yet, or are they not coming to this new runtime?</p>

<p>The <a href=""https://cloud.google.com/appengine/docs/standard/java11/testing-and-deploying-your-app"" rel=""noreferrer"">testing page</a> says:</p>

<blockquote>
  <p>To test your application's functionality before deploying, run your application in your local environment with the development tools that you usually use.</p>
</blockquote>

<p>That seems to punt the question back to the user - but when deploying to GAE having local runtime emulation for development and unit testing is really important. If it's not ever coming to Java 11, what's the best/right way to actually develop and test a Java 11 runtime GAE app?</p>
",https://stackoverflow.com/questions/59523141/after-migrating-from-app-engine-java-8-to-java-11-what-local-development-and-uni,"['java', 'google-app-engine']",798,True,5,2
Cannot read property &#39;apply&#39; of undefined when unit testing in chai,"<p>Trying to test a simple express rest, and im getting </p>

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

<p>Not sure what i am doing wrong. </p>

<p>I referenced similar threads but it wasn't specific to unit testing </p>

<p><a href=""https://stackoverflow.com/questions/52767617/cannot-read-property-apply-of-undefined"">Cannot read property &#39;apply &#39; of undefined</a></p>

<p>referencing this</p>

<p><a href=""https://codehandbook.org/unit-test-express-route/"" rel=""nofollow noreferrer"">https://codehandbook.org/unit-test-express-route/</a></p>

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

<pre><code>import chai from 'chai';
import chaiHttp from 'chai-http';
import router from '../routes/';

chai.use(chaiHttp);
chai.should();

const expect = chai.expect();

describe('index page should render, hello world', () =&gt; {
    it('should render hello world 200', (done) =&gt; {     
        chai.request(router).get('/').end( (err, res) =&gt; {   
            expect(200, ""ok"").
            expect(res.text).to.equal('Hello World');

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

<p><strong>index.js</strong></p>

<pre><code>import express from 'express';

const router = express.Router();

router.get('/', (req, res) =&gt; {
    return res.status(200).json({
        message: ""Hello World""
    })
})




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

<p><strong>.babelrc</strong></p>

<pre><code>{
    ""presets"": [""@babel/preset-env""]  
}
</code></pre>

<p><strong>package.json</strong></p>

<pre><code>{
  ""name"": ""elinodereactapp"",
  ""version"": ""1.0.0"",
  ""description"": """",
  ""scripts"": {
    ""start"": ""nodemon --exec babel-node ./app.js"",
    ""test"": ""mocha --require @babel/register tests/*.js --exit"",
    ""build"": ""babel src --out-dir ./dist --source-maps"",
    ""serve"": ""node ./app.js""
  },
  ""author"": """",
  ""license"": ""ISC"",
  ""dependencies"": {
    ""assert"": ""^1.4.1"",
    ""body-parser"": ""^1.18.3"",
    ""chai-http"": ""^4.2.1"",
    ""cookie-parser"": ""^1.4.4"",
    ""cors"": ""^2.8.5"",
    ""dotenv"": ""^7.0.0"",
    ""express"": ""^4.16.4"",
    ""morgan"": ""^1.9.1"",
    ""node-mocks-http"": ""^1.7.3""
  },
  ""devDependencies"": {
    ""@babel/cli"": ""^7.4.3"",
    ""@babel/core"": ""^7.4.3"",
    ""@babel/node"": ""^7.2.2"",
    ""@babel/preset-env"": ""^7.4.3"",
    ""@babel/register"": ""^7.4.0"",
    ""babel-cli"": ""^6.26.0"",
    ""babel-core"": ""^7.0.0-bridge.0"",
    ""babel-loader"": ""^8.0.5"",
    ""babel-preset-env"": ""^1.7.0"",
    ""chai"": ""^4.2.0"",
    ""mocha"": ""^6.1.1"",
    ""nodemon"": ""^1.18.10""
  }
}
</code></pre>
",https://stackoverflow.com/questions/55580740/cannot-read-property-apply-of-undefined-when-unit-testing-in-chai,"['javascript', 'express', 'mocha.js', 'chai']",4600,True,2,1
Why can&#39;t I test that a class&#39;s instance is defined,"<p>I have a helper class which creates instance of another class</p>

<pre><code>class TestEnv {
val questionsController = new QuestionsController(...)
}
</code></pre>

<p>I am unit testing <code>QuestionsController</code> and have created a basic test case</p>

<pre><code>class QuestionsControllerUnitSpec extends PlaySpec with BeforeAndAfterAll with BeforeAndAfterEach with OneAppPerSuiteWithComponents{

  override def beforeEach() = {
    println(""------------new test -----------------"")
  }


  override def components: BuiltInComponents = new BuiltInComponentsFromContext(context) with NoHttpFiltersComponents {

    import play.api.mvc.Results
    import play.api.routing.Router
    import play.api.routing.sird._


    lazy val router: Router = Router.from({
      case GET(p""/"") =&gt; defaultActionBuilder {
        Results.Ok(""success!"")
      }
    })




  }

  ""Question Controller "" should {
    ""be created"" in {
      val testEnv = new TestEnv(components = components)
      val qc:QuestionsController = testEnv.questionsController
      qc mustBe defined //I get compilation error 

    }
  }


}
</code></pre>

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

<pre><code>Error:(52, 10) could not find implicit value for parameter definition: org.scalatest.enablers.Definition[controllers.QuestionsController]
      qc mustBe defined
Error:(52, 10) not enough arguments for method mustBe: (implicit definition: org.scalatest.enablers.Definition[controllers.QuestionsController])org.scalatest.Assertion.
Unspecified value parameter definition.
      qc mustBe defined
</code></pre>

<p>I checked the definition of <code>mustBe</code> in <code>MustMatchers.class</code>. It is defined as <code>def mustBe(right : org.scalatest.words.DefinedWord)(implicit definition : org.scalatest.enablers.Definition[T]) : org.scalatest.Assertion = { /* compiled code */ }</code></p>

<p>Why am I getting the error.</p>
",https://stackoverflow.com/questions/55721519/why-cant-i-test-that-a-classs-instance-is-defined,"['scalatest', 'playframework-2.6']",42,True,0,2
differences in unit testing frameworks and how to use,"<p>I am trying to compare the following test frameworks</p>

<p>•   Microsoft Unit Testing Framework for C++
•   Google Test
•   Boost.Test
•   CTest</p>

<p>And I am lost.  Which is best?  And how to write test-driven development.  We are a Microsoft shop with 80% C++ code and 20% c#</p>
",https://stackoverflow.com/questions/58207511/differences-in-unit-testing-frameworks-and-how-to-use,"['windows', 'unit-testing']",46,True,-1,1
Jest unit test module.export fails?,"<p>I have setup Jest for unit testing and it works great, but the functions do not work in the browser? I know it is because the way the functions are exported.</p>

<pre><code>import $ from 'jquery';

function factBox() {
  console.log(""GHEje fwe"");
  $(""body"").css(""background-color"", ""red"");
}

function sum(a, b) {
  console.log(""SUMMM"");
  return a + b;
}

module.exports = factBox;
module.exports = sum;
</code></pre>

<p>On the other hand this works in the browser, but the test now fails?:</p>

<pre class=""lang-js prettyprint-override""><code>import $ from 'jquery';

function factBox() {
  console.log(""GHEje fwe"");
  $(""body"").css(""background-color"", ""red"");
}

function sum(a, b) {
  console.log(""SUMMM"");
  return a + b;
}

export {
  factBox,
  sum
};
</code></pre>

<p><a href=""https://i.stack.imgur.com/7pmc9.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/7pmc9.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/58696477/jest-unit-test-module-export-fails,"['javascript', 'unit-testing', 'jestjs']",282,True,0,1
Should I refactor code for unit testing in mvp android?,"<p>I made an mvp application in kotlin and in each function of my presenter I call a view method so should I refactor my code for unit-testing or i just let this like that?</p>

<p>For exemple i have a function that make a regex</p>

<pre><code>private fun checkPassword(isRegister: Boolean, pass: String, confirmPass: String): Boolean {
    val regex = Regex(""^(?=.{8,}\$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])"")
    if (isRegister) {
        if (pass != confirmPass) {
            loginView.showNotMatchingPassword() // display an alert on a inputtext
            return false
        }
        if (!pass.contains(regex)) {
            loginView.showInvalidPassword() // display an alert on a inputtext
            return false
        }
    }
    return true
}
</code></pre>
",https://stackoverflow.com/questions/56360749/should-i-refactor-code-for-unit-testing-in-mvp-android,"['android', 'unit-testing', 'kotlin', 'android-mvp']",92,True,0,1
H2 in-memory database for postgresql | Error Code : 90051,"<p>Using h2 in-memory database for unit testing with Spring. The production database is PostgreSQL. I have following script which works fine on Postgres but failing on h2:</p>

<pre><code>CREATE TABLE address (
  address_id          SERIAL NOT NULL, 
  province_code       char(2), 
  created_timestamp   timestamp(35) with time zone DEFAULT now() NOT NULL
)
</code></pre>

<pre class=""lang-none prettyprint-override""><code>SQL State  : 90051
Error Code : 90051
Message    : Scale($""35"") must not be bigger than precision(""23"");
</code></pre>

<p>Do I need to specify something else in the URL or configuration. Here is the url:</p>

<pre><code>database.url=jdbc:h2:mem:myDb;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS TEST
</code></pre>
",https://stackoverflow.com/questions/57100310/h2-in-memory-database-for-postgresql-error-code-90051,"['spring', 'postgresql', 'junit', 'h2']",144,False,0,0
LNK2019 Error - Boost Unit Test Framework,"<p>I am trying to practice using Boost unit testing but am faced with a LNK2019 error. This error code haunts me as I rarely know what needs to be done to fix it.</p>

<p>I have the unit testing class set up as basic as I possibly could. I am just trying to make the basic functions work right now so I can go in and create real tests. This is what I have in my cpp:</p>

<pre><code>#include &lt;boost/test/unit_test.hpp&gt;
#define BOOST_TEST_MODULE unit_test

BOOST_AUTO_TEST_CASE(MyTest)
{
    BOOST_CHECK(10 == 10);
    BOOST_REQUIRE(10 == 11);
}
</code></pre>

<p>I have the boost directory included in my C++ project properties, and I have included the stage\lib directory in my Linker Additional Library Directories. I am guessing I have the boost directory included incorrectly, but I am really not sure what I did wrong or how to remedy this. The error is listed below.</p>

<pre><code>Severity    Code    Line    Suppression State   Description
Error   LNK2019 C:\Users\...\libboost_unit_test_framework-vc142-mt-gd-x32-1_71.lib(unit_test_main.obj)  1       unresolved external symbol ""class boost::unit_test::test_suite * __cdecl init_unit_test_suite(int,char * * const)"" (?init_unit_test_suite@@YAPAVtest_suite@unit_test@boost@@HQAPAD@Z) referenced in function __catch$?unit_test_main@unit_test@boost@@YAHP6APAVtest_suite@12@HQAPAD@ZH0@Z$4
</code></pre>

<p>Any thoughts?</p>
",https://stackoverflow.com/questions/58828930/lnk2019-error-boost-unit-test-framework,"['c++', 'boost', 'lnk2019']",976,False,1,0
Unit testing with flutter scoped model,"<p>Developing an app I end up with some logic in my scoped model. My search does not show any examples on unit testing. Does anyone have an experience with in writing a test for scoped model? How can I mock lifecycle of the scoped model?</p>
",https://stackoverflow.com/questions/55170613/unit-testing-with-flutter-scoped-model,"['unit-testing', 'flutter', 'scoped-model']",503,False,-1,1
ReactWrapper::state() can only be called on class components Unit Testing Jest and Enzyme,"<p>Writing unit testing in react using jest and enzyme. While checking with a component state , it throws an error ""ReactWrapper::state() can only be called on class components "". </p>

<pre><code>import React from 'react';
import { mount } from 'enzyme';
import expect from 'expect';
import CustomerAdd from '../CustomerAdd'
import MUITheme from '../../../../Utilities/MUITheme';
import { ThemeProvider } from '@material-ui/styles';

describe('&lt;CustomerAdd /&gt;', () =&gt; {
    const wrapper = mount(
        &lt;ThemeProvider theme={MUITheme}&gt;
          &lt;CustomerAdd {...mockProps}&gt;&lt;/CustomerAdd&gt;
        &lt;/ThemeProvider&gt;
        );
        test('something', () =&gt; {
            expect(wrapper.find(CustomerAdd).state('addNewOnSubmit')).toEqual(true);
        });
});
</code></pre>

<p>In the above code CustomerAdd Component is class component.I don't what wrong with my code. Can any one help me out of this problem. Thanks in advance.</p>
",https://stackoverflow.com/questions/58429807/reactwrapperstate-can-only-be-called-on-class-components-unit-testing-jest-a,"['reactjs', 'unit-testing', 'jestjs', 'material-ui', 'enzyme']",20188,True,8,1
Can anyone give me an example about unit testing in iOS Swift?,"<p>I am new in iOS development and want to learn unit testing. I want to add two numbers using text fields and show the result in a label when clicking on the action. Can anyone suggest me how to make a unit test for this?</p>
",https://stackoverflow.com/questions/55947493/can-anyone-give-me-an-example-about-unit-testing-in-ios-swift,"['ios', 'swift', 'unit-testing']",774,True,-4,2
Mock mounted hook Jest testing unit,"<p>I am doing some unit testing for components. However, in some components, I have something running on the <code>mounted</code> hook that is making my test fail.
I have managed to mock the methods that I do not need. However, I was wondering if there is a workaround mocking the <code>mounted</code> hook itself.</p>

<p><strong>@/components/attendeesList.vue</strong></p>

<pre><code>&lt;template&gt;
  &lt;div&gt;
    &lt;span&gt; This is a test &lt;/span&gt; 
  &lt;/div&gt;
&lt;/template&gt;
</code></pre>

<p><strong>JS</strong></p>

<pre><code>&lt;script&gt;
methods: {
    testMethod: function() {
        // Whatever is in here I have managed to mock it
    }
},

mounted: {
    this.testMethod();
}
&lt;/script&gt;
</code></pre>

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

<pre><code>import { mount, shallowMount } from '@vue/test-utils'
import test from '@/components/attendeesList.vue'

describe('mocks a method', () =&gt; {    
  test('is a Vue instance', () =&gt; {
  const wrapper = shallowMount(attendeesList, {
    testMethod:jest.fn(),
  })
  expect(wrapper.isVueInstance()).toBeTruthy()
})
</code></pre>
",https://stackoverflow.com/questions/55746890/mock-mounted-hook-jest-testing-unit,"['vue.js', 'vuejs2', 'jestjs', 'babel-jest', 'vue-test-utils']",11884,True,8,2
How can I activate ceedling trace?,"<p>I am using ceedling for unit testing in a firmware I am working on.
I would like to see all command line option ceedling uses when invoking the compiler.</p>

<p>I tried to use the option --trace, but so for I have not found any difference. </p>

<p>ceedling test:all --trace</p>
",https://stackoverflow.com/questions/56907683/how-can-i-activate-ceedling-trace,"['unit-testing', 'ceedling']",1186,True,3,2
How to use jest in react native for unit testing,"<p>Here I am trying to implemnet jest unit testing . There are 2 files test and mock . In below code I am excuting test file (npm run test Contactdetails-test). But getting error
     FAIL  <strong>tests</strong>/Contactdetails-test.js
  × find Contact details info (5ms)
   ● find Contact details info</p>

<pre><code>ReferenceError: MockedProvider is not defined


 Contactdetails-mock.js
        import react from 'react-native';
        import Contactdetails from '../app/components/container/ContactdetailsContainer';
        import { __generator } from 'tslib';

        const contactDetails = `[{""contactDetails"":{""isContactBySms"":""Y"",""mobileNo"":""8880995809"",""isContactByPost"":""N"",""isContactByEmail"":""Y"",""emailId"":""test@test.com""},""socialMediaDetails"":{""socialMediaDetail"":[{""name"":""twitter"",""link"":""HARIRAM@twitter.com"",""__typename"":""SocialMediaDetail""},{""name"":""facebook"",""link"":""VarnaHERO@facebook.com"",""__typename"":""SocialMediaDetail""},{""name"":""linkedIn"",""link"":""linkedIn@linkedin.com"",""__typename"":""SocialMediaDetail""},{""name"":""instagram"",""link"":""instagram@instagram.com"",""__typename"":""SocialMediaDetail""},{""name"":""telegram"",""link"":""kaushik@telegram.com"",""__typename"":""SocialMediaDetail""}]}}]`;
        const contactDetailsinfo = JSON.parse(contactDetails);
        console.log(""contact info"", contactDetailsinfo);


        export const ContactDetailsData = {
            customerInfo: { contactDetailsinfo },

        }

    // Contactdetails-test.js

    import React from 'react';
    import renderer from 'react-test-renderer';
    import ContactDetailsData from '../__mocks__/Contactdetails-mock';
        expect(findElement(tree,'Contactdetails.customerInfo','Contactdetails.navigation','')).toBeDefined();

    //   });

    it('find Contact details info', () =&gt; {

        renderer.create(
            &lt;MockedProvider mocks={mocks} addTypename={false}&gt;
                &lt;ContactDetailsData /&gt;
            &lt;/MockedProvider&gt;,
        );
    });
</code></pre>

<p>Please help</p>
",https://stackoverflow.com/questions/57671933/how-to-use-jest-in-react-native-for-unit-testing,"['javascript', 'reactjs', 'react-native', 'jestjs', 'babel-jest']",42,False,1,0
iOS Keychain - what is the difference between kSecClassGenericPassword and kSecClassInternetPassword?,"<p>I have some code that stores data in keychain. The code is working during unit testing. The value that I store is Data However, when I  specify</p>

<pre><code> kSecClass : kSecClassGenericPassword, I get OSStatus 0 - success
 kSecClass : kSecClassInternetPassword, I get OSStatus -25303
</code></pre>

<p><strong>What are the storage requirements or differences between kSecClassGenericPassword and kSecClassInternetPassword?</strong> 
(Same code fails with kSecClassInternetPassword)</p>

<p>Update: potentially the internet password query was missing one of the required fields, like <code>kSecAttrServer</code>,not <code>kSecAttrService</code></p>
",https://stackoverflow.com/questions/55456238/ios-keychain-what-is-the-difference-between-ksecclassgenericpassword-and-ksecc,"['ios', 'keychain', 'osstatus']",1763,True,9,1
Maven cannot obtain junit,"<p>I have got a project that implements unit testing with <code>junit</code>. There is a <code>pom.xml</code> fragment</p>

<pre><code>&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>However, the project does not compile. The error in <code>pom.xml</code> looks like:</p>

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

<p>How to fix the error?</p>

<hr>

<p><code>mvn install</code> returns next error message</p>

<pre><code>[INFO] C:\Users\loom\prj\src\main\java:-1: info: compiling
[INFO] C:\Users\loom\prj\target\generated-sources\annotations:-1: info: compiling
[INFO] Compiling 7 source files to C:\Users\loom\prj\target\classes at 1548091925026
[ERROR] error: scala.reflect.internal.MissingRequirementError: object java.lang.Object in compiler mirror not found.
[ERROR]         at scala.reflect.internal.MissingRequirementError$.signal(MissingRequirementError.scala:17)
[ERROR]         at scala.reflect.internal.MissingRequirementError$.notFound(MissingRequirementError.scala:18)
[INFO]  at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:53)
[INFO]  at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:45)
[INFO]  at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:45)
[INFO]  at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:66)
[INFO]  at scala.reflect.internal.Mirrors$RootsBase.getClassByName(Mirrors.scala:102)
[INFO]  at scala.reflect.internal.Mirrors$RootsBase.getRequiredClass(Mirrors.scala:105)
[INFO]  at scala.reflect.internal.Definitions$DefinitionsClass.ObjectClass$lzycompute(Definitions.scala:257)
[INFO]  at scala.reflect.internal.Definitions$DefinitionsClass.ObjectClass(Definitions.scala:257)
[INFO]  at scala.reflect.internal.Definitions$DefinitionsClass.init(Definitions.scala:1394)
[INFO]  at scala.tools.nsc.Global$Run.&lt;init&gt;(Global.scala:1215)
[INFO]  at scala.tools.nsc.Driver.doCompile(Driver.scala:31)
[INFO]  at scala.tools.nsc.MainClass.doCompile(Main.scala:23)
[INFO]  at scala.tools.nsc.Driver.process(Driver.scala:51)
[INFO]  at scala.tools.nsc.Driver.main(Driver.scala:64)
[INFO]  at scala.tools.nsc.Main.main(Main.scala)
[INFO]  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[INFO]  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[INFO]  at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[INFO]  at java.base/java.lang.reflect.Method.invoke(Method.java:564)
[INFO]  at org_scala_tools_maven_executions.MainHelper.runMain(MainHelper.java:161)
[INFO]  at org_scala_tools_maven_executions.MainWithArgsInFile.main(MainWithArgsInFile.java:26)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 9.196 s
[INFO] Finished at: 2019-01-21T20:32:06+03:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.scala-tools:maven-scala-plugin:2.15.2:compile (default) on project prj: wrap: org.apache.commons.exec.ExecuteException: Process exited with an error: 1(Exit value: 1) -&gt; [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code></pre>

<p><a href=""https://pastebin.com/rcSNfc5Q"" rel=""nofollow noreferrer"">There</a> is a full log of <code>maven install</code> </p>

<hr>

<p>Java and maven versions:</p>

<pre><code>$ mvn -version
Apache Maven 3.5.3 (3383c37e1f9e9b3bc3df5050c29c8aff9f295297; 2018-02-24T22:49:05+03:00)
Maven home: C:\ProgramData\chocolatey\lib\maven\apache-maven-3.5.3bin..
Java version: 10.0.2, vendor: Oracle Corporation
Java home: C:\Users\loom\scoop\apps\openjdk\current
Default locale: ru_RU, platform encoding: Cp1251
OS name: ""windows 7"", version: ""6.1"", arch: ""amd64"", family: ""windows""

$ java -version
java version ""1.8.0_191""
Java(TM) SE Runtime Environment (build 1.8.0_191-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)
</code></pre>

<hr>

<p>Plugin info follows:</p>

<pre><code>&lt;plugins&gt;
    &lt;plugin&gt;
        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
        &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
        &lt;version&gt;3.3&lt;/version&gt;

        &lt;configuration&gt;
            &lt;source&gt;1.8&lt;/source&gt;
            &lt;target&gt;1.8&lt;/target&gt;
            &lt;encoding&gt;UTF-8&lt;/encoding&gt;
        &lt;/configuration&gt;
    &lt;/plugin&gt;

    &lt;plugin&gt;
        &lt;groupId&gt;org.scala-tools&lt;/groupId&gt;
        &lt;artifactId&gt;maven-scala-plugin&lt;/artifactId&gt;
        &lt;version&gt;2.15.2&lt;/version&gt;
        &lt;executions&gt;
            &lt;execution&gt;
                &lt;goals&gt;
                    &lt;goal&gt;compile&lt;/goal&gt;
                    &lt;goal&gt;testCompile&lt;/goal&gt;
                &lt;/goals&gt;
            &lt;/execution&gt;
        &lt;/executions&gt;

        &lt;configuration&gt;
            &lt;sourceDir&gt;src/main/scala&lt;/sourceDir&gt;
            &lt;testSourceDir&gt;src/test/scala&lt;/testSourceDir&gt;
        &lt;/configuration&gt;
    &lt;/plugin&gt;

&lt;/plugins&gt;
</code></pre>
",https://stackoverflow.com/questions/54294923/maven-cannot-obtain-junit,"['java', 'maven', 'junit', 'dependencies']",90,True,1,2
Angular 4 - How to parse hyphened variable in template for Karma testing?,"<p>I am facing an issue while unit testing my Angular 4 component with Karma. Below is the command I am running to test:</p>

<pre><code>tsc &amp;&amp; karma start --browsers PhantomJS
</code></pre>

<p>I have hyphened variable as below, which is bound with the HTML template and I verified the bind is working and data displays on the page (in browser).</p>

<p><strong>Hyphned variable - in a component.ts file</strong></p>

<pre><code>template-variable-key
</code></pre>

<p>But during the unit testing, I am facing an issue as it gives below error:</p>

<pre><code>TypeError: Cannot read property 'layout-permission-title-key' of undefined
</code></pre>

<hr>

<h3>How I defined in HTML template</h3>

<strong>(1)</strong> In template with EXPRESSION

<pre><code>&lt;p&gt;{{error['template-variable-key']}}&lt;/p&gt;
</code></pre>

<strong>(2)</strong> OR In template with data binding using <code>innerHtml</code>

<pre><code>&lt;p [innerHtml]=""error['template-variable-key']""&gt;&lt;/p&gt; &lt;!-- or --&gt;

&lt;p [innerHtml]=""error?.template-variable-key""&gt;&lt;/p&gt;
</code></pre>

<p><strong>Note:</strong> As the same hyphened variable is being used at many places other than Angular, I cannot change it to camelCase or something else.</p>

<p><strong>(1)</strong> and <strong>(2)</strong> both didn't work for me.</p>

<p>Thanks in advance for your answer :)</p>
",https://stackoverflow.com/questions/57156953/angular-4-how-to-parse-hyphened-variable-in-template-for-karma-testing,"['javascript', 'angular', 'karma-jasmine', 'angular-template', 'angular-test']",225,True,0,1
How to mock all layer of application in test method?,"<p>I am trying to perform Unit Testing my ASP.NET Core WebAPI with XUnit Project. I am using 3-Layer Architecture where every layer is in different class library project and dependencies ware resolved with dependency injection. Everything is working fine. But when I want to perform unit test I got stuck with mocking of logic layer &amp; data layer. When I run the test I got this error:</p>

<blockquote>
  <p>Message: System.ArgumentException : Constructor arguments cannot be passed for interface mocks.</p>
</blockquote>

<p>My Mock Object generates in this class:</p>

<pre><code>public static class MockObjects
{
    public static  Mock&lt;UserManager&lt;TUser&gt;&gt; GetUserManagerMock&lt;TUser&gt;() where TUser : IdentityUser
    {
        return new Mock&lt;UserManager&lt;TUser&gt;&gt;(
            new Mock&lt;IUserStore&lt;TUser&gt;&gt;().Object,
            new Mock&lt;IOptions&lt;IdentityOptions&gt;&gt;().Object,
            new Mock&lt;IPasswordHasher&lt;TUser&gt;&gt;().Object,
            new IUserValidator&lt;TUser&gt;[0],
            new IPasswordValidator&lt;TUser&gt;[0],
            new Mock&lt;ILookupNormalizer&gt;().Object,
            new Mock&lt;IdentityErrorDescriber&gt;().Object,
            new Mock&lt;IServiceProvider&gt;().Object,
            new Mock&lt;ILogger&lt;UserManager&lt;TUser&gt;&gt;&gt;().Object);
    }

    public static Mock&lt;SignInManager&lt;TUser&gt;&gt; GetSignInManagerMock&lt;TUser&gt;() where TUser : IdentityUser
    {
        return new Mock&lt;SignInManager&lt;TUser&gt;&gt;(
            GetUserManagerMock&lt;TUser&gt;().Object,
            new Mock&lt;IHttpContextAccessor&gt;().Object,
            new Mock&lt;IUserClaimsPrincipalFactory&lt;TUser&gt;&gt;().Object,
            new Mock&lt;IOptions&lt;IdentityOptions&gt;&gt;().Object,
            new Mock&lt;ILogger&lt;SignInManager&lt;TUser&gt;&gt;&gt;().Object,
            new Mock&lt;IAuthenticationSchemeProvider&gt;().Object
            );
    }

    public static Mock&lt;RoleManager&lt;TIdentityRole&gt;&gt; GetRoleManagerMock&lt;TIdentityRole&gt;() where TIdentityRole : IdentityRole
    {
        return new Mock&lt;RoleManager&lt;TIdentityRole&gt;&gt;(
            new Mock&lt;IRoleStore&lt;TIdentityRole&gt;&gt;().Object,
            new IRoleValidator&lt;TIdentityRole&gt;[0],
            new Mock&lt;ILookupNormalizer&gt;().Object,
            new Mock&lt;IdentityErrorDescriber&gt;().Object,
            new Mock&lt;ILogger&lt;RoleManager&lt;TIdentityRole&gt;&gt;&gt;().Object);
    }

    public static Mock&lt;ApplicationDbContext&gt; GetDbContextMock()
    {
        return new Mock&lt;ApplicationDbContext&gt;(new DbContextOptions&lt;ApplicationDbContext&gt;());
    }

    public static Mock&lt;TRepository&gt; GetRepositoryMock&lt;TRepository&gt;() where TRepository : class
    {
        return new Mock&lt;TRepository&gt;(GetDbContextMock().Object);
    }

    public static Mock&lt;ISmsService&gt; GetSmsServiceMock()
    {
        return new Mock&lt;ISmsService&gt;(GetRepositoryMock&lt;SmsRepository&gt;().Object);
    }

    public static Mock&lt;IEmailService&gt; GetEmailServiceMock()
    {
        return new Mock&lt;IEmailService&gt;(GetRepositoryMock&lt;EmailRepository&gt;().Object);
    }

    public static Mock&lt;IProfileService&gt; GetProfileServiceMock()
    {
        return new Mock&lt;IProfileService&gt;(GetRepositoryMock&lt;ProfileRepository&gt;().Object);
    }

    public static Mock&lt;IAccountService&gt; GetAccountServiceMock()
    {
        return new Mock&lt;IAccountService&gt;(
            GetUserManagerMock&lt;ApplicationUser&gt;().Object,
            GetSignInManagerMock&lt;ApplicationUser&gt;().Object,
            GetSmsServiceMock().Object,
            GetEmailServiceMock().Object,
            new Mock&lt;IConfiguration&gt;().Object,
            GetProfileServiceMock().Object
            );
    }
}
</code></pre>

<p>I implemented this class following this blog post:
<a href=""https://dejanstojanovic.net/aspnet/2019/september/unit-testing-repositories-in-aspnet-core-with-xunit-and-moq/"" rel=""nofollow noreferrer"">https://dejanstojanovic.net/aspnet/2019/september/unit-testing-repositories-in-aspnet-core-with-xunit-and-moq/</a></p>

<p>My Test Method:</p>

<pre><code>[Fact]
public async Task RegisterSimpleTest()
{
    // Arrange
    var mockService = MockObjects.GetAccountServiceMock().Object;
    var controller = new AccountController(mockService);
    var data = new EmailRegisterViewModel()
    {
        Email = ""a@a.a"",
        Password = ""123456"",
        ConfirmPassword = ""123456""
    };
    // Act
    var result = await controller.Register(data) as ObjectResult;

    // Assert
    Assert.NotNull(result);
    Assert.Equal(200, result.StatusCode);
}
</code></pre>

<p>And Controller Action which I want to test:</p>

<pre><code>[HttpPost]
public async Task&lt;IActionResult&gt; Register([FromBody]EmailRegisterViewModel model)
{
    if (!ModelState.IsValid)
    {
        var errors = ModelStateExtention.GetModelErrors(ModelState);
        return BadRequest(errors);
    }
    var user = new ApplicationUser()
    {
        UserName = model.Email,
        Email = model.Email
    };

    var result = await _accountService.EmailRegisterAsync(user, model.Password);
    return StatusResultExtension&lt;ActionMessage&gt;.GetStatusResult(result);
}
</code></pre>

<p>How can I perform Unit Test? What's the wrong I am doing?</p>
",https://stackoverflow.com/questions/58483917/how-to-mock-all-layer-of-application-in-test-method,"['c#', 'unit-testing', 'asp.net-core', 'dependency-injection', 'xunit.net']",953,False,0,1
Why can most of the mock frameworks in .NET (Core) not mock static and private methods?,"<p>My question is about the <strong>technical reason</strong> for this limitation, not about how to fix it.</p>
<p>Why do some frameworks like <a href=""https://www.telerik.com/products/mocking.aspx"" rel=""nofollow noreferrer"">Telerik JustMock</a> and <a href=""https://www.typemock.com/"" rel=""nofollow noreferrer"">Typemock Isolator</a> support these features, but we can not have these in <a href=""https://github.com/moq/moq4"" rel=""nofollow noreferrer"">Moq</a> or <a href=""https://fakeiteasy.github.io/"" rel=""nofollow noreferrer"">FakeItEasy</a> or <a href=""https://nsubstitute.github.io/"" rel=""nofollow noreferrer"">NSubstitute</a>, etc.?</p>
<p>Are the items mentioned unnecessary in unit testing?</p>
",https://stackoverflow.com/questions/56249527/why-can-most-of-the-mock-frameworks-in-net-core-not-mock-static-and-private-m,"['c#', 'mocking', 'moq', 'nsubstitute', 'fakeiteasy']",1311,True,4,1
Swipe left in unit test manually to call handler to test in Swift,"<p>I am unit testing the tableview and I need to swipe logically? a row in UITableView. Is it possible to execute the swiping in unit test to invoke the handler? I looked at the UITableViewDelegate but there isn't a swiping action (didSelectRowAt is there and tested in unit test).</p>

<pre><code>func createDeleteHandler(tableView : UITableView, indexPath : IndexPath) -&gt; UIContextualAction.Handler {
        let deleteHandler =  { (ac:UIContextualAction, view:UIView, success:(Bool) -&gt; Void) in
            let noteToBeDeleted = self.notes[indexPath.row]
            NoteManager.shared.deleteNote(note: noteToBeDeleted)
            self.notes.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
            success(true)
        }

        return deleteHandler
    }
</code></pre>
",https://stackoverflow.com/questions/55129843/swipe-left-in-unit-test-manually-to-call-handler-to-test-in-swift,"['ios', 'swift', 'uitableview', 'handler']",1223,True,2,2
How can I use Catch2 to test my CMake static library project?,"<p>I'm writing a static library which contains some shared code between several projects. In order to verify that the code in this library functions properly I'd like to use Catch2 to do some unit testing on it.</p>

<p>Unfortunately, when attempting to run the tests I run into the problem that the compilation's output file is a shared library (.a), rather than an executable.</p>

<p>I'm sure I can create a separate project which uses the functions from my static library, and subsequently run tests that way, but ideally I'd like to keep the tests and build configurations as close as possible to one another.</p>

<p>So my question is:
what's the best way to set up my project such that I can use Catch2 for unit testing my  static library code?</p>

<p>Here's my project's CMakeLists.txt file for reference:</p>

<pre><code>project(sharedLib CXX)

find_package(OpenMP)

if (CMAKE_COMPILER_IS_GNUCC)
    set(CMAKE_CXX_FLAGS ""${CMAKE_CXX_FLAGS} -fopenmp -lpthread -Wall -Wextra -Wpedantic -std=c++17"")
endif()

if (MSVC)
    set(CMAKE_CXX_FLAGS ""${CMAKE_CXX_FLAGS} /fopenmp /W4 /std:c++latest"")
endif()

include_directories (
        src/
        lib/Catch2/single_include/
)

file (GLOB_RECURSE LIBRARY_SOURCES src/*.cpp
                                   src/*.c
                                   tests/*.cpp)

add_library(${PROJECT_NAME} STATIC ${LIBRARY_SOURCES})

target_include_directories(${PROJECT_NAME} PUBLIC src/)
</code></pre>
",https://stackoverflow.com/questions/55227598/how-can-i-use-catch2-to-test-my-cmake-static-library-project,"['c++', 'catch2']",2499,True,3,1
How to test directory reading and addressing method in ruby?,"<p>I have a ruby class to read directory and do something for each file. But I am not sure how to test it.</p>

<pre><code>class Scanner
  def scan(dir)
    Dir.glob(File.join(dir, '**', '*')).each do |path|
       verify(path)
    end
  end

  private 

  def verify(path)
    do something for the file...
  end
end
</code></pre>

<p>I want to have a unit-testing for <code>scan</code> method. </p>

<ul>
<li>Should I mock something?</li>
<li>Should I provide a test directory in <code>spec/fixtures</code>?</li>
<li>What's the expectation?</li>
</ul>

<p>Cheers</p>
",https://stackoverflow.com/questions/56312157/how-to-test-directory-reading-and-addressing-method-in-ruby,"['ruby', 'rspec']",394,False,0,1
ExecutorService Submit Method Return NULL,"<p>I have Executor Service, and submitting it. It returns Future>. My code as below,</p>

<pre><code>for (int i = 0; i &lt; firstSplitFiles.size(); i++) {
            Future&lt;Map&lt;String, AtomicInteger&gt;&gt; result = executorService.submit(new WordCountTask(firstSplitFiles, firstFile.getName()));
            firstFileCounterMap = result.get();
        }
</code></pre>

<p>I have written Unit testing as below,</p>

<pre><code>
 @Mock
    private Future&lt;Map&lt;String, AtomicInteger&gt;&gt; firstFileWordCounter;

    @Mock
    private Future&lt;Map&lt;String, AtomicInteger&gt;&gt; secondFileWordCounter;


    when(executorService.submit(new WordCountTask(Collections.emptyList(), firstFile.getName()))).thenReturn(firstFileWordCounter);
        when(executorService.submit(new WordCountTask(Collections.emptyList(), secondFile.getName()))).thenReturn(secondFileWordCounter);

        when(firstFileWordCounter.get()).thenReturn(firstCounterMap);
        when(secondFileWordCounter.get()).thenReturn(secondCounterMap);
FileReadHelper.splitAndReadProcess(firstFile, secondFile, executorService, 21);

</code></pre>

<p>and my splitAndReadProcess method as below,</p>

<pre><code>public static void splitAndReadProcess(File firstFile, File secondFile, ExecutorService executorService, int splitSize) throws
            IOException, InterruptedException, ExecutionException {

        AtomicInteger atomicInteger = new AtomicInteger(INITIAL_COUNTER_VALUE);
        Map&lt;String, AtomicInteger&gt; firstFileCounterMap = null;
        Map&lt;String, AtomicInteger&gt; secondFileCounterMap = null;

        List&lt;File&gt; firstSplitFiles = splitFile(firstFile, splitSize, atomicInteger);
        List&lt;File&gt; secondSplitFiles = splitFile(secondFile, splitSize, atomicInteger);
        logger.info(""Reading File(s) process started!"");
        for (int i = 0; i &lt; firstSplitFiles.size(); i++) {
            Future&lt;Map&lt;String, AtomicInteger&gt;&gt; result = executorService.submit(new WordCountTask(firstSplitFiles, firstFile.getName()));
            firstFileCounterMap = result.get(); // NULL RESULT
        }

        for (int j = 0; j &lt; secondSplitFiles.size(); j++) {
            Future&lt;Map&lt;String, AtomicInteger&gt;&gt; result = executorService.submit(new WordCountTask(secondSplitFiles, secondFile.getName()));
            secondFileCounterMap = result.get();
        }


    }
</code></pre>

<p>I'm getting result as NULL. Is this correct approach or i need to modify something in a way of coding?</p>
",https://stackoverflow.com/questions/58199624/executorservice-submit-method-return-null,"['multithreading', 'unit-testing', 'junit', 'concurrency', 'mockito']",118,False,0,1
Puppeteer mock page request object,"<pre><code>import { Page } from 'puppeteer/lib/Page';
export class MonitorRequestHelper {
   public static monitorRequests(page: Page, on = false) {
    if(on) {
      page.on('request', req =&gt; {
        if (['image', 'font', 'stylesheet'].includes(req.resourceType())) {
          // Abort requests for images, fonts &amp; stylesheets to increase page load speed.

          req.abort();
        } else {
          req.continue();
        }
      });
    } else {
      return true;
    }
  }
}
</code></pre>

<p>I am trying to mock and spy the function to check if it got called at least once.
Also, it would be helpful if some explain me how to mock and spy event-emitter object. 
The source code is available on <a href=""https://github.com/Mukesh23singh/puppeteer-unit-testing"" rel=""nofollow noreferrer"">https://github.com/Mukesh23singh/puppeteer-unit-testing</a></p>
",https://stackoverflow.com/questions/54784426/puppeteer-mock-page-request-object,"['node.js', 'mocha.js', 'sinon', 'puppeteer', 'eventemitter']",1291,True,0,1
Redux Form component &quot;onSubmitSuccess&quot; Unit Test,"<p>I am new to react, I need a help for writing a test case for Redux Form component ""onSubmitSuccess"",
below is the code </p>

<pre><code>reduxForm({ form: ""AddTagForm"", 
  enableReinitialize: true,
  onSubmitSuccess: afterSubmit })

callback function,

export const afterSubmit = (dispatch) =&gt; dispatch(reset(""AddTagForm""));
</code></pre>

<p>I need a help for writing a test case for afterSubmit method. Please help</p>

<p>Note: I am using jest with enzyme for unit testing.</p>
",https://stackoverflow.com/questions/58406872/redux-form-component-onsubmitsuccess-unit-test,"['reactjs', 'react-redux', 'jestjs']",147,False,0,1
Trouble unit testing onClick method using Mocha Chai and Enzyme,"<p>I'm having trouble with unit testing using mocha, chai and enzyme for the following. I can't seem to understand how to unit test methods in components and how to unit test <code>onClick</code> methods will call those methods. 
The following is what I am trying to unit test: </p>

<pre><code>&lt;Link to=""/create-new-template-results"" onClick={this.checkLink}&gt;
    &lt;Button
        buttonname=""Next_button""
        variant=""primary""
        label=""Save""
        onClickMethod={() =&gt; this.submitTemplateCreation()}
        disabled={!this.disabledButtonCheck()}
    /&gt;
&lt;/Link&gt;
</code></pre>

<p>.</p>

<pre><code>Header: '',
Cell: value =&gt; {
    return (
        &lt;div&gt;
            &lt;img
                height={34}
                src=""https://content.usaa.com/mcontent/static_assets/Media/icon-trash.svg""
                onClick={() =&gt; this.removeAttribute(value)}
            /&gt;
        &lt;/div&gt;
    );
}
</code></pre>

<p>.</p>

<pre><code>removeAttribute = value =&gt; {
    this.props.change('templateAttributeForm', value.original.name, '');
    this.props.removeAttributeItem(value.index);
};

submitTemplateCreation() {
    let profLvlData = Object.values(this.props.templateAttributeFormData);
    let attrData = Object.keys(this.props.templateAttributeFormData);
    let attributeProfLvl = attributeProfLvlUtil(attrData, profLvlData);
    let templateCreationJSON = templateCreationPOSTFilter(attributeProfLvl, this.props.templateFormData);
    this.props.submitTemplateCreation(templateCreationJSON);
}
</code></pre>
",https://stackoverflow.com/questions/54635758/trouble-unit-testing-onclick-method-using-mocha-chai-and-enzyme,"['unit-testing', 'react-redux', 'mocha.js', 'enzyme', 'chai']",2308,False,0,1
Test setters and getters with CHAI,"<p>I'm studying for an exam, and one of the tasks will be unit testing with Chai and Mocha, but couldn't quite understand how to test if a class has getter and settor methods for properties. Can you help me out? Here's a sample class from homework:</p>

<pre><code> class PaymentPackage {
    constructor(name, value) {
        this.name = name;
        this.value = value;
        this.VAT = 20;      // Default value    
        this.active = true; // Default value
      }

  get name() {
    return this._name;
  }

  set name(newValue) {
    if (typeof newValue !== 'string') {
      throw new Error('Name must be a non-empty string');
    }
    if (newValue.length === 0) {
      throw new Error('Name must be a non-empty string');
    }
    this._name = newValue;
  }

  get value() {
    return this._value;
  }

  set value(newValue) {
    if (typeof newValue !== 'number') {
      throw new Error('Value must be a non-negative number');
    }
    if (newValue &lt; 0) {
      throw new Error('Value must be a non-negative number');
    }
    this._value = newValue;
  }

  get VAT() {
    return this._VAT;
  }

  set VAT(newValue) {
    if (typeof newValue !== 'number') {
      throw new Error('VAT must be a non-negative number');
    }
    if (newValue &lt; 0) {
      throw new Error('VAT must be a non-negative number');
    }
    this._VAT = newValue;
  }

  get active() {
    return this._active;
  }

  set active(newValue) {
    if (typeof newValue !== 'boolean') {
      throw new Error('Active status must be a boolean');
    }
    this._active = newValue;
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/59164159/test-setters-and-getters-with-chai,"['unit-testing', 'chai']",486,True,0,1
I need to call a method from another class that has dependencies,"<p>I am unit testing and my test is running two tests due to me having to call the class and then the method so I get one assertion and one failure.</p>

<pre><code>assert_equal(Class, ClassName.new('query', 'test').upload_file(results_csv, 'test'), 'tests do not match')

assert_equal(Class, ClassName.new('query', 'test').upload_file(results_csv, 'test'), 'tests do not match')
</code></pre>

<p>I get one assertion and one failure due to the unit test running two tests.</p>
",https://stackoverflow.com/questions/56996695/i-need-to-call-a-method-from-another-class-that-has-dependencies,['ruby'],30,False,0,0
Jest test run not recognizing `jest.spyOn`,"<p>I am using <code>jest-preset-angular</code> to using jest for unit testing. (Earlier i was using karma). I have converted my tests using <code>jest-codemods</code>.</p>

<p>I am getting jest test error when i run the test</p>

<pre><code>TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    src/app/mymodele/my-component.component.spec.ts:38:9 - error TS2554: Expected 3 arguments, but got 2.

    38         jest.spyOn(component, 'mymethod').mockImplementation();
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code></pre>

<p>IDE is recognizing the <code>jest.spyOn</code> method but then the test runs this is displayed</p>

<p>Jest Debug 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>{
  ""configs"": [
    {
      ""automock"": false,
      ""browser"": false,
      ""cache"": true,
      ""cacheDirectory"": ""&lt;user-profile&gt;\\AppData\\Local\\Temp\\jest"",
      ""clearMocks"": false,
      ""coveragePathIgnorePatterns"": [
        ""\\\\node_modules\\\\""
      ],
      ""cwd"": ""&lt;my-proj-root-dir&gt;"",
      ""dependencyExtractor"": null,
      ""detectLeaks"": false,
      ""detectOpenHandles"": false,
      ""errorOnDeprecated"": false,
      ""filter"": null,
      ""forceCoverageMatch"": [],
      ""globalSetup"": null,
      ""globalTeardown"": null,
      ""globals"": {
        ""ts-jest"": {
          ""tsConfig"": ""&lt;rootDir&gt;/src/tsconfig.spec.json"",
          ""stringifyContentPathRegex"": ""\\.html$"",
          ""astTransformers"": [
            ""&lt;my-proj-root-dir&gt;\\node_modules\\jest-preset-angular\\InlineHtmlStripStylesTransformer.js""
          ]
        }
      },
      ""haste"": {
        ""computeSha1"": false,
        ""providesModuleNodeModules"": [],
        ""throwOnModuleCollision"": false
      },
      ""moduleDirectories"": [
        ""node_modules""
      ],
      ""moduleFileExtensions"": [
        ""ts"",
        ""html"",
        ""js"",
        ""json""
      ],
      ""moduleNameMapper"": [
        [
          ""@app/(.*)"",
          ""&lt;my-proj-root-dir&gt;\\src\\app\\$1""
        ],
        [
          ""@assets/(.*)"",
          ""&lt;my-proj-root-dir&gt;\\src\\assets\\$1""
        ],
        [
          ""@core/(.*)"",
          ""&lt;my-proj-root-dir&gt;\\src\\app\\core\\$1""
        ],
        [
          ""@env"",
          ""&lt;my-proj-root-dir&gt;\\src\\environments\\environment""
        ],
        [
          ""@src/(.*)"",
          ""&lt;my-proj-root-dir&gt;\\src\\src\\$1""
        ],
        [
          ""@state/(.*)"",
          ""&lt;my-proj-root-dir&gt;\\src\\app\\state\\$1""
        ],
        [
          ""helpers/(.*)"",
          ""&lt;my-proj-root-dir&gt;\\src\\helpers\\$1""
        ],
        [
          ""app/(.*)"",
          ""&lt;my-proj-root-dir&gt;\\src\\app\\$1""
        ],
        [
          ""environments/(.*)"",
          ""&lt;my-proj-root-dir&gt;\\src\\environments\\$1""
        ],
        [
          ""^src/(.*)$"",
          ""&lt;my-proj-root-dir&gt;\\src\\$1""
        ],
        [
          ""^app/(.*)$"",
          ""&lt;my-proj-root-dir&gt;\\src\\app\\$1""
        ],
        [
          ""^assets/(.*)$"",
          ""&lt;my-proj-root-dir&gt;\\src\\assets\\$1""
        ],
        [
          ""^environments/(.*)$"",
          ""&lt;my-proj-root-dir&gt;\\src\\environments\\$1""
        ]
      ],
      ""modulePathIgnorePatterns"": [],
      ""name"": ""b6bd5a0b25dd9d0d8be554d366e12f3d"",
      ""prettierPath"": ""prettier"",
      ""resetMocks"": false,
      ""resetModules"": false,
      ""resolver"": null,
      ""restoreMocks"": false,
      ""rootDir"": ""&lt;my-proj-root-dir&gt;"",
      ""roots"": [
        ""&lt;my-proj-root-dir&gt;\\src""
      ],
      ""runner"": ""jest-runner"",
      ""setupFiles"": [],
      ""setupFilesAfterEnv"": [
        ""&lt;my-proj-root-dir&gt;\\src\\setup-jest.ts""
      ],
      ""skipFilter"": false,
      ""snapshotSerializers"": [
        ""&lt;my-proj-root-dir&gt;\\node_modules\\jest-preset-angular\\AngularSnapshotSerializer.js"",
        ""&lt;my-proj-root-dir&gt;\\node_modules\\jest-preset-angular\\HTMLCommentSerializer.js""
      ],
      ""testEnvironment"": ""&lt;my-proj-root-dir&gt;\\node_modules\\jest-environment-jsdom-thirteen\\build\\index.js"",
      ""testEnvironmentOptions"": {},
      ""testLocationInResults"": false,
      ""testMatch"": [
        ""**/__tests__/**/*.[jt]s?(x)"",
        ""**/?(*.)+(spec|test).[tj]s?(x)""
      ],
      ""testPathIgnorePatterns"": [
        ""\\\\node_modules\\\\""
      ],
      ""testRegex"": [],
      ""testRunner"": ""&lt;my-proj-root-dir&gt;\\node_modules\\jest-jasmine2\\build\\index.js"",
      ""testURL"": ""http://localhost"",
      ""timers"": ""real"",
      ""transform"": [
        [
          ""^.+\\.(ts|js|html)$"",
          ""&lt;my-proj-root-dir&gt;\\node_modules\\ts-jest\\dist\\index.js""
        ]
      ],
      ""transformIgnorePatterns"": [
        ""&lt;my-proj-root-dir&gt;\\\\node_modules\\\\(?!@ngrx|jest-test)""
      ],
      ""watchPathIgnorePatterns"": []
    }
  ],
  ""globalConfig"": {
    ""bail"": 0,
    ""changedFilesWithAncestor"": false,
    ""collectCoverage"": false,
    ""collectCoverageFrom"": null,
    ""coverageDirectory"": ""&lt;my-proj-root-dir&gt;\\coverage"",
    ""coverageReporters"": [
      ""json"",
      ""text"",
      ""lcov"",
      ""clover""
    ],
    ""coverageThreshold"": null,
    ""detectLeaks"": false,
    ""detectOpenHandles"": false,
    ""errorOnDeprecated"": false,
    ""expand"": false,
    ""filter"": null,
    ""globalSetup"": null,
    ""globalTeardown"": null,
    ""json"": false,
    ""listTests"": false,
    ""maxConcurrency"": 5,
    ""maxWorkers"": 4,
    ""noStackTrace"": false,
    ""nonFlagArgs"": [],
    ""notify"": false,
    ""notifyMode"": ""failure-change"",
    ""passWithNoTests"": false,
    ""projects"": null,
    ""rootDir"": ""&lt;my-proj-root-dir&gt;"",
    ""runTestsByPath"": false,
    ""skipFilter"": false,
    ""testFailureExitCode"": 1,
    ""testNamePattern"": """",
    ""testPathPattern"": """",
    ""testResultsProcessor"": null,
    ""updateSnapshot"": ""new"",
    ""useStderr"": false,
    ""verbose"": null,
    ""watch"": true,
    ""watchman"": true
  },
  ""version"": ""24.5.0""
}</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/55181748/jest-test-run-not-recognizing-jest-spyon,"['angular', 'reactjs', 'typescript', 'jestjs']",273,False,0,0
VS 2017 Live Unit Testing persisted data directory is read only,"<p>I'm having an issue with live unit testing, and have found that the solution may be to set a different persisted data directory (seen below). I try to do this, but that field is read-only for me. Running VS as administrator does nothing. What could cause this?</p>

<p><a href=""https://i.stack.imgur.com/JR3gD.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/JR3gD.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/57171359/vs-2017-live-unit-testing-persisted-data-directory-is-read-only,"['visual-studio', 'live-unit-tests']",61,True,1,1
Mockito junit testing not working- beans mocked by @mockBean are null,"<p>I am trying Mockito for mocking and unit testing. </p>

<p>Trying to mock an autowired bean using <code>@MockBean</code>. But the bean is null at run time.</p>

<p>Class under test. </p>

<pre><code>@Service
public class UserServiceImpl  {

  @Autowired
  GenericRestClient restClient;

  @Autowired
  RequestMapper requestMapper;

  @Autowired
  ResponseMapper responseMapper;

  @Override
  public List&lt;User&gt; findUsers(RRequest requestBody,
      String index) throws HostException {
List&lt;User&gt; users= 
requestMapper.mapRequest(""test"");
// ...doing something
return users;
}
</code></pre>

<p>The test class :</p>

<pre><code>
import static org.junit.Assert.assertNotNull;

import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.mock.mockito.MockBean;

@RunWith(MockitoJUnitRunner.class)

public class UserServiceImplTest {

    @MockBean
    GenericRestClient restClient;

    @MockBean
    RequestMapper requestMapper;

    @MockBean
    ResponseMapper responseMapper;

    @InjectMocks
    UserServiceImpl userService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

    }

    @Test
    public void testFindUsers() {
List&lt;Users&gt; users = null;
        Mockito.when(requestMapper.mapRequest(""test""))
        .thenReturn(users); 
        assertNull(users);      
    }
}

</code></pre>

<p>Error : </p>

<pre><code>java.lang.NullPointerException
    at test.my.code.UserServiceImplTest.testFindUsers(UserServiceImplTest.java:10)
    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.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.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>I have debugged, <code>NullPointerException</code> is because of <code>requestMapper</code> (mocked using MockBean as it is <code>null</code>.)</p>

<p>What is wrong with this code?</p>
",https://stackoverflow.com/questions/58673420/mockito-junit-testing-not-working-beans-mocked-by-mockbean-are-null,"['unit-testing', 'junit', 'mockito']",9535,True,1,3
How do I trigger the valuesChanged observable in a unit test after making changes to a FormGroup?,"<p>I am writing unit testing code on a component that includes a reactive form (FormGroup) and a subscription to valueChanges and I haven't figured out how to ensure the valueChanges event gets emitted by the FormGroup.</p>

<pre><code>// In the component under test:
this.formGroup.get('field').valueChanges
     .subscribe((obj: any[]) =&gt; {
         debugger; // BREAKPOINT
         dataObject.fieldValues = [ ... ];
         ... details here should be unimportant ...
     });

// In the unit test:
it('should set dataObject from field component', fakeAsync(() =&gt; {
        [
    values: string[] = [ ... ];

    component.formGroup.get('field').setValue(values);
    component.formGroup.get('field').updateValueAndValidity({ emitEvent: true });
    fixture.detectChanges();
    tick();

    expect(component.dataObject.fieldValues.length).toEqual(values.length);

}));

</code></pre>

<p>I can not get the unit test spec to hit the breakpoint in the component subscription code.</p>
",https://stackoverflow.com/questions/56135552/how-do-i-trigger-the-valueschanged-observable-in-a-unit-test-after-making-change,"['angular', 'unit-testing', 'angular-reactive-forms']",6268,True,4,1
What would happen when the Websockets protocol is disabled?,"<p>I'm working with Socket.io and I'm trying to disable Websockets for unit testing purposes. Obviously, none of the pushes from the backend reached the client.</p>

<p>But that got me wondering. What are the drawbacks of having websocket protocol disabled? Other than rendering my program completely useless, I mean.</p>
",https://stackoverflow.com/questions/57542935/what-would-happen-when-the-websockets-protocol-is-disabled,"['node.js', 'sockets', 'websocket', 'socket.io']",25,False,1,0
R: test on multiple versions,"<p>Does anyone have a solution for automating unit testing of R packages under various multiple versions of R and/or prerequisite packages?</p>

<p>Python has a nice package, <a href=""https://tox.readthedocs.io/en/latest/"" rel=""nofollow noreferrer""><code>tox</code></a>, which allows the user to write a configuration file specifying what dimensions to expand over, then it runs testing under all combinations of those.</p>
",https://stackoverflow.com/questions/56386271/r-test-on-multiple-versions,"['r', 'unit-testing', 'testing', 'configuration']",97,False,2,0
Want to Mock ValidationofToken in restcontroller junit testing,"<p>Need to skip a Validation of token id login in controller for unit testing</p>

<p>Not sure what to use Mock or spy since i'm testing the controller itself</p>

<pre><code>public class TestController extends BaseController {

    @Autowired
    TestService service;    

    @RequestMapping(value = ""/test"")
    public @ResponseBody TestResponse getAll(@RequestBody TestRequest request) {

        validateToken(request);
        TestResponse response = service.getall(request);
        response.setTokenID(request.getTokenID());
        return response;
    }   

}
</code></pre>

<hr>

<pre><code>public class BaseController {

    protected void validateToken(IRequest request) {

        TokenResponse tokenresponse = restTemplate.exchange(TokenServiceURL, HttpMethod.GET, null, TokenResponse .class, tokenId).getBody();
        User user = new user()
        user.setUserRole(tokenresponse.getUser()));
        request.setUser(user);
    }
}
</code></pre>

<hr>

<pre><code>public class TestControllerTest {

    private MockMvc mockMvc;

    @Autowired
        private WebApplicationContext wac;

    @Autowired
    private TestController testControlller;

    @MockBean
        private TestService testService;

    BaseController baseControllerSpy = Mockito.spy(BaseController.class);


    @Before
    public void setUp(){
         MockitoAnnotations.initMocks(this);        
             mockMvc =  MockMvcBuilders.webAppContextSetup(wac).build();
    }


    @Test
    public void verifygetAll() throws Exception {
        TestRequest request = new TestRequest();        
        TestResponse response = new Response();     

        **Mockito.doNothing().when(baseControllerSpy).validateTokenID(request);**
        when(testService.get(request)).thenReturn(response);

        mockMvc.perform(MockMvcRequestBuilders.post(""/test"")
        .contentType(MediaType.APPLICATION_JSON)
        .content(requestString)
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
    }
</code></pre>

<h2>    }</h2>

<p>Base controller being spy doesn't seem to work, is there any other way i can approach this scenrio. please help</p>
",https://stackoverflow.com/questions/57085950/want-to-mock-validationoftoken-in-restcontroller-junit-testing,"['spring', 'spring-mvc', 'mocking', 'springmockito']",75,False,0,1
Unit testing: getText is not a function,"<p>I'm new to unit testing and I'm trying to select an ID to select its text and check if it equals 'Inbox'. I'm getting a</p>

<blockquote>
  <p>TypeError in ""User visits Quick Add Task starts with a blank task"" elem.getText is not a function</p>
</blockquote>

<p>and I don't understand why.
Test source code <a href=""https://pastebin.com/77qUEnpB"" rel=""nofollow noreferrer"">here</a>.</p>

<pre><code>describe('User visits Quick Add Task', () =&gt; {
    it('starts with a blank task', () =&gt; {
        browser.url('http://localhost:8080/');

        const elem = $('#inbox-clickable');
        console.log(elem.getText());

        assert.equal(elem.getText(), 'Inbox');

    })
});
</code></pre>
",https://stackoverflow.com/questions/57541520/unit-testing-gettext-is-not-a-function,"['mocha.js', 'chai', 'webdriver-io']",4000,True,2,1
How to use sinon for middleware testing in nodejs?,"<p>Trying to test failure scenario for the middleware , v1TransformResponse will throw error on some validation now in unit testing i am not able to get expected result , any idea what is implemented wrong in below test ? i have added the error i am getting.</p>

<p>server.js</p>

<pre><code>app.post('/cvs/v1/drugprice/:membershipId', orchestrateDrugPrice, v1TransformResponse);
</code></pre>

<p>v1TransformResponse.js</p>

<pre><code>module.exports = async (req, res) =&gt; {
  try {
    const validateResponse = responseHandler(req.drugPriceResponse);
    const transformedResponse = transformResponse(validateResponse);
    const filterDrug = filteredResponse(transformedResponse);
    logDrugPriceResponse('TRANSFORMED_RESPONSE V1', filterDrug);

    res.status(200).send({ drugPrice: filterDrug });
  } catch (error) {
    if (error instanceof AppError) {
      res.status(error.response.status).send(error.response.payload);
    } else {
      res.status(500).send(defaultErrorResponse);
    }
  }
};
</code></pre>

<p>main.test.js</p>

<pre><code>const { expect } = require('chai');
const sinon = require('sinon');
const { spy, stub } = require('sinon');
const request = require('supertest');
const app = require('./../../../server/server');
const v1TransformResponse = require('./../../../server/middleware/v1TransformResponse');
const orchestrateDrugPrice = require('./../../../server/middleware/orchestrateDrugPrice');

describe('v1Transform()', () =&gt; {
  let status,
    send,
    res;
  beforeEach(() =&gt; {
    status = stub();
    send = spy();
    res = { send, status };
    status.returns(res);
  });
  describe('if called with a request that doesn\'t have an example query', () =&gt; {
    const req = {
      drugPriceResponse: [{
        'brand': false,
        'drugName': 'Acitretin',
        'drugStrength': '10mg',
        'drugForm': 'Capsule',
        'retailPrice': {
          'copayEmployer': '0',
          'costAnnual': '3',
          'costEmployer': '733.84',
          'costToday': 'N/A',
          'daysSupply': '30',
          'deductible': 'n/a',
          'memberCopayAmount': '30',
          'NDC11': '378702093',
          'penalties': 'N/A',
          'totalDrugCost': '763.84'
        }
      }]
    };
    beforeEach(() =&gt; (req, res));
    it('should return error if prices are ommitted', async () =&gt; {
      try {
        await v1TransformResponse(req, res);
      } catch (error) {
        expect(error.response).to.deep.equal({
          httpStatus: 500,
          payload: {
            status: 500,
            title: 'Internal Server Error',
            detail: 'Drug prices are not valid'
          }
        });
      }
    });
  });
});
</code></pre>

<p>ERROR:</p>

<pre><code>  if called with a request that doesn't have an example query
         should return error if prices are ommitted:
     AssertionError: expected undefined to deeply equal { Object (httpStatus, payload) }
</code></pre>
",https://stackoverflow.com/questions/56960779/how-to-use-sinon-for-middleware-testing-in-nodejs,"['node.js', 'unit-testing', 'chai', 'sinon']",42,True,0,1
"How to test my ETL pipeline entirely on Amazon Athena, given that there are no libraries or mocks for it?","<p>I am writing a huge big data ETL pipeline entirely written on AWS Athena and Python just orchestrating the athena queries, There are no unit testing frameworks or libraries which can help in mocking for example w.r.t AWS Athena. I would want to write unit tests and make sure my queries work as expected.</p>
",https://stackoverflow.com/questions/55755376/how-to-test-my-etl-pipeline-entirely-on-amazon-athena-given-that-there-are-no-l,"['python', 'python-3.x', 'amazon-web-services', 'bigdata', 'amazon-athena']",459,False,5,0
How do I view the XML produced by the python-docx package,"<p>For the purposes of unit testing, I want to check that the XML produced for a Word paragraph is what I expect when I parse an HTML paragraph.</p>

<p>How do I extract the XML itself instead of writing to a file, unzipping the file, and re-reading the word/document.xml file it contains?</p>

<p>e.g.</p>

<pre><code>from docx import Document
import bs4

def add_parsed_html_to_paragraph(p, s):
    soup = bs4.BeautifulSoup(s)
    para = soup.find('p')
    for e in para.children:
        if type(e) == bs4.element.NavigableString:
            r = p.add_run(str(e))
        else:
            r = p.add_run(e.text)
        if e.name == 'sub':
            r.font.subscript = True
        elif e.name == 'sup':
            r.font.superscript = True


title = 'A formula: H&lt;sub&gt;2&lt;/sub&gt;O.'

document = Document()
p = document.add_paragraph()
add_parsed_html_to_paragraph(p, title)

# ... Now I want to check p or document for the correct XML
</code></pre>
",https://stackoverflow.com/questions/56357111/how-do-i-view-the-xml-produced-by-the-python-docx-package,"['python', 'xml', 'docx', 'python-docx']",10271,True,5,1
Content values are assigned null even after putting values in it,"<p>As a part of Unit testing I wanted to insert values to DB using content resolver. But when I tried this,</p>

<pre><code> @Before
    public void runBeforeTestSignOut() {
        ContentValues values = new ContentValues();
        String userId=""123"";
        String userInfo=""test"";
        values.put(UserProvider.USER_ID, userId);
        values.put(UserProvider.USER_INFO, userInfo);
        System.out.print(""Values are ""+values);
        Uri uri = contentResolver.insert(UserProvider.CONTENT_USER_URI, values);
    }
</code></pre>

<p>Values are still assigned null. I can’t figure out why this is happening. I found some related questions but couldn’t find a solution. Please help me with this.</p>
",https://stackoverflow.com/questions/54128972/content-values-are-assigned-null-even-after-putting-values-in-it,"['android', 'junit', 'android-contentprovider', 'android-contentresolver', 'content-values']",77,False,0,0
Is there any DataRowAttribute in f# unit testing?,"<p>In c# I can do this (<a href=""https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.datarowattribute?view=mstest-net-1.2.0"" rel=""nofollow noreferrer"">DataRowAttribute (c#)</a>)</p>

<pre><code>[TestMethod]
[DataRow(1,2,3)]
[DataRow(2,2,4)]
public void TestSum (int x, int y, int expected)
</code></pre>

<p>I could not find a way to do this in f#. If it does not exist, how can I create such attribute for f# unit testing ?</p>

<hr>

<p>UPDATE</p>

<p>Providing code after Jonathon Chase's suggestion with <code>[&lt;DataRow (2,4,6)&gt;]</code>.
Unfortunately the test <code>AddTest</code> is not discovered by the test runner.</p>

<pre><code>namespace FsharpTests

open System
open Microsoft.VisualStudio.TestTools.UnitTesting

[&lt;TestClass&gt;]
type TestClass () =

    [&lt;TestMethod&gt;]
    member this.TestMethodPassing() =
        Assert.IsTrue(true);

    [&lt;TestMethod&gt;]
    [&lt;DataRow (1,2,3)&gt;]
    [&lt;DataRow (2,4,6)&gt;]
     member this.AddTest(a, b, expected) = 
        Assert.AreEqual(expected, a+b); //won't be discovered by the test runner
</code></pre>
",https://stackoverflow.com/questions/58718596/is-there-any-datarowattribute-in-f-unit-testing,"['c#', 'f#']",154,True,3,1
Spring Boot - use H2 for unit testing AND for quick development (with a Spring profile),"<p>How can I use H2 both for the normal Unit Testing AND during (the first part of) development? I could start the application with a specific Spring Profile so that the application-h2.properties would be selected. </p>

<p>I have two projects: for simplicity I used exactly the same POM files. </p>

<p>When I create a simple Spring Boot Application -- immediately inserting/reading db stuff, then all works fine. </p>

<p>Important dependencies are: </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;
&lt;dependency&gt;
  &lt;groupId&gt;com.h2database&lt;/groupId&gt;
  &lt;artifactId&gt;h2&lt;/artifactId&gt;
  &lt;scope&gt;runtime&lt;/scope&gt;
  &lt;!--&lt;scope&gt;test&lt;/scope&gt;--&gt;
&lt;/dependency&gt;
</code></pre>

<p>When I have an Angular / Spring Boot application, again with the same Maven dependencies, thus with much web stuff, then I keep on getting this error: </p>

<blockquote>
  <p>IllegalStateException: Cannot load driver class: org.h2.Driver</p>
</blockquote>

<p><strong>UPDATE</strong>: When looking for the maven dependency tree, in both projects I get the dependency: </p>

<pre><code>[INFO] +- com.h2database:h2:jar:1.4.197:compile
</code></pre>

<p><strong>UPDATE</strong>: Even when I put the h2 dependency with scope 'runtime', unit testing still works with h2 AND the driver is not found</p>

<pre><code>[INFO] +- com.h2database:h2:jar:1.4.197:runtime
</code></pre>
",https://stackoverflow.com/questions/54468274/spring-boot-use-h2-for-unit-testing-and-for-quick-development-with-a-spring-p,"['spring-boot', 'maven-3', 'spring-test']",610,False,1,0
Null Pointer exception passed by test method,"<blockquote>
  <p>Method that needs to be tested - located in AnalyticsServiceImpl.java class</p>

<pre><code>public void trackSplashState(MeasurementViewEnum measurementViewEnum) {
    HashMap&lt;String, Object&gt; data = createCommonData(measurementViewEnum);
    MeasureServiceImpl.StartStatus status = mMeasureService.getLaunchStatus();
    switch (status) {
        case INSTALL:
            data.put(APP_EVENT_INSTALL, INSTALL);
            break;
        case LAUNCH:
            data.put(APP_EVENT_LAUNCH, LAUNCH);
            break;
        case UPDATE:
            data.put(APP_EVENT_UPDATE, UPDATE);
            break;
    }
    trackState(measurementViewEnum, data);
}
</code></pre>
  
  <p>Test class</p>
</blockquote>

<pre><code>@Config(constants = BuildConfig.class, sdk = TestConfig.SDK)
@RunWith(RobolectricTestRunner.class)
public class AnalyticsServiceImplTest {

    @Module(includes = TestAppModule.class, injects = AnalyticsServiceImplTest.class, overrides = true)
    static class TestModule {
    }

    @Inject
    AnalyticsServiceImpl analyticsServiceImpl;
    @Inject
    MeasureServiceImpl measureService;
    @Inject
    Context mContext;
    @Inject
    LoginService mLoginService;

    @Captor
    ArgumentCaptor&lt;HashMap&lt;String, Object&gt;&gt; data;

    @Captor
    ArgumentCaptor&lt;String[]&gt; varargs;

    private ArgumentCaptor&lt;MeasurementViewEnum&gt; enumArgumentCaptor;

    @Before
    public void setUp() throws Exception {
        Services.initialize(new AnalyticsServiceImplTest.TestModule()).inject(this);
        enumArgumentCaptor = ArgumentCaptor.forClass(MeasurementViewEnum.class);
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void trackSplashState_shouldReturnInstall_whenLaunchStatusEqualsINSTALL() throws Exception {
        analyticsServiceImpl = mock(AnalyticsServiceImpl.class);
        MeasureServiceMock measureServiceMock = new MeasureServiceMock();
        measureServiceMock.setStatus(MeasureServiceImpl.StartStatus.INSTALL);
        analyticsServiceImpl.mMeasureService = measureServiceMock;
        analyticsServiceImpl.trackSplashState(MeasurementViewEnum.SPLASH);
        verify(analyticsServiceImpl, times(1)).trackState(enumArgumentCaptor.capture(), data.capture());
    }
}
</code></pre>

<p>when I run this test case I got null pointer exception at the last line. I'm a bit new to unit testing. Can you please explain what is the mistake that I have done in this code?</p>
",https://stackoverflow.com/questions/56627469/null-pointer-exception-passed-by-test-method,"['java', 'android', 'unit-testing', 'mockito', 'android-testing']",955,True,0,1
Unit test of jQuery datatable&#39;s callback method in Angular 6,"<p>Is there anyway to test callback method of jQuery datatable in Angular 6 using karma/jasmine?</p>

<p>I want to test following method's footer callback but I can't figure out any way to do so. I am new in unit testing and cannot finding anything helpful on web. </p>

<pre><code> initializeBugIndexPageSetting() {
    let self = this;
    $('example').DataTable({
        'footerCallback': function (row, data, start, end, display) {
            const api = this.api();
            // Remove the formatting to get integer data for summation
            const intVal = function (i) {
                if (i === 'N/A') {
                    return 0;
                }
                return i * 1;
            };
            // Total over this page
            const pageInProgrssToResolved = api
                .column(14, { page: 'current' })
                .data()
                .reduce(function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0);
            const pageCount = api
                .column(5, { page: 'current' })
                .data().count();
           // Update footer           
            $(api.column(14).footer()).html((pageInProgrssToResolved / pageCount).toFixed(2));
        }
    });
}
</code></pre>

<p>Little help and guidance. </p>
",https://stackoverflow.com/questions/58319793/unit-test-of-jquery-datatables-callback-method-in-angular-6,"['jquery', 'angular', 'unit-testing', 'datatables', 'karma-jasmine']",542,True,1,1
Unit Testing a Service with Moq &amp; xUnit,"<p>Sorry, this is likely a very amateur question, but I am struggling to understand how to use Moq properly. I am quite new to unit testing as a whole, but I think I'm <em>starting</em> to get the hang of it.</p>

<p>So here's my question... I have this snippet of code below which is using a <code>TestServer</code> in Visual Studio that I using for am Unit Testing... I'm trying to mock <code>IGamesByPublisher</code> so that my test is not reliant on data in the repository (or would it be better to mock <code>GamesByPublisher</code>?... Or do I need to do both?)</p>

<pre><code>public static TestServerWithRepositoryService =&gt; new TestServer(services =&gt;
{
    services.AddScoped&lt;IGamesByPublisher, GamesByPublisher(); 
}).AddAuthorization(""fake.account"", null);


[Fact] // 200 - Response, Happy Path
public async Task GamesByPublisher_GamesByPublisherLookup_ValidRequestData_Produces200()
{

    // Arrange
    var server = ServerWithRepositoryService;

    // Act
    var response = await server.GetAsync(Uri);

    // Assert
    Assert.NotNull(response);
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);

}
</code></pre>

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

<pre><code>public interface IGamesByPublisher interface.
{
    Task&lt;IEnumerable&lt;Publisher&gt;&gt; Execute(GamesByPublisherQueryOptions options);
    }
}
</code></pre>

<p>I tried</p>

<pre><code>public static TestServerWithRepositoryService =&gt; new TestServer(services =&gt;
{
    services.AddScoped&lt;Mock&lt;IGamesByPublisher&gt;, Mock&lt;GamesByPublisher&gt;&gt;(); 
}).AddAuthorization(""fake.account"", null);
</code></pre>

<p>And then I tried</p>

<pre><code>// Not exactly what I attempted, but that code is long gone... 
var mock = new Mock&lt;IGamesByPublisher &gt;();
var foo = new GamesByPublisherQueryOptions();
mock.Setup(x =&gt; x.Execute(foo)).Returns(true);
</code></pre>

<p>I didn't really find great documentation on using Moq, just the quick start guide on GitHub, which I wasn't sure how to apply (probably my own level of experience at fault there...).</p>

<p>I am obviously missing some fundamentals on using Moq...</p>
",https://stackoverflow.com/questions/54165639/unit-testing-a-service-with-moq-xunit,"['c#', 'unit-testing', 'moq', 'xunit']",2319,True,4,1
Minimal audio (wav or mp3) file in bytes for unit testing,"<p>I want to find a minimal audio file (like the <code>testfile_gif</code> below) for unit testing. </p>

<p>I don't want to load it from the hard drive (like <a href=""https://stackoverflow.com/a/4287271/2275286"">here</a>). </p>

<p>I want the second test to perform like the first one. </p>

<pre class=""lang-py prettyprint-override""><code>import magic
from django.core.files.uploadedfile import SimpleUploadedFile


class TestFiles(TestCase):
    def test_working(self):
        # Test an Image File #
        testfile_gif = (
            b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04'
            b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02'
            b'\x02\x4c\x01\x00\x3b')
        gif_file = SimpleUploadedFile(name='image.gif', content=testfile_gif,
                                      content_type='image/gif')
        mime = magic.from_buffer(gif_file.read(1024), mime=True)
        self.assertEqual('image/gif', mime)

    def test_not_working(self):
        # Test an Audio File #
        testfile_audio = b'What should be written in here?'
        audio_file = SimpleUploadedFile(name='music.mp3',
                                        content=testfile_audio,
                                        content_type='audio/mpeg')
        mime = magic.from_buffer(audio_file.read(1024), mime=True)
        self.assertEqual('audio/mpeg', mime)
</code></pre>

<p>Preferably, I don't want to use any packages (like <code>import mock</code>). </p>

<p><strong>UPDATE</strong></p>

<p>Here is an <code>mp3</code> file with <code>audio/mpeg</code> mime:</p>

<pre><code>b'MM\x00*\x00\x00\x00\x08\x00\x03\x01\x00\x00\x03\x00\x00\x00\x01\x00\x01'
b'\x00\x00\x01\x01\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00\x01\x11\x00\x03'
b'\x00\x00\x00\x01\x00\x00\x00\x00'
</code></pre>
",https://stackoverflow.com/questions/57192090/minimal-audio-wav-or-mp3-file-in-bytes-for-unit-testing,"['python', 'django', 'unit-testing']",961,True,3,1
Unit Test Controller mocking ISession,"<p>I want to Unit Test my Controller, but I'm having issues reading values from <code>HttpContext.Session</code>.<br>
I want to mock this piece from my Controller: <code>HttpContext.Session.Get&lt;int&gt;(Foo)</code></p>

<p>With <a href=""https://stackoverflow.com/questions/41400030/mock-httpcontext-for-unit-testing-a-net-core-mvc-controller"">Mock HttpContext for unit testing a .NET core MVC controller?</a> and
<a href=""https://stackoverflow.com/questions/47203333/how-to-mock-session-object-in-asp-net-core/47203926#47203926"">How to mock Session Object in asp net core</a> I was able to come to the following solution:</p>

<p>My Test:</p>

<pre><code>public void GetFoos_AllGood_ReturnList()
{
  //Arrange
  Mock&lt;ISession&gt; sessionMock = new Mock&lt;ISession&gt;();
  var fooSessionValue = new byte[0];

  Web.Controllers.FooController fooController = new Web.Controllers.FooController();
  fooController.ControllerContext.HttpContext = new DefaultHttpContext();
  fooController.ControllerContext.HttpContext.Request.Headers[""Foo""] = 0;

  Mock&lt;IServiceCollection&gt; mock = new Mock&lt;IServiceCollection&gt;();
  mock.Object.AddSession(); // Tried this, but failed

  //Setup
  sessionMock.Setup(_ =&gt; _.Set(""Foo"", It.IsAny&lt;byte[]&gt;())).Callback&lt;string, byte[]&gt;((k, v) =&gt; fooSessionValue = v);
  sessionMock.Setup(_ =&gt; _.TryGetValue(""Foo"", out fooSessionValue)).Returns(true);
  mockWebDataManager.Setup(b =&gt; b.GetFoos(It.IsAny&lt;FooArgs&gt;())).Returns(new FooResult() { Foos = new List&lt;Foo&gt;() });

  //Act
  var result = fooController.GetFoos() as JsonResult;

  //Assert
  Assert.NotNull(result);
  Assert.Equal(200, result.StatusCode);
}
</code></pre>

<p>My Controller:</p>

<pre><code>internal virtual DataArgs CreateArgs()
{
  return new FooArgs
  {
     HttpContext.Session.Get&lt;int&gt;(Foo) // I want to Mock this value    
  };
}

[HttpGet]
public IActionResult GetFoos()
{
  FooArgs args = CreateArgs();
  ...
}
</code></pre>
",https://stackoverflow.com/questions/54217245/unit-test-controller-mocking-isession,"['c#', 'asp.net-core', 'mocking', 'moq', 'xunit']",2291,True,6,2
How to use imported graphql files in jest unit testing?,"<p>I'm trying to run unit tests with jest but I'm getting the following error:</p>

<pre><code>  ● Test suite failed to run

/apollo/queries/articles.gql:1
({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){query articles($orderBy: [OrderByClause!], $stripTags: Boolean, $maxCharacters: Int) {
                                                                                               ^^^^^^^^

SyntaxError: Unexpected identifier
</code></pre>

<p>I have installed </p>

<blockquote>
  <p><a href=""https://github.com/jagi/jest-transform-graphql"" rel=""noreferrer"">https://github.com/jagi/jest-transform-graphql</a></p>
</blockquote>

<p>It's suppose to transform GQL files.</p>

<p>My package.json (jest part)</p>

<pre><code>""jest"": {
    ""moduleFileExtensions"": [
        ""js"",
        ""json"",
        ""vue"",
        ""gql""
    ],
    ""watchman"": false,
    ""moduleNameMapper"": {
        ""^~/(.*)$"": ""&lt;rootDir&gt;/$1"",
        ""^~~/(.*)$"": ""&lt;rootDir&gt;/$1""
    },
    ""transform"": {
        ""^.+\\.js$"": ""&lt;rootDir&gt;/node_modules/babel-jest"",
        "".*\\.(vue)$"": ""&lt;rootDir&gt;/node_modules/vue-jest"",
        ""\\.(gql|graphql)$"": ""@jagi/jest-transform-graphql""
    },
    ""snapshotSerializers"": [
        ""&lt;rootDir&gt;/node_modules/jest-serializer-vue""
    ],
    ""collectCoverage"": true,
    ""collectCoverageFrom"": [
        ""&lt;rootDir&gt;/components/**/*.vue"",
        ""&lt;rootDir&gt;/pages/*.vue""
    ]
}
</code></pre>

<p>Test file</p>

<pre><code>import Index from ""../index"";

const factory = () =&gt;
    shallowMount(Index, {
        propsData: {
            label: ""click me!""
        }
    });

describe(""Index"", () =&gt; {
    test(""mounts properly"", () =&gt; {
        const wrapper = factory();
        expect(wrapper.isVueInstance()).toBeTruthy();
    });

    test(""renders properly"", () =&gt; {
        const wrapper = factory();
        expect(wrapper.html()).toMatchSnapshot();
    });
});
</code></pre>

<p>index.vue file (stripped out unimportant things)</p>

<pre><code>&lt;template&gt;
    &lt;div&gt;&lt;/div&gt;
&lt;/template&gt;

&lt;script lang=""ts""&gt;
import Vue from ""vue"";
import ArticlesQuery from ""~/apollo/queries/articles.gql"";

export default Vue.extend({
    name: ""Homepage"",
    apollo: {
        articles: {
            query: ArticlesQuery,
            variables() {
                return {
                    orderBy: [{ field: ""id"", order: ""DESC"" }],
                    stripTags: true,
                    maxCharacters: 150
                };
            },

            prefetch: true
        }
    }
});
&lt;/script&gt;
</code></pre>

<p>This is my first time doing unit testing, so I have zero knowledge on this subject.</p>
",https://stackoverflow.com/questions/59412890/how-to-use-imported-graphql-files-in-jest-unit-testing,"['unit-testing', 'vue.js', 'nuxt.js', 'vue-apollo']",1735,False,6,1
Getting error in hasClass for react jest testing,"<p>I have started jest testing for my react component and this one is my first test. my component code is </p>

<pre><code>import React from 'react';
import PropTypes from 'prop-types';
import uuidv1 from 'uuid';
import withStyles from 'react-jss';

const styles ={
    keyvaluestyle:{
        fontSize: props =&gt; props.keyvalueFontsize,
        display: props =&gt; props.keyvalueDisplay,
        verticalAlign: 'top',
        width: props =&gt; props.keyvalueWidth,
        margin: props =&gt; props.keyvalueMargin,
    }
}

const KeyValueJCpenny1 = ({

children,keyvalId,keyId,valueId, classes}) =&gt;{
    return(
        &lt;div className={classes.keyvaluestyle} data-element-type-id=""KEY_VALUE_CONTAINER"" data-element-id={keyvalId} data-key-id={keyId} data-clickable-value-id={valueId} data-component-name=""true""&gt;
            {children}
        &lt;/div&gt;
    )
}

KeyValueJCpenny1.propTypes = {
    /**
     * KeyValue label for JCpenny form 1.
     */
    children: PropTypes.node.isRequired,
    keyvalId:PropTypes.any.isRequired,
    keyId : PropTypes.any.isRequired,
    valueId : PropTypes.any.isRequired,
    keyJCpennyClass : PropTypes.string.isRequired
};
KeyValueJCpenny1.defaultProps = {
    keyId : uuidv1(),
    keyvalId : uuidv1(),
    valueId : uuidv1(),
    children : 'key of jcpenny',
    keyJCpennyClass : 'keyJCpenny1'
};


export default withStyles(styles)(KeyValueJCpenny1)
</code></pre>

<p>and my test code is</p>

<pre><code>import React from 'react';
import {configure, shallow, mount} from 'enzyme';

import KeyValueJCpenny1 from '../KeyValueJCpenny1/KeyValueJCpenny1';
import Adapter from 'enzyme-adapter-react-16';

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


describe('key value container',()=&gt;{
    it('renders container for key and value', ()=&gt;{
        const wrapper = mount(&lt;KeyValueJCpenny1  className=""keyvalue""/&gt;);
        expect(wrapper.find('.keyvaluestyle').hasClass('keyvaluestyle').to.equal(true))
    })
})
</code></pre>

<p>But I am getting error for my </p>

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

<p>can you please help me to solve this issue.Or how can I do the unit testing for my components</p>
",https://stackoverflow.com/questions/54684904/getting-error-in-hasclass-for-react-jest-testing,"['reactjs', 'unit-testing', 'jestjs', 'enzyme', 'jss']",969,True,1,1
Parameter count mismatch in unit test uwp project,"<p>I've a UWP project for which I'm doing unit testing. Here's the code</p>

<pre><code>[UITestMethod]
[DataRow(""123"", IMAdSize.Banner300x50)]
public void TestValidCreationOfIMBannerObject(string placementId, IMAdSize size) {
    IMBanner banner = new IMBanner(placementId, size);
    List&lt;IMErrorCode&gt; receivedEvents = new List&lt;IMErrorCode&gt;();

    banner.OnAdFailed += delegate (object sender, IMErrorCode e) {
        receivedEvents.Add(e);
    };

     Assert.AreEqual(receivedEvents.Count, 0);
}
</code></pre>

<p>However, when I run the above test case, I get exception as below:</p>

<p><code>System.Reflection.TargetParameterCountException: Parameter count mismatch</code></p>

<p>I am sending both the parameters that are required by the test case, cannot figure out what could possibly be wrong with above code.</p>
",https://stackoverflow.com/questions/58410805/parameter-count-mismatch-in-unit-test-uwp-project,"['c#', 'visual-studio', 'unit-testing', 'uwp', 'mstest']",232,False,1,1
Writing a JEST unit test with React,"<p>I am new to unit testing would really appreciate help.
Below is the component</p>

<pre><code>import React from 'react';
import PropTypes from ""prop-types"";
import {Textfit} from 'react-textfit'; //This will fit the text how big or small it is.

class DisplayPanel extends React.Component {
    render() { 
        return (
            &lt;Textfit className=""calculator-display""&gt;{this.props.value}&lt;/Textfit&gt;
        );
    }
}

DisplayPanel.propTypes = {
    value: PropTypes.string,
};

export default DisplayPanel
</code></pre>

<p>I want to write a test scenario in regards to the </p>

<pre><code>&lt;Textfit className=""calculator-display""&gt;{this.props.value}&lt;/Textfit&gt;
</code></pre>

<p>that checks for the components has value setup.</p>

<p>How can I do this with jest and enzyme?</p>

<p>I have tried the code for tests as below :</p>

<pre><code>import React from ""react"";
import { shallow } from ""enzyme"";
import DisplayPanel from ""../components/DisplayPanel"";
import { Textfit } from ""react-textfit"";

describe(""Display Panel"", () =&gt; {
  let wrapper;
  beforeEach(() =&gt; (wrapper = shallow(&lt;DisplayPanel/&gt;)));

  it(""should render correctly"", () =&gt; expect(wrapper).toMatchSnapshot());

  it(""should render a Textfit component"", () =&gt; {
    expect(wrapper.containsMatchingElement(&lt;Textfit /&gt;)).toEqual(true);
  });

   //what should come here
   it(""renders the value"", () =&gt; {
    //expect(wrapper.text()).toEqual('0');
  }); 
});
</code></pre>
",https://stackoverflow.com/questions/55221300/writing-a-jest-unit-test-with-react,"['reactjs', 'jestjs']",588,True,1,1
Replace a class within a Dll for unit testing,"<p>My target is to check DLL using unit testing.
I already have a project that loads the DLL and checks it using Google tests.
Now I want to replace one of the classes within the DLL with a mock and repeat the tests.</p>

<p>Is is possible? How can I do it?</p>
",https://stackoverflow.com/questions/54178558/replace-a-class-within-a-dll-for-unit-testing,"['c++', 'unit-testing', 'dll', 'mocking', 'googletest']",137,False,1,1
How to test a program in bash? (functional testing),"<p>I wrote a program in C named <code>gcd</code> that return the greatest common divisor that I call with:</p>

<pre><code>$ ./gcd 42 36
6
</code></pre>

<p>I could test these input with: </p>

<pre><code>#!/bin/bash 

[[ $(./a.out 42 36) == ""6"" ]] || exit 1
[[ $(./a.out 42 11) == ""1"" ]] || exit 1
</code></pre>

<p>Unfortunately with this I do not have any summary such as</p>

<pre><code>ran 11 tests, 0 failures, 11 successful tests
</code></pre>

<p>Is there any very simple template/framework to do such testing at program level (not unit testing)?</p>
",https://stackoverflow.com/questions/58130263/how-to-test-a-program-in-bash-functional-testing,"['linux', 'bash', 'testing', 'automated-tests']",616,True,1,1
How to get the response data in laravel unit testing,"<p>I have been trying to work with laravel unit testing.
What I wanted was how to get the response data of original.</p>

<pre><code>public function testProducts()
{
    $response=$this-&gt;call('GET','/products',['cat','all']);

    // dd($response);

    $data = $response-&gt;getData();
    //  dd($data);
}
</code></pre>

<p>When I dd in the first case it shows me HTML content. What I want to be shown is the real content with array. What should I do ?</p>
",https://stackoverflow.com/questions/59012648/how-to-get-the-response-data-in-laravel-unit-testing,"['laravel', 'unit-testing']",2206,False,1,3
"Unit Testing Controllers use Jest, NodeJS","<p>I want to check a case that certain routes are calling the correct controller use <strong>Jest</strong> specific <em>(mock or spy)</em>.</p>

<p>It is case specific for unit testing. Somebody can help me how to check it use jest. I don't need verify kind of 
expect (status code or res object) i need to check if <strong>controller</strong> have been called.
Thanks!</p>

<p>For instance:</p>

<pre><code>// todoController.js
function todoController (req, res) {
    res.send('Hello i am todo controller')
} 

// index.spec.js
const express = require('express');
const request = require('request-promise');
const todoController = require('./todoController');
jest.mock('./todoController');

const app = express();

app.get('/todo', todoController)

test('If certain routes are calling the correct controller , controller should to have been called times one.', async() =&gt; {
    await request({url: 'http://127.0.0.1/todo'})
    expect(todoController).toHaveBeenCalledTimes(1);
})
</code></pre>
",https://stackoverflow.com/questions/55463886/unit-testing-controllers-use-jest-nodejs,"['javascript', 'node.js', 'unit-testing', 'express', 'jestjs']",18970,True,9,1
Why @Value are always null when run unit-test?,"<p>I write the <code>Spring Boot</code> app and I come up with a conditional scheduling service idea.
I decided to populate all properties from <code>application-test.yml</code> via <code>@Value</code> and put it in the <code>HashMap</code>. </p>

<p>What I don't understand why during unit-testing it always <code>null</code>, independently of if it is in a <code>HashMap</code> or <code>@Value</code> populated property.</p>

<p><code>ReportService.java</code>:</p>

<pre><code>@Component
public class ReportService {

    @Value(""${reports.name}"")
    private String name;

    @Value(""${reports.enabled}"")
    private Boolean enabled;

    private final Map&lt;String, Boolean&gt; enabledReports = new HashMap&lt;String, Boolean&gt;() {{
        put(name, enabled);
    }};


    boolean isEnabled(String reportName) {
        System.out.println(enabledReports.keySet() + "" : "" + enabledReports.values());
        System.out.println(name);

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

<p><code>ReportServiceTest.java</code>:</p>

<pre><code>@SpringBootTest
@SpringBootConfiguration
@RunWith(SpringRunner.class)
@TestPropertySource(locations=""classpath:application-test.yml"")
@EnableAutoConfiguration
public class ReportServiceTest {

    private ReportService reportService = new ReportService();

    @Test
    public void test() {
        reportService.isEnabled(""reportName"");
    }

} 
</code></pre>

<p><code>application-test.yml</code>:</p>

<pre><code>reports:
  name: ""report""
  enabled: false
</code></pre>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/58363653/why-value-are-always-null-when-run-unit-test,"['java', 'spring-boot', 'unit-testing']",2568,True,2,2
Angular console.log in tests printing in VS Code,"<p>I'm using Jasmine/Karma for unit testing my Angular application, and I'm using Visual Studio Code as the IDE.</p>

<p>When I do <code>console.log</code> in the test, I'm not able to find where the output is printed.</p>

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

<pre><code>it('verify filter changes', () =&gt; {

    let nameInput = fixture.debugElement.query(By.css('#name-input'));
    console.log(nameInput);
    nameInput.nativeElement.value = 'dummyName';
    nameInput.nativeElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    expect(component.name).toBe('dummyName');
  });
</code></pre>

<p>My karma.conf.json:</p>

<pre><code>process.env.CHROME_BIN = require('puppeteer').executablePath();

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: {
      jasmine: {
        random: true,
      },
      clearContext: false, // leave Jasmine Spec Runner output visible in browser
      captureConsole: true,
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, 'coverage'),
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true,
    },

    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_DEBUG,
    autoWatch: true,
    browsers: ['Chrome'],
    //browsers: ['ChromeHeadless'],
    browserConsoleLogOptions: {
      level: 'log',
      format: '%b %T: %m',
      terminal: true
    }
  });
};
</code></pre>

<p>Where is the output of console.log printed in Visual Studio Code? </p>
",https://stackoverflow.com/questions/58370563/angular-console-log-in-tests-printing-in-vs-code,"['angular', 'visual-studio-code', 'jasmine', 'karma-jasmine']",1364,False,2,0
How to unit test a method that changes reference of a private field,"<p>I'm writing unit tests for a class in a game of life application. I have a method which creates a 2d array of bools and then changes the reference of a field (another 2d array of bools) to the new array.</p>

<p>I have trouble unit testing the class. I'm trying to test if the output is correct, however, there is no way for me to access the array after it has changed the reference.</p>

<p>I have found a workaround which is, instead of creating a new array and assigning new reference, I'm looping re-populating the original field with the contents of the new array, but that is adding an unnecessary computation just for the sake of unit testing which does not sound like a good idea.</p>

<p>How can I test the Evolve method for the correct behaviour?</p>

<p><strong>Board.cs</strong></p>

<pre><code>public class Board : IBoard
{
    private bool[,] _board;
    private int _noRows;
    private int _noColumns;
    private IConsole _console;

    public Board(IConsole console)
    {
        _console = console;
    }

    public void Set(bool[,] board)
    {
        _board = board;
        _noRows = board.GetLength(0);
        _noColumns = board.GetLength(1);
    }

    private IEnumerable&lt;bool&gt; GetNeighbours(int boardTileY, int boardTileX)
    {
        var neighbours = new List&lt;bool&gt;();

        for (var i = boardTileY - 1; i &lt;= boardTileY + 1; i++)
        {
            for (var j = boardTileX - 1; j &lt;= boardTileX + 1; j++)
            {
                if (i == boardTileY &amp;&amp; j == boardTileX)
                {
                    continue;
                }
                //if neighbour out of bounds add as dead
                else if (i &gt;= _noRows || i &lt; 0 || j &gt;= _noColumns || j &lt; 0)
                {
                    neighbours.Add(false);
                }
                else
                {
                    neighbours.Add(_board[i, j]);
                }
            }
        }

        return neighbours;
    }

    public void Evolve()
    {
        var boardAfter = new bool[_noRows, _noColumns];

        for (var i = 0; i &lt; _noRows; i++)
        {
            for (var j = 0; j &lt; _noColumns; j++)
            {
                var aliveCounter = GetNeighbours(i, j).Count(n =&gt; n);

                switch (_board[i, j])
                {
                    // if dead tile has exactly 3 neighbours that are alive it comes to life
                    case false when aliveCounter == 3:
                        boardAfter[i, j] = true;
                        break;

                    // if alive tile has 0 or 1 neighbours (is lonely) or more than 3 neighbours (overcrowded) it dies
                    case true when (aliveCounter &lt; 2 || aliveCounter &gt; 3):
                        boardAfter[i, j] = false;
                        break;

                    default:
                        boardAfter[i, j] = _board[i, j];
                        break;
                }
            }
        }

        _board = boardAfter;
    }       
}
</code></pre>

<p><strong>BoardTests.cs</strong></p>

<pre><code>[TestFixture]
public class BoardTests
{
    private Mock&lt;IConsole&gt; _fakeConsole;

    [SetUp]
    public void SetUp()
    {
        _fakeConsole = new Mock&lt;IConsole&gt;();
    }

    [Test]
    public void Evolve_Once_ReturnCorrectOutput()
    {
        //Arrange
        var board = new Board(_fakeConsole.Object);

        var boardArray = new[,] {
            {false, false, false, false, false},
            {false, false, false, false, false},
            {false, true , true , true , false},
            {false, false, false, false, false},
            {false, false, false, false, false}
        };

        //Act
        board.Set(boardArray);
        board.Evolve();

        //Assert
        Assert.That(boardArray[1, 1].Equals(false));
        Assert.That(boardArray[1, 2].Equals(true));
        Assert.That(boardArray[1, 3].Equals(false));
        Assert.That(boardArray[2, 1].Equals(false));
        Assert.That(boardArray[2, 2].Equals(true));
        Assert.That(boardArray[2, 3].Equals(false));
        Assert.That(boardArray[3, 1].Equals(false));
        Assert.That(boardArray[3, 2].Equals(true));
        Assert.That(boardArray[3, 3].Equals(false));            
    }

    [Test]
    public void Evolve_Twice_ReturnCorrectOutput()
    {          
        //Arrange
        var board = new Board(_fakeConsole.Object);

        var boardArray = new[,] {
            {false, false, false, false, false},
            {false, false, false, false, false},
            {false, true , true , true , false},
            {false, false, false, false, false},
            {false, false, false, false, false}
        };

        //Act
        board.Set(boardArray);
        board.Evolve();
        board.Evolve();

        //Assert
        Assert.That(boardArray[1, 1].Equals(false));
        Assert.That(boardArray[1, 2].Equals(false));
        Assert.That(boardArray[1, 3].Equals(false));
        Assert.That(boardArray[2, 1].Equals(true));
        Assert.That(boardArray[2, 2].Equals(true));
        Assert.That(boardArray[2, 3].Equals(true));
        Assert.That(boardArray[3, 1].Equals(false));
        Assert.That(boardArray[3, 2].Equals(false));
        Assert.That(boardArray[3, 3].Equals(false));
    }        
}    
</code></pre>
",https://stackoverflow.com/questions/55774683/how-to-unit-test-a-method-that-changes-reference-of-a-private-field,"['c#', '.net', 'unit-testing']",633,True,0,4
Testing Controller method that is not linked to any routes,"<p>So I am giving a sample of my controller and web.php file.</p>

<pre><code>controller
{
   public function add() 
   {
      //Method called via web.php
   }
   public function multiply() 
   {
      //how to access this while testing
   }
}
</code></pre>

<p>web.php</p>

<pre><code>route::get('/add','controller@add');
</code></pre>

<p>And now I want to perform unit testing</p>

<p>case1: add <code>$response = $this-&gt;get(route('add'));</code> Now it will send a get request when <code>/add</code> is accessed and controller method <code>add</code> will be accessed. And then I can use various assertions to check its functionality.</p>

<p>case2: <code>multiply</code> Here there isn't any route specified, so it wont be able to access controller method.</p>

<p>How can I test my multiply method in such a case</p>

<p><strong><em>UPDATED ANSWER</em></strong></p>

<p>So from all the answers and comments, i have understood that in Laravel</p>

<ol>
<li>Unit Testing -  Create a controller instance and then call the method that you want to test.</li>
<li>Feature testing - In this mode of testing, we will be calling the route and testing whether correct method has been hit and it is working as desired. </li>
</ol>

<p>Thank You!!</p>
",https://stackoverflow.com/questions/55241099/testing-controller-method-that-is-not-linked-to-any-routes,"['php', 'laravel', 'unit-testing', 'web', 'testing']",357,True,0,1
Angular how not to import all the dependencies in component unit tests each time,"<p>I have a working app(when run <code>ng serve</code> all works fine)
however, when I run  <code>ng test</code> compiler complains about not recognizing directives/properties such as <code>Can't bind to 'formControl' since it isn't a known property of 'input'.</code> When I add </p>

<pre><code>TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        SomeComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
        .. other dependencies
    ]
</code></pre>

<p>what is the smart way not to add all the imports that I have already added in the <code>app.module</code> ?</p>

<p>UPDATE: I am talking about unit testing a component.</p>
",https://stackoverflow.com/questions/55121873/angular-how-not-to-import-all-the-dependencies-in-component-unit-tests-each-time,"['angular', 'unit-testing', 'angular-cli', 'angular7']",1845,True,2,3
How to properly unit test a suffix tree algorithm?,"<p>I'm working on an implementation of Ukkonen's linear time suffix tree construction algorithm, and planning to implement improvements suggested by e.g. Kurtz and NJ Larsson (for example edge links instead of suffix links).</p>

<p>While testing, I experienced mixed green and red lights based on the specific strings I tested, and had similar experiences with a few algorithms I found online. Which made me wonder:</p>

<ul>
<li><p>Are there any known, specifically built (preferably simple/short) strings for unit-testing suffix trees to ensure the algorithm works precisely in all branching scenarios?</p></li>
<li><p>Furthermore, are there any good methods to separate the testing of the tree building algorithm from the testing of the traversal/lookup algorithm?</p></li>
</ul>

<p>I know this question doesn't have a single specific correct answer, but I think it could serve as a good reference point for people working on similar algorithms.</p>

<p>My current unit-testing approach is quite primitive (C# with NUnit):</p>

<pre class=""lang-cs prettyprint-override""><code>[TestCase]
public void Contains_Simple_ShouldReturnTrue()
{
    var s = ""bananasbanananananananananabananas"";
    var st = SuffixTree.Build(s);

    var t1 = s.Substring(0, 10);
    Assert.IsTrue(st.Contains(t1));
}

// ... Other simple test cases


[TestCase]
// This test fails, but it's not particularly helpful for bugfixing
public void Contains_DynamicBarrage_OnLongString_ShouldReturnTrue()
{
    const int   CYCLES = 200,
                MAXLEN = 200;

    var s = ""olbafuynhfcxzqhnebecxjrfwfttw""; // Shortened for sanity
    var st = SuffixTree.Build(s);
    var r = new Random();

    for (int i = 0; i &lt; CYCLES; i++)
    {
        var pos = r.Next(0, s.Length - 2);
        var len = r.Next(1, Math.Min(s.Length - pos, MAXLEN));

        Assert.IsTrue(st.Contains(s.Substring(pos, len)));
    }
}
</code></pre>
",https://stackoverflow.com/questions/55726359/how-to-properly-unit-test-a-suffix-tree-algorithm,"['algorithm', 'unit-testing', 'suffix-tree']",458,False,3,0
Directory phpunit wrong?,"<p>i would like to create a separate folder for phpunit. I want to have one folder for all related to unit testing. unit_test is the name. But i get a message: </p>

<pre><code>PS C:\Users\dh_netsense.no\utv\NSS-Hyttetjenester&gt; unit_test/vendor/bin/phpunit
PHPUnit 8.4.3 by Sebastian Bergmann and contributors.

Usage:
  phpunit [options] UnitTest [UnitTest.php]
  phpunit [options] &lt;directory&gt;
</code></pre>

<p>How do i configure phpunit so I can run it in this path? I do not see the tests being run now.</p>
",https://stackoverflow.com/questions/59136291/directory-phpunit-wrong,"['php', 'terminal', 'phpunit']",217,True,2,1
Error: Expected spy MovieService.getWatchListedMovies to have been called. angular Unit Testing,"<ul>
<li><p>A component file called <strong>watchlist</strong> which dependent on
<strong>MovieService(service)</strong> to fetch movie.</p></li>
<li><p>calling ngOnInit() will invoke MovieService.getWatchlistedMovies()</p></li>
<li><p>the component code is given below,</p></li>
</ul>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>export class WatchlistComponent implements OnInit {

  movies: Array&lt;Movie&gt;;
  movieType:string;
  
  constructor(private movieService:MovieService,private route:ActivatedRoute) { 

    this.movies=[];
    this.route.data.subscribe((data)=&gt;{
      this.movieType=data.movieType
    });
   
  }

  ngOnInit() {

    this.movieService.getWatchListedMovies()
    .subscribe((movies)=&gt;{
     this.movies.push(...movies);
       },
       this.handleErrors()
       );

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

<ul>
<li><p>Unit testing on the <strong>component(watchlist)</strong> using <em>jasmine.spy</em> object on <strong>movieService(Service)</strong>  </p></li>
<li><p>watchlist.spec.ts file code as follow,</p></li>
</ul>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe('WatchlistComponent', () =&gt; {
  let component: WatchlistComponent;
  let fixture: ComponentFixture&lt;WatchlistComponent&gt;;
  let movieServiceFake:jasmine.SpyObj&lt;MovieService&gt;;
  let movieService;
  let stubTmdbMovies: Movie[];
  beforeEach(async(() =&gt; {
    movieServiceFake = jasmine.createSpyObj('MovieService', ['getWatchListedMovies']);


    TestBed.configureTestingModule({
      imports: [MovieModule,
        RouterTestingModule,
        HttpClientTestingModule],
      providers: [{ provide: MovieService, useValue: movieServiceFake }]
    })
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(WatchlistComponent);
    component = fixture.componentInstance;
    movieServiceFake = TestBed.get(MovieService);
  });

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

  it('should call ngOnInIt', () =&gt; {
    //Arrange
    let spyOnComponent = spyOn(component, 'ngOnInit');
    movieServiceFake.getWatchListedMovies.and.callFake(() =&gt; { return of(stubTmdbMovies) });
    //Act
    component.ngOnInit();
    //Assert
    expect(spyOnComponent).toHaveBeenCalled();
    expect(movieServiceFake.getWatchListedMovies).toHaveBeenCalled();//error line
  });
});</code></pre>
</div>
</div>
</p>

<p>`<strong>MovieModule</strong> where I have registered <strong>watchlist</strong> and <strong>MovieService.</strong> as below</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>@NgModule({
  imports: [
    CommonModule,
    HttpClientModule,
    MovieRouterModule,
    MatCardModule,
    MatButtonModule,
    MatSnackBarModule,
    FormsModule,
    ReactiveFormsModule,
    MatInputModule
      ],
  declarations: [ContainerComponent,TmdbContainerComponent,TumbnailComponent, WatchlistComponent, MovieDetailsComponent],
  
  exports:[
    MovieRouterModule,
    TumbnailComponent,
    ContainerComponent,
    TmdbContainerComponent
  ],
  providers:[
    MovieService
  ]
})
export class MovieModule { }</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/54843056/error-expected-spy-movieservice-getwatchlistedmovies-to-have-been-called-angul,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'spy']",84,False,0,1
Angular Unit Testing with karma and jamis,"<p>I have set up my Angularjs application for unit testing with Karma and Jasmin. but when I try to run my test cases with <code>karma start</code> I am getting the error The controller with the name <code>Myctrl</code> is not registered.</p>

<p>My application structure is as follows</p>

<pre><code>project-folder
  - app
    - components
      - controllers
        - account
          - signInController.js
          - SignUpController.js
  - app.modules.js
  - app.routes.js
  - test
</code></pre>

<p>This is my app.modules.js</p>

<pre><code>let app = angular.module( 'app', [
  'app.config', 'templates', 'ngAnimate', 'ngAria', 'ngCookies', 'ngMessages', 'ngResource', 'ngSanitize',
  'ngTouch', 'ui.router', 'ui.bootstrap', 'ui.utils', 'ui.load', 'ui.jq', 'oc.lazyLoad','angular-cache',
  'ngToast', 'ngFileUpload', 'ngFileSaver', 'angularMoment', 'angulartics', 'angulartics.google.analytics',
  'ngMessages', 'ng.httpLoader'
]);
</code></pre>

<p>And the karma.config.js file</p>

<pre><code>module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'browserify'],

    // list of files / patterns to load in the browser
    files: [
      'dist/libs/jquery/jquery.js',
      'dist/libs/angular/angular.js',
      'dist/libs/angular-ui-router/angular-ui-router.js',
      'dist/libs/angular-sanitize/angular-sanitize.js',
      'dist/libs/angular-mocks/angular-mocks.js',
      'dist/libs/angular-bootstrap/ui-bootstrap-tpls.js',
      'app/app.modules.js',
      'app/app.routes.js',
      'app/config.lazyload.js',
      'app/components/controllers/account/*.js',
      'test/**/*spec.js',
      ],
      . 
      .
</code></pre>

<pre><code>describe('Myctrl Test', function() {

  describe('Myctrl', function() {
    var vm;

    beforeEach(inject(function( ) {
      angular.module('app')
    }));

    beforeEach(inject(function(_$rootScope_, $controller) {
      var scope = _$rootScope_.$new();
      vm = $controller('Myctrl', {$scope: scope});
    }));

    it('test controller', function() {
      expect(vm.title).toBe(null);
    });

  });

});
</code></pre>

<pre><code>app.controller( 'Myctrl', ['$scope', '$state', 'backendApi', 'ngToast', 'access_token', 'FileUploader', 'keys',
function( $scope, $state, backendApi, ngToast, access_token, FileUploader, keys ) {

  $scope.title = ""Hello"";


}])
</code></pre>
",https://stackoverflow.com/questions/54568235/angular-unit-testing-with-karma-and-jamis,"['angularjs', 'karma-jasmine']",148,False,0,1
How do I mock JoinRow for unit testing,"<p>I have looked at code base of jdbi v3 but still can't figure out a way to mock <code>Stream&lt;JoinRow&gt;</code> returned by Dao class.</p>

<p>Constructor is package protected which is only invoked from <code>JoinRowMapper</code>'s specialize function which itself needs <code>StatementContext</code>. </p>

<p>Is there any way to mock <code>JoinRow</code> object for unit testing purposes?</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/54369553/how-do-i-mock-joinrow-for-unit-testing,"['unit-testing', 'jdbi']",391,False,0,1
"When using MockMvc to test the controller, a parameter passing error occurred","<p>I am using MockMvc to test the controller. Regarding parameter import, I encountered a type mismatch problem. I tried all the json styles.But nothing works</p>

<p>This is my controller class::</p>

<pre><code>package app.dnatask.controller;

import ......;

@Slf4j
@RestController
@RequestMapping(value = ""/API/scanresultconfigure"")

public class ScanResultConfigureController extends BaseController {
    @RequestMapping(value = ""/queryScanResultList/{taskId}/{externalname}"", method = RequestMethod.POST)
    public IBaseResult queryscanResultList(final HttpServletRequest request, @PathVariable final String taskId, @PathVariable final String externalname, @RequestBody Map map) throws Exception {
        return runController(new IControllRunner() {
            public void run(IOutResult or, CheckResult cr) throws Exception {
                ......
            }
        }
    }
}
</code></pre>

<p>This is my test class::</p>

<pre><code>package app.dnatask.controller;

import ......

@WebAppConfiguration
@ContextConfiguration(classes = {ScanResultConfigureController.class})
@ComponentScan(
        includeFilters = {
                @ComponentScan.Filter(type = FilterType.CUSTOM,
                        value = {ScanResultConfigureController.class})
        },
        useDefaultFilters = false,
        lazyInit = true
)

public class ScanResultConfigureControllerTest extends AbstractTestNGSpringContextTests {
    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;

    @BeforeMethod
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).dispatchOptions(true).build();
        System.out.println(""UT starting............."");
    }

    @AfterMethod
    public void am() {
        System.out.println(""UT ending............."");
    }

    @Test
    public void testQueryscanResultList() throws Exception {
        Map&lt;String, String&gt; testMap = new HashMap&lt;&gt;();
        testMap.put(""key1"", ""value1"");
        testMap.put(""key2"", ""value2"");
        String requestJson = JSONObject.toJSONString(testMap);
        mockMvc.perform(
                post(""/API/scanresultconfigure/queryScanResultList/001/abc"")
                        .contentType(MediaType.APPLICATION_JSON)
                        .param(""map"", requestJson)
        )
                .andExpect(status().isOk())
                .andDo(print());
    }
}
</code></pre>

<p>Error message::</p>

<pre><code>org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported

java.lang.AssertionError: Status expected:&lt;200&gt; but was:&lt;415&gt;
</code></pre>

<p>This is a project implemented by springmvc framework, I use TestNG for unit testing.</p>
",https://stackoverflow.com/questions/59407734/when-using-mockmvc-to-test-the-controller-a-parameter-passing-error-occurred,"['spring', 'unit-testing', 'spring-mvc', 'testng', 'mockmvc']",460,True,-1,1
How to mock Spring Boot Session and SecurityContext for testing purpose,"<p>It is Spring Boot project. It uses SecurityContext.</p>

<p>Most of its Rest controller and service, depend on the role of its logged in user, for validation purpose. So during testing, I need a user to login. </p>

<p>Please inform me unit testing code example, for Spring boot, that involve login user process.</p>

<pre><code>@RunWith(PowerMockRunner.class)
@PrepareForTest({SecurityContextHolder.class,AuthenticationManager.class,UserRepository.class,UserCreationRequestRepository.class,        PasswordEncoder.class,AuthorityRepository.class,CacheManager.class,POMasterCompanyRepository.class,BranchRepository.class})
public class BOAuthControllerTest {

@Autowired
private WebApplicationContext context;

@Mock
private AuthenticationManager authenticationManager;

@Mock
private UserRepository userRepository;
@Mock
private UserCreationRequestRepository userCreationRequestRepository;
@Mock
private PasswordEncoder passwordEncoder;
@Mock
private AuthorityRepository authorityRepository;
@Mock
private CacheManager cacheManager;
@Mock
private POMasterCompanyRepository poMasterCompanyRepository;
@Mock
private BranchRepository branchRepository;
private UserService userService;

private MockMvc mockMvc;

@Before
public void setup() {

    userService = new UserService(userRepository, passwordEncoder, authorityRepository, cacheManager, userCreationRequestRepository,
            poMasterCompanyRepository,branchRepository);

    UsernamePasswordAuthenticationToken authenticationToken =
            new UsernamePasswordAuthenticationToken(""admin"",""admin"");
    Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    SecurityContext securityContext = new SecurityContextImpl();
    securityContext.setAuthentication(authentication);

            System.out.println(authenticationToken==null?""null"":""not null"");
    System.out.println(authenticationManager==null?""null"":""not null"");
    System.out.println(authentication==null?""null"":""not null"");
    System.out.println(SecurityContextHolder.getContext()==null?""null"":""not null"");
    System.out.println(SecurityContextHolder.getContext().getAuthentication()==null?""null"":""not null"");
    System.out.println(SecurityContextHolder.getContext().getAuthentication().getName());
    System.out.println(securityContext.getAuthentication().getName());

    PowerMockito.mockStatic(SecurityContextHolder.class);
    when(SecurityContextHolder.getContext()).thenReturn(securityContext);

    System.out.println(userService.getUserWithAuthorities().isPresent());
}

@Test
public void loginAvailableForAll() throws Exception {

    System.out.println(userService.getUserWithAuthorities().isPresent());

}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/58605876/how-to-mock-spring-boot-session-and-securitycontext-for-testing-purpose,"['spring-boot', 'unit-testing', 'junit', 'mockito']",5133,True,0,2
Fizz Buzz question with extra difficulty layer,"<p>I am trying to solve the Fizz Buzz question with an extra layer.</p>

<p>This is what I have so far. All this works fine but I need one more extra condition. </p>

<p>It's JS Unit testing</p>

<blockquote>
  <p>For any other input (valid or otherwise) return a string representation of the input</p>
</blockquote>

<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>printFizzBuzz = function(input) {

  // Your code goes here
  for (var i = 1; i &lt;= 20; i++) {

    if (i % 3 === 0 &amp;&amp; i % 5 === 0) {
      console.log(""FizzBuzz"");
    } else if (i % 3 === 0) {
      console.log(""FizzBuzz"");
    } else if (i % 5 === 0) {
      console.log(""Buzz"");
    } else {
      console.log(i);
    }
  }
};</code></pre>
</div>
</div>
</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/59078245/fizz-buzz-question-with-extra-difficulty-layer,"['javascript', 'fizzbuzz']",160,True,-2,3
Django channels ProtocolTypeRouter unit testing with pytest,"<p>I am checking out channels for the next project. But I am stuck at unit testing the basics. I guess it must be something I keep overlooking. </p>

<p><strong>Versions:</strong></p>

<ul>
<li>channels==2.1.7</li>
<li>django==2.1.3</li>
</ul>

<p><strong>routing.py</strong></p>

<pre><code>from channels.routing import ProtocolTypeRouter #, URLRouter
from Phoenix.ProtocolTestConsumer import ProtocolTestConsumer

application = ProtocolTypeRouter({
    # Empty for now (http-&gt;django views is added by default)

    ""test"": ProtocolTestConsumer,
})
</code></pre>

<p><strong>ProtocolTestConsumer.py</strong></p>

<pre><code>import logging
logging.basicConfig(level=logging.DEBUG)

from django.conf import settings
from channels.consumer import SyncConsumer

class ProtocolTestConsumer(SyncConsumer):
    def test_a(self, event):
        logging.debug(""consumer test_a {}"".format(event))

    def test_b(self, event):
        logging.debug(""consumer test_b {}"".format(event))

    def test_c(self, event):
        logging.debug(""consumer test_c {}"".format(event))
</code></pre>

<p><strong>test_ProtocolTestConsumer.py</strong></p>

<pre><code>import pytest
import logging

from Phoenix.ProtocolTestConsumer import ProtocolTestConsumer
from channels.testing import ApplicationCommunicator

communicator = ApplicationCommunicator(ProtocolTestConsumer, {""type"": ""test""})

@pytest.mark.asyncio
async def test_call_a():
    await communicator.send_input(
        {""type"": ""test.a"",
         ""text"": ""Blue""})
    logging.debug(""pytest is printing this"")
</code></pre>

<p><strong>DJANGO_SETTINGS_MODULE=web.settings pytest -s -v</strong></p>

<pre><code>== test session starts ==
platform linux -- Python 3.7.1, pytest-4.1.1, py-1.7.0, pluggy-0.8.1 -- /home/user/src/web/Phoenix/venv-phoenix/bin/python3.7
cachedir: .pytest_cache
Django settings: web.settings (from environment variable)
rootdir: /home/user/src/web/Phoenix/web/Phoenix, inifile:
plugins: django-3.4.5, asyncio-0.10.0
collected 1 item                                                                                        

test_ProtocolTestConsumer.py::test_call_a DEBUG:asyncio:Using selector: EpollSelector
DEBUG:root:pytest is printing this
PASSED

== 1 passed in 0.24 seconds ==
</code></pre>

<p>I expected to see more console output from the Consumer.</p>
",https://stackoverflow.com/questions/54477038/django-channels-protocoltyperouter-unit-testing-with-pytest,['django-channels'],1009,False,0,1
Do unit testing using protractor having good scope in future?,"<p>I was working in Blackbox automation testing earlier, recently I am working on E2E unit testing using type script and Protractor framework. I just want to know the scope of my current work compared to my previous one. This ll help me to learn and work more enthusiastically. </p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/57001344/do-unit-testing-using-protractor-having-good-scope-in-future,"['typescript', 'unit-testing', 'protractor']",63,True,0,1
What is the difference between mocking and simulating virtual services?,"<p>I have been looking at <a href=""http://codesv.io/"" rel=""nofollow noreferrer"">CodeSV</a>, a free Java library which enables to set up virtual services in unit testing. I do not quite understand the difference between that and mocking. According to CodeSV's authors their library can achieve more than mocking. What would be the advantages of one approach against another?</p>
",https://stackoverflow.com/questions/57511538/what-is-the-difference-between-mocking-and-simulating-virtual-services,"['java', 'unit-testing', 'testing', 'mocking', 'integration-testing']",52,True,1,1
Unit testing the views in laravel?,"<p>How to do unit testing of the controller's function which returns a view. Here, is my controller function </p>

<pre><code>public function index(Request $request)
{
   $data = Data::all();
   return view('index',[
       'data' =&gt; $data
   ]);
}
</code></pre>

<p>Here is test code</p>

<pre><code>public function testIndex()
{
   $response = $this-&gt;withoutMiddleware();

   $response = $this-&gt;get('/user');

   $response-&gt;assertSuccessful();
}
</code></pre>

<p>I tried this</p>

<pre><code>public function testIndex()
{
   $response = $this-&gt;withoutMiddleware();

   $response = $this-&gt;get('/user');

   $response = $this-&gt;assertContains('data', $response-&gt;content());

   $response-&gt;assertSuccessful();
}
</code></pre>

<p>which shows error of</p>

<blockquote>
  <p>Error: Call to a member function assertSuccessful() on null</p>
</blockquote>

<p>Any idea, How to write a test case for my index controller function?</p>
",https://stackoverflow.com/questions/55509287/unit-testing-the-views-in-laravel,"['php', 'laravel', 'phpunit']",4118,True,0,3
React alphanumeric validation issue,"<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>export default (value = """") =&gt; {
  let error = null;
  const stripped = value.replace(/^[0-9a-zA-Z]*$/, """");

  if (stripped.length !== value.length) {
    error = ""Input Contains Bad Characters"";
  }

  return { error, value };
};

// This below code for varying the formats

import validator from ""../../validators/alpha-numeric.js"";

describe(""Alphanumeric Only Validator For Input Validation"", () =&gt; {
  test(""Only Characters Passed"", () =&gt; {
    expect(validator(""Abcd"")).toMatchObject({
      error: null,
      value: ""Abcd""
    });
  });

  test(""Alphanumeric Characters With Space"", () =&gt; {
    expect(validator(""Abc d"")).toMatchObject({
      error: ""Input Contains Bad Characters"",
      value: ""Abc d""
    });
  });

  test(""Alphanumeric Characters With Numbers"", () =&gt; {
    expect(validator(""Ab123d"")).toMatchObject({
      error: null,
      value: ""Ab123D""
    });
  });

  test(""Alphanumeric Characters With Special Characters"", () =&gt; {
    expect(validator(""Abcd@"")).toMatchObject({
      error: ""Input Contains Bad Characters"",
      value: ""Abcd@""
    });
  });
});</code></pre>
</div>
</div>
</p>

<p>This is full code i am using in React, please guide me the perfect result how can i verify alphanumeric.</p>

<p>This is the requirement even the below describe code i have written that is for unit testing, but if i am running ""yarn unit-test"" so i am getting error. </p>
",https://stackoverflow.com/questions/54127056/react-alphanumeric-validation-issue,"['javascript', 'reactjs', 'user-interface']",10153,True,-2,2
How to add Unit Tests for Apple Watch in Xcode?,"<p>1.Does watchOS (as of watchOS 4.3) currently support unit or UI testing? There is no UI Test Case Class file and Unit Test Case Class file in the watchOS file.</p>

<p>2.If watchOS supports unit testing, can we place the Unit Test Case file of watchOS in the iOS Unit Test Case file?</p>
",https://stackoverflow.com/questions/54338305/how-to-add-unit-tests-for-apple-watch-in-xcode,"['unit-testing', 'watchkit', 'watchos']",733,False,3,1
Unit Test in Python assertIsNotNone,"<p>I am completely new to unit testing and cannot see why i am getting an 'AssertionError: unexpectedly None'</p>

<p>my test in written as</p>

<pre><code>import unittest
from Extraction import Core

class testDict(unittest.TestCase):

    def test_dict_populate(self):
        result=Core(file='input.txt')
        self.assertIsNotNone(result)
</code></pre>

<p>from the Extraction file is my Core function</p>

<pre><code>def Core(file):
    with open(file) as f:
        for line in f:
        # populate auction item
            if 'SELL' in line:
            auctionsplit = (line.strip().split('|'))
            new_item = auction(auctionsplit)
            dct[new_item] = []

            elif 'BID' in line:
                tokens = (line.strip().split('|'))
                new_bid = bid(tokens)
                bid_item_id = new_bid.item
                key_to_update = find_item(bid_item_id, dct.keys())
                dct[key_to_update].append(new_bid)
            else:
                pass
</code></pre>

<p>The input file is stored in the same project as the test and Core so am abit confused tbh</p>
",https://stackoverflow.com/questions/59176868/unit-test-in-python-assertisnotnone,['python-3.x'],1617,True,0,1
What is instrumentation in nyc istanbul?,"<p>What is instumentation used in nyc? </p>

<blockquote>
  <p>nyc's instrument command can be used to instrument source files outside of the context of your unit-tests:</p>
</blockquote>

<p>I assume it will do coverage outside unit-testing. I tried it with</p>

<pre><code>nyc instrument src coverage/instrument
</code></pre>

<p>then run the application and tries hitting an endpoint</p>

<pre><code>npm start
</code></pre>

<p>but when I do above, it doesn't generate a file in <code>nyc_output</code> thus can't report anything. </p>

<p>Do I have to finish the <code>nyc instrument</code> command? how to do so? </p>
",https://stackoverflow.com/questions/58075076/what-is-instrumentation-in-nyc-istanbul,"['istanbul', 'nyc']",4530,True,17,3
"When testing an Angular app, how can I get Jest to recognize CanvasJS?","<p>I am using <a href=""https://canvasjs.com/"" rel=""nofollow noreferrer"">CanvasJS</a> to display charts in an Angular app. The charts display properly when running my app, so I know CanvasJS is a part of the project and is working. However, Jest can't find CanvasJS when unit testing, here's the error:</p>

<pre><code>import Charts from '../core/charts';
       ^^^^^^

SyntaxError: Unexpected identifier

  1 | import { Component, OnInit } from '@angular/core';
&gt; 2 | import * as CanvasJS from 'canvasjs';
    | ^
  3 | 
</code></pre>

<p>What could be causing this, and what is the workaround?</p>
",https://stackoverflow.com/questions/59416633/when-testing-an-angular-app-how-can-i-get-jest-to-recognize-canvasjs,"['angular', 'typescript', 'unit-testing', 'jestjs', 'canvasjs']",61,False,1,0
AuditingEntityListener junit cannot find context,"<p>I have an entity and would like to implement Audit and AuditHistory, both works but while unit testing Application context is null.</p>

<p><strong>The Entity</strong></p>

<pre><code>@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@EntityListeners(UserListener.class)
public class User extends BaseModel&lt;String&gt; {
    @Column
    private String username;
    @Column
    private String password;

    @Transient
    private String passwordConfirm;

    @ManyToMany
    private Set&lt;Role&gt; roles;
}
</code></pre>

<p><strong>UserListener</strong></p>

<pre><code>public class UserListener {

    @PrePersist
    public void prePersist(User target) {
        perform(target, INSERTED);
    }

    @PreUpdate
    public void preUpdate(User target) {
        perform(target, UPDATED);
    }

    @PreRemove
    public void preRemove(User target) {
        perform(target, DELETED);
    }

    @Transactional(MANDATORY)
    void perform(User target, Action action) {
        EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
        if(target.isActive()){
            entityManager.persist(new UserAuditHistory(target, action));
        }else{
            entityManager.persist(new UserAuditHistory(target, DELETED));
        }

    }
}
</code></pre>

<p><strong>UserAuditHistory</strong></p>

<pre><code>@Entity
@EntityListeners(AuditingEntityListener.class)
public class UserAuditHistory {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    @JoinColumn(name = ""user_id"", foreignKey = @ForeignKey(name = ""FK_user_history""))
    private User user;

    @CreatedBy
    private String modifiedBy;

    @CreatedDate
    @Temporal(TIMESTAMP)
    private Date modifiedDate;

    @Enumerated(STRING)
    private Action action;

    public UserAuditHistory() {
    }

    public UserAuditHistory(User user, Action action) {
        this.user = user;
        this.action = action;
    }
}
</code></pre>

<p><strong>BeanUtil for getting and setting context</strong></p>

<pre><code>@Service
public class BeanUtil implements ApplicationContextAware {
    private static ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    public static &lt;T&gt; T getBean(Class&lt;T&gt; beanClass) {
        return context.getBean(beanClass);
    }
}
</code></pre>

<p>Now the Junit where I get null pointer exception on the context from the above BeanUtil class in getBean() method. </p>

<pre><code>@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryTest{

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private UserRepository repository;

    @Test
    public void whenFindAll_theReturnListSize(){

        entityManager.persist(new User(""jk"", ""password"", ""password2"", null));
        assertEquals(repository.findAll().size(), 1);
    }
}
</code></pre>
",https://stackoverflow.com/questions/54912438/auditingentitylistener-junit-cannot-find-context,"['java', 'spring', 'hibernate', 'jpa', 'spring-data-jpa']",285,True,1,2
How to check whether for assistance of element based on element name in angular unit testing?,"<p>I have a side navbar as follows,</p>

<pre><code>      &lt;kendo-sidenav *ngFor=""let nav of navOptions"" [title]=""nav.title""&gt;
      &lt;kendo-sidenav&gt;
</code></pre>

<p>My ts,</p>

<pre><code>       ""navOptions"" = [{'title':'profile'},{'title':'friends'}];
</code></pre>

<p>My spec,</p>

<pre><code>     it('should render title in a h1 tag', async(() =&gt; {
        const fixture = TestBed.createComponent(AppComponent);
        fixture.detectChanges();
        const compiled = fixture.debugElement.nativeElement;
       expect(compiled.querySelector('kendo-sidenav')).toBeTruthy()
      }));
</code></pre>

<p>But here I want to check 2 conditions,</p>

<p>1) Check side navbar is displayed if navOptions is not empty</p>

<p>2_ Check side navbar is not displayed if navOptions is empty.</p>

<p>I am new to unit testing,can anyone please suggest me help.Thanks.</p>
",https://stackoverflow.com/questions/57583290/how-to-check-whether-for-assistance-of-element-based-on-element-name-in-angular,"['javascript', 'angular', 'typescript', 'jasmine', 'angular-unit-test']",20,False,1,0
Mockito returning null value for Future,"<p>I am unit-testing a <code>controller</code> in a <code>play-framework</code> application. </p>

<p>The <code>controller</code> uses a repository and I am mocking the repository as follows</p>

<pre><code>val mockUserRepository = mock(classOf[UsersRepository])
  when(mockUserRepository.findOne(userKeys)).thenReturn(Future{Some(user)})
  when(mockUserRepository.save(user)).thenReturn(Future(Some(user)))
</code></pre>

<p>Then I run the following test. In the test, <code>controller.signupUser(request)</code> calls the <code>findOne</code> method of the repository as follows</p>

<pre><code>val findUserFuture: Future[Option[User]] = userRepo.findOne(userKeys) 

        println(""user future is "",findUserFuture)
        findUserFuture.flatMap { (userOption: Option[User]) =&gt; //this crashes because findUserFuture is null)
</code></pre>

<p>But <code>findOne</code> returns a <code>null</code> instead of a dummy <code>Future{user}</code></p>

<pre><code>""User signup request with body"" should {
    ""return OK and user profile if the signup profile data is correct"" in {


      val jsonBody = Json.parse(
        """"""
          {
             ""external-profile"":{
                ""email"":""test@test.com"",
                ""firstname"":""fn"",
                ""lastname"":""ln"",
                ""password"":""aA1!1111""
             }
          }
        """""")
      //val jsonBody = Json.toJson(signupInfo)
      val request: Request[AnyContentAsJson] = FakeRequest(""POST"", ""ws/users/signup"",Headers((""someH""-&gt;""someV"")),new AnyContentAsJson(jsonBody))
      println(""sending sign up request "", request)
      //request.body = signupInfo
      val response: Future[Result] = controller.signupUser(request)
      val responseBodyAsJsValue:JsValue = contentAsJson(response)
      println(""received response of sign up "", responseBodyAsJsValue)

    }
  }
</code></pre>

<p>error
received profile </p>

<pre><code>UserProfile(None,ExternalUserProfile(test@test.com,fn,ln,Some(aA1!1111)))
checking if the user with the following details exists LoginInfo(credentials,test@test.com)
returning id 116 for name test@test.com
(user future is ,null)

java.lang.NullPointerException was thrown.
java.lang.NullPointerException
    at controllers.UserController.$anonfun$signupUser$1(UserController.scala:116)
</code></pre>

<p>What I might be doing wrong?</p>
",https://stackoverflow.com/questions/54996297/mockito-returning-null-value-for-future,"['mockito', 'playframework-2.6']",880,True,1,1
moq unit testing in c# web api,"<p>I am tring to test one web api method in asp.net core 2.</p>

<p>Web api</p>

<p>method:</p>

<pre class=""lang-cs prettyprint-override""><code>public IActionResult Delete(int id)
{
    try
    {
        var success = sportsService.DeleteSport(id);

        if (!success)
        {
            return new NotFoundResult();
        }
        return new OkResult();
    }
    catch (Exception e)
    {
        return new StatusCodeResult(400);
    }
}
</code></pre>

<p>Unit testing part: </p>

<pre class=""lang-cs prettyprint-override""><code>private Mock&lt;ISportsService&gt; mockService;

[SetUp]
public void Setup()
{
    mockService.SetupSequence(x =&gt; x.DeleteSport(It.IsAny&lt;int&gt;())).
        Returns(true). // OkResult();
        Returns(false). // NotFoundResult()
        Throws(new Exception()); //Exception
}
</code></pre>

<p>Test method looks like this. What I am not clear about with this method is, what the right approach to testing the method is?</p>

<pre class=""lang-cs prettyprint-override""><code>[Test]
public void TestStrategyControllerWithDelete()
{
    var result = controller.Delete(STRAT_ID);
    var okResult = result as ObjectResult;
    Assert.AreEqual(HttpStatusCode.NotFound, okResult.StatusCode);
    Assert.AreEqual(HttpStatusCode.OK, okResult.StatusCode);
    Assert.AreEqual(400, okResult.StatusCode);
}
</code></pre>

<p>and i am okresult as null ! <strong>and not able to get okResult.StatusCode</strong></p>
",https://stackoverflow.com/questions/58992517/moq-unit-testing-in-c-web-api,"['c#', 'unit-testing', 'moq']",3823,True,2,3
Why is findAll() not returning all objects in model?,"<p>Im working on mocking DB because im unit testing API. For mocking i use sequelize-mock library and for models i use sequelize. When im calling GET request the function getAll() returns only first element in that array.</p>

<p>My mock model:</p>

<pre><code>const assetmeter = (sequelize) =&gt; {
  const AssetMeter = sequelize.define('assetmeter', {
    id: 1,
    assetId: 1,
    sequence: null,
    meterName: 'BAD',
    measureUnit: 'km',
    meterType: 'CHARACTERISTIC', 
    description: 'test description', 
    active: true,
  },{
    id: 2,
    assetId: 2,
    sequence: null,
    meterName: 'TEST',
    measureUnit: 'TEST',
    meterType: 'TEST', 
    description: 'TEST', 
    active: true,
  });

  return AssetMeter;
}

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

<p>Get all function:</p>

<pre><code>import { AssetMeter } from '../../models';
import paginate from '../../utils/paginate';

export default async (req, res) =&gt; {
  let assetMeters = [];
  try {
    assetMeters = await AssetMeter.findAndCountAll({
      limit: req.pagination.limit, 
      offset: req.pagination.offset
    });
    console.log(assetMeters);
  } catch (err) {
    console.log(err);
    return res.status(500).send({ error: 'Internal server error' });
  }
  const links = paginate(req.protocol, req.hostname, req.baseUrl, req.pagination, assetMeters.count);
  if (links) {
    res.set('Link', links);
  }
  return res.set('X-Total-Count', assetMeters.count).send(assetMeters.rows);
}; 
</code></pre>

<p>The output im expecting is that it would return two objects in array.
Current result:</p>

<pre><code>[ { id: 1,
    assetId: 1,
    sequence: null,
    meterName: 'BAD',
    measureUnit: 'km',
    meterType: 'CHARACTERISTIC',
    description: 'test description',
    active: true,
    createdAt: '2019-03-29T07:33:02.812Z',
    updatedAt: '2019-03-29T07:33:02.812Z' } ]
</code></pre>
",https://stackoverflow.com/questions/55412760/why-is-findall-not-returning-all-objects-in-model,"['node.js', 'mocha.js', 'sequelize.js']",1399,True,4,1
Nullinjectorerror: no provider for FormBuilder (I&#39;m importing ReactiveFormsModule),"<p>So I'm trying to write a really basic test for a component. I just want to make sure that the form that I'm creating using FormBuilder is an instance of FormGroup, but I'm consistently getting a NullInjectorerror: No provider for FormBuilder, and I've tried pretty much everything. I made sure I was importing the ReactiveFormsModule.</p>

<p>hours-calculator.component.ts</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-hours-calculator',
  templateUrl: './hours-calculator.component.html',
  styleUrls: ['./hours-calculator.component.scss']
})
export class HoursCalculatorComponent implements OnInit {

  constructor(private formBuilder: FormBuilder) { }

  form: FormGroup;
  
  ngOnInit() {
      this.form = this.formBuilder.group({
         control1: this.formBuilder.control('')
      });
  }
}</code></pre>
</div>
</div>
</p>

<p>hours-calculator.spec.ts</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormGroup, ReactiveFormsModule, FormsModule, FormBuilder } from '@angular/forms';
import { HoursCalculatorComponent } from './hours-calculator.component';

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        FormsModule,
        ReactiveFormsModule
      ],
      declarations: [ HoursCalculatorComponent ]
    }).compileComponents();
  }));

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

  it('should create a form using formbuilder', () =&gt; {
    expect(component.form instanceof FormGroup).toBeTruthy();
  });
}</code></pre>
</div>
</div>
</p>

<p>Am I just missing something extremely obvious? I'm really tearing my hair out over this one. I'm really new to unit testing angular components, so explain it to me like I'm 5 :) For the record, I'm using angular 7.</p>

<p>Full error message:</p>

<pre><code>          StaticInjectorError(Platform: core)[HoursCalculatorComponent -&gt; FormBuilder]: 
            NullInjectorError: No provider for FormBuilder!
            at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3228:1)
            at resolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3473:1)
            at tryResolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3417:1)
            at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3314:1)
            at resolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3473:1)
            at tryResolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3417:1)
            at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:3314:1)
            at resolveNgModuleDep (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:19784:1)
            at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:20473:1)
            at resolveDep (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:20844:1)
</code></pre>

<p>package.json</p>

<pre><code>    {
      ""name"": ""babysitter-app"",
      ""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"": {
        ""@angular/animations"": ""~7.1.0"",
        ""@angular/common"": ""~7.1.0"",
        ""@angular/compiler"": ""~7.1.0"",
        ""@angular/core"": ""~7.1.0"",
        ""@angular/forms"": ""~7.1.0"",
        ""@angular/platform-browser"": ""~7.1.0"",
        ""@angular/platform-browser-dynamic"": ""~7.1.0"",
        ""@angular/router"": ""~7.1.0"",
        ""core-js"": ""^2.5.4"",
        ""rxjs"": ""~6.3.3"",
        ""tslib"": ""^1.9.0"",
        ""zone.js"": ""~0.8.26""
      },
      ""devDependencies"": {
        ""@angular-devkit/build-angular"": ""~0.11.0"",
        ""@angular/cli"": ""~7.1.3"",
        ""@angular/compiler-cli"": ""~7.1.0"",
        ""@angular/language-service"": ""~7.1.0"",
        ""@types/node"": ""~8.9.4"",
        ""@types/jasmine"": ""~2.8.8"",
        ""@types/jasminewd2"": ""~2.0.3"",
        ""codelyzer"": ""~4.5.0"",
        ""jasmine-core"": ""~2.99.1"",
        ""jasmine-spec-reporter"": ""~4.2.1"",
        ""karma"": ""~3.1.1"",
        ""karma-chrome-launcher"": ""~2.2.0"",
        ""karma-coverage-istanbul-reporter"": ""~2.0.1"",
        ""karma-jasmine"": ""~1.1.2"",
        ""karma-jasmine-html-reporter"": ""^0.2.2"",
        ""protractor"": ""~5.4.0"",
        ""ts-node"": ""~7.0.0"",
        ""tslint"": ""~5.11.0"",
        ""typescript"": ""~3.1.6""
      }
    }
</code></pre>
",https://stackoverflow.com/questions/54976493/nullinjectorerror-no-provider-for-formbuilder-im-importing-reactiveformsmodul,"['angular', 'unit-testing', 'testing', 'jasmine', 'karma-runner']",49089,True,35,5
Vue unit tests - cannot read property &#39;t&#39; of undefined,"<p>I'm using jest to run vue unit tests to check the output of individual components. The component uses vuetify.</p>

<p>I create an instance of vue to mount the component: </p>

<pre><code>import myComponent from './MyComponent.vue';
import VueRouter from 'vue-router';
import Vuetify from 'vuetify';

describe('Component', () =&gt; {
    let wrapper;

    const router = new VueRouter({
        base: '/ui/',
        routes: [
            {
                name: 'myRoute',
                path: '/route-to-my-component',
                component: myComponent
            },
        ]
    });

    beforeEach(() =&gt; {
        const localVue = createLocalVue();
        localVue.use(VueRouter);
        localVue.use(Vuetify);

        wrapper = mount(myComponent, {
            localVue: localVue,
            router
        });
    });



    it('contains a container', () =&gt; {
      expect(wrapper.contains('v-container')).toBe(true);
    })
});
</code></pre>

<p>I expect this test to pass, but instead I'm getting <code>TypeError: Cannot read property 't' of undefined</code>.</p>

<p>For reference, I was following <a href=""https://fernandobasso.github.io/javascript/unit-testing-vue-vuetify-with-jest-and-vue-test-utils.html"" rel=""nofollow noreferrer"">https://fernandobasso.github.io/javascript/unit-testing-vue-vuetify-with-jest-and-vue-test-utils.html</a>.</p>
",https://stackoverflow.com/questions/57663237/vue-unit-tests-cannot-read-property-t-of-undefined,"['vue.js', 'vuetify.js', 'vue-test-utils']",7630,True,4,1
Testing Keystone and Mongoose with Jest,"<p>I am implementing unit testing in a project with <a href=""https://keystonejs.com/"" rel=""nofollow noreferrer"">Keystone</a> but it always throws an error at testing:</p>

<pre><code>an all test suites.
/Project/node_modules/mongodb/lib/mongo_client.js:433
      throw err
      ^

TypeError: require(...) is not a function
at /Project/node_modules/keystone/lib/core/start.js:64:44
at /Project/node_modules/async/dist/async.js:3880:24
at eachOfArrayLike (/Project/node_modules/async/dist/async.js:1069:9)
at eachOf (/Project/node_modules/async/dist/async.js:1117:5)
at _parallel (/Project/node_modules/async/dist/async.js:3879:5)
at Object.parallelLimit [as parallel] (/Project/node_modules/async/dist/async.js:3962:5)
at /Project/node_modules/keystone/lib/core/start.js:60:9
at connected (/Project/node_modules/keystone/lib/core/openDatabaseConnection.js:78:5)
at NativeConnection.&lt;anonymous&gt; (/Project/node_modules/keystone/lib/core/openDatabaseConnection.js:85:4)
at Object.onceWrapper (events.js:273:13)
at NativeConnection.emit (events.js:182:13)
at /Project/node_modules/mongoose/lib/connection.js:860:13
at connectCallback (/Project/node_modules/mongodb/lib/mongo_client.js:527:5)
at /Project/node_modules/mongodb/lib/mongo_client.js:430:11
at process._tickCallback (internal/process/next_tick.js:61:11)
npm ERR! Test failed.  See above for more details.
</code></pre>

<p>I already tried using ""import { init, start, mongoose } from 'keystone';"" instead, and using jest async() and await. I run too ""jest --clearCache"". Jest version: ""jest"": ""^24.3.1""</p>

<p>My .babelrc:</p>

<pre><code>{
""presets"": [
    [""@babel/preset-env"",
        {""targets"": {
            ""node"": ""current""
        }}
    ], 
    ""@babel/preset-react""
]    
}
</code></pre>

<p>test.js:</p>

<pre><code>const Keystone = require('keystone');

beforeAll( done =&gt; {
    Keystone.init({
        'name': 'Keystone CMS',
        'cookie secret': 'My_Biscuit',
    });
    Keystone.start();
    done();
})

describe('Test Keystone CMS own features', () =&gt; {
    test('Keystone connects to MongoDB', (done) =&gt; {
        expect(Keystone.mongoose.connections._listening).toBeTruthy;
        done();
    });
});
</code></pre>

<p>I will then expand it to test mongoose </p>
",https://stackoverflow.com/questions/55206795/testing-keystone-and-mongoose-with-jest,"['node.js', 'mongoose', 'jestjs', 'keystonejs']",247,False,2,1
Cannot add assemblies to .Net Core application in Visual Studio 2019,"<p>When I try to add a missing assembly to my project (for unit testing specifically) I noticed that the Assemblies tab is missing in the ""Add Reference"" dialog , see:</p>

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

<p>Is this a bug or a expected behavior? If it's expected how we are supposed to add the missing assemblies.</p>

<p>Note that I already tried through Nuget package manager and still didn't work.</p>
",https://stackoverflow.com/questions/56772625/cannot-add-assemblies-to-net-core-application-in-visual-studio-2019,"['.net-core', 'assemblies', 'visual-studio-2019']",12755,True,7,2
How to mock a class in my exception class?,"<p>I have to access ApplicationContext in MyException class </p>

<pre><code>public class MyException extends Exception {
    public MyException(Map&lt;String, Map&lt;String,String&gt;&gt; errorObj) throws IOException {
            ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
            Environment env = applicationContext.getEnvironment();
            ...
    }
}
</code></pre>

<p>And this service throw it.</p>

<pre><code> @Service
 public class MyServiceImpl implements MyService {

    @Override
    public Response myFunction() {

          throw new MyException(errorObj);
       ...
    }
 }
</code></pre>

<p>Edit this is ApplicationContextProvider</p>

<pre><code>public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext(){
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}
</code></pre>

<p>when I run unittest I got NullPointerException on ApplicationContext. I want to mock ApplicationContext How to do this? </p>

<p>I found this error only unit testing but when I run with spring-boot:run it work fine</p>
",https://stackoverflow.com/questions/58316005/how-to-mock-a-class-in-my-exception-class,"['spring-boot', 'unit-testing', 'mockito']",441,False,0,1
PHP testing simple object constructor,"<p>I had little dispute with my coworkers about unit testing simple class.
I have to test simple class like that.</p>

<pre class=""lang-php prettyprint-override""><code>class Person
{
  /** @var string */
  protected $name

  public function __construct(string $name)
  {
    $this-&gt;name = $name;
  }

  public function __toString(): string
  {
    return (string) $this-&gt;name;
  }
}
</code></pre>

<p>We both agree on testing toString method.
But in my opinion, first we have to test creating this object as such:</p>

<pre class=""lang-php prettyprint-override""><code>public function testObjectCreation()
{
  $testSubject = new Person('name');

  $this-&gt;assertInstanceOf(Person::class, $testSubject);
}
</code></pre>

<p>My question is: 
Is there any sense in testing this case?</p>
",https://stackoverflow.com/questions/54367739/php-testing-simple-object-constructor,"['php', 'unit-testing', 'phpunit']",182,False,0,0
Show error of two strings are equal in unit testing,"<p>I have created a small Laravel project and I am applying unit testing on my project. When I fill wrong credentials in function, it doesn't redirect to the login page and shows error on terminal saying Failed asserting that two strings are equal. Here is my code...</p>

<pre><code>$credentials = [
    'email' =&gt; 'test@gmail.com',
    'password' =&gt; 'wrongcode'
];

$this-&gt;post('/login', $credentials)-&gt;assertRedirect('/login');
</code></pre>

<p>But when i change <code>assertRedirect('/login')</code> to <code>assertRedirect('/')</code> , it works fine</p>

<pre><code>$credentials = [
    'email' =&gt; 'test1234@gmail.com',
    'password' =&gt; '98756412'
];

$this-&gt;post('/login', $credentials)-&gt;assertRedirect('/');
</code></pre>
",https://stackoverflow.com/questions/55468883/show-error-of-two-strings-are-equal-in-unit-testing,"['php', 'laravel', 'unit-testing']",752,True,2,2
How To Create Temporary Directory in Scala Unit Tests,"<p><strong>In scala how can a unit test create a temporary directory to use as part of the testing?</strong></p>

<p>I am trying to unit test a class which depends on a directory</p>

<pre><code>class UsesDirectory(directory : java.io.File) {
  ...
}
</code></pre>

<p>I'm looking for something of the form:</p>

<pre><code>class UsesDirectorySpec extends FlatSpec {
  val tempDir = ??? //missing piece

  val usesDirectory = UsesDirectory(tempDir)

  ""UsesDirectory"" should {
    ...
  }
}
</code></pre>

<p>Also, any comments/suggestions on appropriately cleaning up the resource after the unit testing is completed would be helpful.</p>

<p>Thank you in advance for your consideration and response.</p>
",https://stackoverflow.com/questions/54946535/how-to-create-temporary-directory-in-scala-unit-tests,"['scala', 'unit-testing', 'filesystems', 'scalatest']",8024,True,10,3
How to test F# option types with xUnit,"<p>I want to unit test this bit of code using xUnit in F#. How do I handle the options?</p>

<p>From Scott Wlaschin's book: Domain Modeling Made Functional</p>

<pre><code>type UnitQuantity = private UnitQuantity of int
// ^ private constructor

// define a module with the same name as the type
module UnitQuantity =
    /// Define a ""smart constructor"" for UnitQuantity
    /// int -&gt; Result&lt;UnitQuantity,string&gt;
    let create qty =
        if qty &lt; 1 then
            // failure
            Error ""UnitQuantity can not be negative""
        else if qty &gt; 1000 then
            // failure
            Error ""UnitQuantity can not be more than 1000""
        else
            // success -- construct the return value
            Ok (UnitQuantity qty)
</code></pre>

<p>Test:</p>

<pre><code>let ``Check UnitQuantity.create is one`` () =

    // ARRANGE
    let expected = 1

    // ACT
    //let unitQtyResult = UnitQuantity.create 1
    match UnitQuantity.create 1 with
    | Error msg -&gt; 0
        //printfn ""Failure, Message is %s"" msg
    | Ok x -&gt; 0
       // let innerValue = UnitQuantity.value actual

    // ASSERT
    //Assert.Equal(expected,actual)
</code></pre>

<p>I know the <code>ACT</code> is all wrong, that is where I am hung up. I do not understand F# options nor xUnit.net nor unit testing enough yet to Assert on the actual value from the function.</p>
",https://stackoverflow.com/questions/57491375/how-to-test-f-option-types-with-xunit,"['f#', 'xunit.net']",1106,True,7,3
Mocking Axios with Jest in React - mock function not being called,"<p>I am trying to use Jest for unit testing. Part of the testing is to mock Axios, but for some reason it is not being called.</p>

<p>Here is my <code>/__mocks__/axios.js</code> code:</p>

<pre><code>export default {
  post: jest.fn(() =&gt; Promise.resolve({})),
};
</code></pre>

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

<pre><code>import mockAxios from 'axios';
import { registerUser } from '../../actions/auth';
import user from '../fixtures/user';


describe('Register User', () =&gt; {
  test('Should call register API and redirect to login', async () =&gt; {
    const historyMock = { push: jest.fn() };

    mockAxios.post.mockImplementationOnce(() =&gt; Promise.resolve());

    await registerUser(user, historyMock);

    expect(mockAxios.post).toHaveBeenCalledTimes(1);

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

<p>Also here is the registerUser code:</p>

<pre><code>export const registerUser = (user, history) =&gt; dispatch =&gt; axios
  .post('/users/register', user)
  .then(() =&gt; history.push('/login'))
  .catch((err) =&gt; {
    dispatch(handleError(err));
  });
</code></pre>

<p>But for some reason I continue to get the error:</p>

<pre><code>Register User › Should call register API and redirect to login

    expect(jest.fn()).toHaveBeenCalledTimes(1)

    Expected mock function to have been called one time, but it was called zero times.

      35 |     await registerUser(user, historyMock);
      36 | 
    &gt; 37 |     expect(mockAxios.post).toHaveBeenCalledTimes(1);
</code></pre>

<p>Any ideas why the mock is not working?</p>
",https://stackoverflow.com/questions/54930968/mocking-axios-with-jest-in-react-mock-function-not-being-called,"['reactjs', 'jestjs']",11004,True,3,2
Matchers for cats EitherT and effects,"<p>I'm new in cats and functional programming and I'm struggling  with unit testing functional data types like <code>EitherT</code>. Having example code:</p>

<pre><code>class Library[F[_]]() {
    def create(book: Book)(implicit M: Monad[F]): EitherT[F, BookAlreadyExistsError, Book] = ...
}
</code></pre>

<p>I'd like to test it using Spec2 but I don't know how to do it properly. Tried something like this but it does not work:</p>

<pre><code>  val library = Library[IO]()

  test(""create book"") {

    val book = Book(""Title 1"", 2016, ""author 1"")
    (for (
      resultBook &lt;- library.create(book)
    ) yield resultBook shouldEqual ???
    ).unsafeRunSync()

  }
</code></pre>

<p>I'd like to have very simple assertions like this:</p>

<pre><code>   resultBook shouldEqual Right(Book(""Title 1"", 2016, ""author 1""))
   // or
   resultBook shouldEqual Left(BookAlreadyExistsError)
</code></pre>
",https://stackoverflow.com/questions/59234283/matchers-for-cats-eithert-and-effects,"['scala', 'functional-programming', 'scala-cats', 'specs2', 'cats-effect']",643,True,2,1
Skip execution of a line using Mockito,"<p>I am using mockito for unit testing and I want to skip a line. </p>

<pre><code>// method I am testing
public String doSomeTask(String src, String dst) {
    // some code

    utils.createLink(src,dst);

    // some more code
} 


// utils class
public void createLink(String src, String dst) {
    // do something
    Path realSrc = ""/tmp/"" + src;
    Files.createSymbolicLink(realSrc, dst);

    // do something
}


// Test class

@Mock
private Utils utils;

@Test
public void testDoSomeTask() {
    // this does not seem to work, it is still executing the createLink method
    doNothing.when(utils).createLink(anyString(), anyString());
    myClass.doSomeTask(anyString(), anyString());
}
</code></pre>

<p>Now, <code>createLink</code> is a void method and its failing during my testing with exception reason <code>AccessDenied</code> to create a directory. </p>

<p>I want to skip the line <code>utils.createLink(src,dst);</code> and continue with next lines. Is there a way I can tell Mockito to do this ?</p>
",https://stackoverflow.com/questions/55542010/skip-execution-of-a-line-using-mockito,"['java', 'unit-testing', 'junit', 'mockito']",11072,True,2,2
Android Alert Dialog unit testing,"<blockquote>
  <p>AlertFragment</p>
</blockquote>

<pre><code>public class AlertFragment extends DialogFragment {

    private static final String TAG = ""DeliveryRequestErrMsg"";

    private String mMsg;
    private String mTitle;
    private AlertDismissListener mAlertDismissListener;
    private FragmentManager mFragmentManager;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        return new AlertDialog
                .Builder(getActivity())
                .setTitle(mTitle)
                .setMessage(mMsg)
                .setNegativeButton(R.string.cart_btn_dismiss, null)
                .create();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        mAlertDismissListener.onDismiss(this);
    }

    public AlertFragment title(String title) {
        this.mTitle = title;
        return this;
    }

    public AlertFragment msg(String mMsg) {
        this.mMsg = mMsg;
        return this;
    }

    public AlertFragment fragmentMgr(FragmentManager fragmentManager) {
        mFragmentManager = fragmentManager;
        return this;
    }

    public AlertFragment onDismiss(AlertDismissListener alertDismissListener) {
        this.mAlertDismissListener = alertDismissListener;
        return this;
    }

    public void show() {
        try {
            super.show(mFragmentManager, getClass().getName());
        } catch (Exception e) {
            Log.e(TAG, ""show: "", e);
        }
    }

    interface AlertDismissListener {
        void onDismiss(AlertFragment fragment);
    }

    public String getMsg() {
        return mMsg;
    }

    public String getTitle() {
        return mTitle;
    }
}
</code></pre>

<blockquote>
  <p>AlertManagerImpl</p>
</blockquote>

<pre><code>public class AlertManagerImpl implements AlertManager {

        private List&lt;AlertFragment&gt; mListOfMessageShown = new ArrayList&lt;&gt;();

        @Override
        public boolean isMessageDisplayed(@Nonnull String message) {
            boolean isAlreadyShown = false;
            for (AlertFragment deliveryRequestErrMsgFragment : mListOfMessageShown) {
                if (message.equals(deliveryRequestErrMsgFragment.getMsg())) {
                    isAlreadyShown = true;
                    break;
                }
            }
            return isAlreadyShown;
        }

        @Override
        public void showAlertMessage(@Nullable String title, String msg, FragmentActivity activity) {
            AlertFragment deliveryRequestErrMsgFragment = new AlertFragment()
                    .title(title)
                    .msg(msg)
                    .onDismiss(fragment -&gt; mListOfMessageShown.remove(fragment))
                    .fragmentMgr(activity.getSupportFragmentManager());
            deliveryRequestErrMsgFragment.show();
            mListOfMessageShown.add(deliveryRequestErrMsgFragment);
        }

        @Override
        public void showAlertMessageWithoutDuplicates(@Nullable String title, String msg, FragmentActivity activity) {
            if (!isMessageDisplayed(msg)) {
                showAlertMessage(title, msg, activity);
            }
        }
    }
</code></pre>

<blockquote>
  <p>AlertManager</p>
</blockquote>

<pre><code>    public interface AlertManager {

    /**
     * This method allow user to show multiple same alert messages
     *
     * @param title Title that need to show
     * @param msg Message that need to show
     * @param activity
     */
    void showAlertMessage(@Nullable String title, String msg, FragmentActivity activity);

    /**
     * This method does not allow user to show multiple same alert messages
     *
     * @param title Title that need to show
     * @param msg Message that need to show
     * @param activity
     */
    void showAlertMessageWithoutDuplicates(@Nullable String title, String msg, FragmentActivity activity);

    /**
     * Verify if there is already a similar message currently displayed to the user. Returns true if a similar message is already showing, else returns false
     *
     * @param message The message that we want to compare with the currently displayed alert messages
     * @return
     */
    boolean isMessageDisplayed(@Nonnull String message);

}
</code></pre>

<blockquote>
  <p>AlertManagerImplTest</p>
</blockquote>

<pre><code>    @Config(constants = BuildConfig.class, sdk = TestConfig.SDK)
@RunWith(RobolectricTestRunner.class)
public class AlertManagerImplTest {
    @Inject
    AlertManager alertManager;
    @Inject
    Context mContext;
    MainActivity mainActivity;

    @Module(
            includes = TestAppModule.class,
            injects = AlertManagerImplTest.class,
            overrides = true
    )
    static class TestModule {
    }

    @Before
    public void setUp() {
        mContext = RuntimeEnvironment.application;
        FirebaseApp.initializeApp(mContext);
        Services.initialize(new AlertManagerImplTest.TestModule()).inject(this);
        mainActivity = Robolectric.buildActivity(MainActivity.class).create().get();
    }

    @Test
    public void checkMessageDisplayed_WhenSameMessage_ShouldReturnTrue() throws Exception {
        alertManager.showAlertMessage(""Title1"", ""Message1"", mainActivity);
        Assert.assertTrue(alertManager.isMessageDisplayed(""Message1""));
    }

    @Test
    public void checkMessageDisplayed_WhenDifferentMessage_ShouldReturnFalse() throws Exception {
        alertManager.showAlertMessage(""Title1"", ""Message1"", mainActivity);
        Assert.assertFalse(alertManager.isMessageDisplayed(""Message2""));
    }
}
</code></pre>

<blockquote>
  <p>Here I have created AlertManager to use in my project. So implementation is working properly. But now I'm facing a challenge that I need to write some Unit testing for this implementation. Especially I need to test the following scenarios </p>
</blockquote>

<ul>
<li>show one alert -> Verify if it is showing</li>
<li>try to show one alert with a ""dead"" activity -> Verify that no crash occurs</li>
<li>show 10 alerts -> Verify that all 10 are shown (to verify that we can trust the method in most of the cases)</li>
</ul>

<blockquote>
  <p>I created a test class to just test one function of AlertManagerImpl
  class. I need to actually verify alert is showing. I read some post
  and someone suggested that Robolectric is good for this but I not good
  at Unit testing if you can suggest any other solution also welcome. If someone help with this to me much appreciated.</p>
</blockquote>
",https://stackoverflow.com/questions/59171478/android-alert-dialog-unit-testing,"['android', 'unit-testing', 'robolectric']",1850,False,1,1
Getting error while running ng test command,"<p>I am trying to run test cases for angular project.I am new to unit testing of UI. Whenever I try to run ""ng test"" command, getting following error.</p>

<pre><code>10 01 2019 18:13:33.754:INFO [Chrome 71.0.3578 (Windows 7.0.0)]: Connected on so
cket 3bR__mAXbLbWIyMdAAAA with id 62613448
Chrome 71.0.3578 (Windows 7.0.0) ERROR
  Uncaught ReferenceError: jQuery is not defined
  at http://localhost:9876/_karma_webpack_/scripts.bundle.js:56

Chrome 71.0.3578 (Windows 7.0.0) ERROR
  Uncaught ReferenceError: jQuery is not defined
  at http://localhost:9876/_karma_webpack_/scripts.bundle.js:56
Chrome 71.0.3578 (Windows 7.0.0) ERROR
  Uncaught ReferenceError: jQuery is not defined
  at http://localhost:9876/_karma_webpack_/scripts.bundle.js:56

</code></pre>
https://stackoverflow.com/questions/46701835/cant-find-jquery-when-running-ng-test-command

<p>I followed above answer. Still getting same error of jquery is not defined.</p>
",https://stackoverflow.com/questions/54129266/getting-error-while-running-ng-test-command,"['angular', 'unit-testing', 'user-interface', 'karma-jasmine']",397,False,0,0
Unit testing Scala using mockito,"<p>I'm very much new to doing unit testing in Scala using Mockito. I'm getting an error in the <code>thenReturn</code> statement.</p>

<pre><code>it should ""read null when readFromPostgresTarget is called with some 
         random driver"" in {

Given(""a null query is sent as query"")
       val query = """"
       val pgObject = mock[PersistenceObject]
       val postgresPersistenceObject = 
       mock[PostgressPersistenceServiceTrait]
       val mockDF = mock[DataFrame]

When(""it is passed to readFromPostgresTarget"")
        when(postgresPersistenceObject.readFromPostgresTarget(any[String],mock[Spark 
                                      Session], pgObject)).thenReturn(mockDF)

        assert(postgresPersistenceObject.readFromPostgresTarget(query, 
                             sparkSession, pgObject) === any[DataFrame])

Then(""a null value should be returned"")
        verify(postgresPersistenceObject, times(1))
}
</code></pre>

<p>I'm getting the error-</p>

<pre><code>overloaded method value thenReturn with alternatives:
  (x$1: Unit,x$2: Unit*)org.mockito.stubbing.OngoingStubbing[Unit] &lt;and&gt;
  (x$1: Unit)org.mockito.stubbing.OngoingStubbing[Unit]
 cannot be applied to (org.apache.spark.sql.DataFrame)
                .thenReturn(mockDF)
</code></pre>

<p>I tried making the <code>mockDF</code> in <code>thenReturn(mockDF)</code> to <code>thenReturn(any[DatafRame])</code>, it's not fixing the issue.</p>

<p>I tried passing a <code>SparkSession</code> instead of the mock it isn't working.</p>

<p>I can't figure what mistake I'm doing.</p>
",https://stackoverflow.com/questions/58698160/unit-testing-scala-using-mockito,"['scala', 'mockito']",356,False,0,1
Swift XCTAssertEqual (Float) fails when directly passing getter,"<p>I've run into a very strange bug with Xcode's Swift unit testing. When I store the <code>Float</code> value of a getter, it works, but when I pass the same getter to <code>XCTAssertEqual</code>, it fails because the value the XCT function receives is <code>0</code>, not the actual calculated value (in this case <code>800</code>).</p>

<p>Has anyone run into this?</p>

<pre><code>// Rectangle.width = get { return left - right }

let w = metrics.imageDestinationRectangle.width
let h = metrics.imageDestinationRectangle.height

// these work okay
XCTAssertEqual(w, 800, accuracy: 0.001) 
XCTAssertEqual(h, 533, accuracy: 0.001)

// these fail: ""0"" is not equal to ""800""
XCTAssertEqual(metrics.imageDestinationRectangle.width, 800, accuracy: 0.001)
XCTAssertEqual(metrics.imageDestinationRectangle.height, 533, accuracy: 0.001)
</code></pre>
",https://stackoverflow.com/questions/54701901/swift-xctassertequal-float-fails-when-directly-passing-getter,"['swift', 'xcode', 'unit-testing']",256,False,0,1
Moq MongoDB UpdateOneAsync method for unit testing,"<p>I  want to moq update method that is using mongodbContext. here is what i am trying to do but its not working. how to pass UpdateResult return type <code>.ReturnsAsync&lt;UpdateResult&gt;()</code>. I am very new to Mongodb database Unit Testing with .net core.</p>

<pre><code> public void UpdateEventAsync_Test()
        {
            //Arrange
            var eventRepository = EventRepository();
            var pEvent = new PlanEvent
            {
                ID = ""testEvent"",
                WorkOrderID = ""WorkOrderID"",
                IsDeleted = false,
                IsActive = true,
                EquipmentID = ""EquipmentID""
            };
            ////Act

            mockEventContext.Setup(s =&gt; s.PlanEvent.UpdateOneAsync(It.IsAny&lt;FilterDefinition&lt;PlanEvent&gt;&gt;(), It.IsAny&lt;UpdateDefinition&lt;Model.EventDataModel.PlanEvent&gt;&gt;(), It.IsAny&lt;UpdateOptions&gt;(), It.IsAny&lt;System.Threading.CancellationToken&gt;())).ReturnsAsync&lt;UpdateResult&gt;();
            var result = eventRepository.UpdateEventAsync(pEvent);
            ////Assert
            result.Should().NotBeNull();
            Assert.AreEqual(true, result);

        }
</code></pre>

<p>below is the code for which i want to write Moq Test</p>

<pre><code>   public async Task&lt;bool&gt; UpdateEventAsync(Model.EventDataModel.PlanEvent eventobj)
    {
        var filter = Builders&lt;Model.EventDataModel.PlanEvent&gt;.Filter.Where(f =&gt; f.ID == eventobj.ID);

        // TO Do: Use replace instead of update.
        var updatestatement = Builders&lt;Model.EventDataModel.PlanEvent&gt;.Update.Set(s =&gt; s.IsDeleted, eventobj.IsDeleted)
            .Set(s =&gt; s.EquipmentID, eventobj.EquipmentID)
            .Set(s =&gt; s.PlannedStartDateTime, eventobj.PlannedStartDateTime)
            .Set(s =&gt; s.PlannedEndDatetime, eventobj.PlannedEndDatetime)
            .Set(s =&gt; s.WorkOrderID, eventobj.WorkOrderID)
            .Set(s =&gt; s.ResourceID, eventobj.ResourceID)
            .Set(s =&gt; s.LastUpdatedBy, eventobj.LastUpdatedBy)
            .Set(s =&gt; s.EventComment, eventobj.EventComment)
            .Set(s =&gt; s.SiteID, eventobj.SiteID)
            .Set(s =&gt; s.LastUpdatedDateTime, DateTime.UtcNow.ToString());

        UpdateResult updateResult = await _eventContext.PlanEvent.UpdateOneAsync(filter, updatestatement);
        return updateResult != null &amp;&amp; updateResult.IsAcknowledged &amp;&amp; updateResult.ModifiedCount &gt; 0;
    } 
</code></pre>
",https://stackoverflow.com/questions/54636283/moq-mongodb-updateoneasync-method-for-unit-testing,"['mongodb', 'unit-testing', '.net-core']",2300,True,0,1
Stub only one private static method in a class,"<p>I have a class that I am unit testing. It looks like following:</p>

<pre><code> public class classToUT {
         public static Event getEvent(String id) {
                return getEvent(id, null);
         }
         private static Event getEvent(String id, String name) {
              //do something
              logEvent(id, name);
              return event;
         }
         private static void logEvent(String id, string name) {
             // do some logging
         }
    }
</code></pre>

<p>There are external util methods being called in <code>logEvent</code> that I want to avoid. Basically, I want only <code>logEvent</code> to be stubbed out but all other methods to be called in my unit test. How do I stub out this one method only?</p>

<pre><code>public void UTClass {
    @Test
    public void testGetEvent() {
         assertNotNull(event, classToUt.getEvent(1)); //should not call logEvent 
        //but call real method for getEvent(1) and getEvent(1, null)  
    }
}
</code></pre>
",https://stackoverflow.com/questions/57172975/stub-only-one-private-static-method-in-a-class,"['java', 'unit-testing', 'testing', 'mockito', 'powermock']",101,True,1,1
How to test while loop code using jest and nodejs,"<p>I'm having a hard time doing some test on while loop using jest. This is the code I want to test but don't know how to do it.</p>

<pre><code>const SHA256 = require('crypto-js/sha256')

class Block {
    constructor(index, timestamp, data, prevHash = """") {
        this.index = index
        this.timestamp = timestamp
        this.data = data
        this.prevHash = prevHash
        this.hash = this.calculateHash()
        this.nonce = 0
    }

    calculateHash() {
        return SHA256(this.index + this.prevHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString()
    }

    mineBlock(difficulty) {
        while(this.hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')) {
            this.nonce++
            this.hash = this.calculateHash()
        }

    }
}

module.exports = Block
</code></pre>

<p>This is what I've done so far</p>

<pre><code>const Block = require('../block')

const BlockClass = new Block()

describe('Block Class', () =&gt; {
    it('constructor', () =&gt; {
        const obj = new Block(1, 2, 3, 4, 0)
        expect(obj.index).toBe(1)
        expect(obj.timestamp).toBe(2)
        expect(obj.data).toBe(3)
        expect(obj.prevHash).toBe(4)
        expect(obj.nonce).toBe(0)
    })
})

describe('hash', () =&gt; {
    it('should be string', () =&gt; {
        expect(typeof BlockClass.calculateHash()).toBe('string')
    })
})
</code></pre>

<p>I'm pretty new with jest and unit testing and I find it really nice skills to have.</p>
",https://stackoverflow.com/questions/55389308/how-to-test-while-loop-code-using-jest-and-nodejs,"['node.js', 'jestjs']",2905,True,0,1
Testing tools for Docker Images,"<p>A colleague of mine removed mysqli driver in one of our Dockerfile for PHP hosting and it causes problem. Luckily it is discovered in staging environment.</p>

<p>Is there any tools our there that does unit testing for docker images and if there are certain unavailability of an essential driver, fail it in the CI/CD pipeline?</p>
",https://stackoverflow.com/questions/55490283/testing-tools-for-docker-images,"['docker', 'dockerfile']",1048,True,3,2
How to compare or verify object that does not override equals method?,"<p>I use mockk for unit testing in Kotlin (Android).</p>

<p>I want to verify that a function is called:</p>

<pre><code>    verify { obj.callSomething(""param1"", Param2(""A"", ""B"")) }
</code></pre>

<p>In this case <code>Param2</code> is a generated Java class that doesn't override <code>equals</code> method so that the verification is always fail.</p>

<p>I've tried to use <code>match</code> but the failure message is simply not helpful.</p>

<pre><code>    verify { obj.callSomething(""param1"", match { it.a == ""A"" &amp;&amp; it.b == ""B"" }) }
</code></pre>

<p>Is there a better or correct way to do this?</p>
",https://stackoverflow.com/questions/55567994/how-to-compare-or-verify-object-that-does-not-override-equals-method,"['android', 'kotlin', 'mockk']",938,True,3,1
How to pass mock date event value on unit testing in angular,"<p>I have a function which needs date from datepicker event. I used matdatepicker to select date from UI.</p>

<p><strong>i want to pass date event value on onDateSelected() function.</strong></p>

<p>can anybody help me to pass date event value to pass my unit test case.</p>

<p>i tried below code but it wont works</p>

<p><strong>my function</strong></p>

<pre><code> onDateSelected(event: MatDatepickerInputEvent&lt;Date&gt;) {
    const dts = event.value;
    const startDate = moment(dts).format('MM/DD/YYYY');
    this.details.controls.contractStartDate.setValue(startDate);
    this.selectedDate = this.details.get('contractStartDate').value;
    this.selectedDate = event.value;
  }
</code></pre>

<p><strong>Unit testing code</strong></p>

<pre><code>  it('should check ondate selected event', () =&gt; {
    const date = new Date(10/03/2019);
    component.onDateSelected(date);
    fixture.detectChanges();
    expect(component.details.get('contractStartDate').value.toString()).toEqual(date);
  });
</code></pre>
",https://stackoverflow.com/questions/58231457/how-to-pass-mock-date-event-value-on-unit-testing-in-angular,"['angular', 'jasmine', 'karma-jasmine']",5103,True,3,1
Testing Angular Directives,"<p>I have an angular directive that attaches to an event on the element:</p>

<pre><code>@Directive({
    selector: '[myDirective]'
})
export class MyDirective {
    @HostListener('click', ['$event']) click(event: Event): void {
        debugger;
        console.log(event); // &lt;-- this is null in unit tests, MouseEvent when running the app normally
    }
}
</code></pre>

<p>This works fine, but for some reason the event parameter is <code>null</code> when unit testing the directive.</p>

<p>My Karma Jasmine unit test setup:</p>

<pre><code>import { CommonModule } from '@angular/common';
import { Component, DebugElement, ElementRef, Injector } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

@Component({
    selector: 'host-component',
    template: `
        &lt;input type=""text"" myDirective id=""findMe""/&gt;
    `
})
class HostComponent {
}

describe(`MyDirective`, () =&gt; {
    let host: HostComponent;
    let fixture: ComponentFixture&lt;HostComponent&gt;;

    let debugElement: DebugElement;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [
                CommonModule
            ],
            declarations: [
                HostComponent, MyDirective
            ]
        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(HostComponent);
        host = fixture.componentInstance;

        debugElement = fixture.debugElement.query(By.css('#findMe'))

        fixture.autoDetectChanges();
    });

    describe(`should listen to the events`, () =&gt; {
        it(`should listen to the click event`, () =&gt; {
            fixture..triggerEventHandler('click', null);

            fixture.detectChanges();
            // expect...
        });
    });
});
</code></pre>

<p>Now, the problem: The directive is being hit in the unit test, but there is no <code>event</code> sent through as a parameter. </p>

<blockquote>
  <p>I've followed this example: <a href=""https://codecraft.tv/courses/angular/unit-testing/directives/"" rel=""nofollow noreferrer"">https://codecraft.tv/courses/angular/unit-testing/directives/</a> but unfortunately it doesnt use the event parameter.</p>
</blockquote>

<p><strong>Edit</strong></p>

<p>I've also followed <a href=""https://medium.com/claritydesignsystem/four-ways-of-listening-to-dom-events-in-angular-part-2-hostlistener-1b66d45b3e3d#3508"" rel=""nofollow noreferrer"">this example</a> to pass through arguments to the <code>@HostListener()</code> decorator:</p>

<pre><code>@HostListener('mouseenter', ['$event.target.id']) 
    onMouseEnter(id: string) {
        // Logs the id of the element 
        // where the event is originally invoked.  
    console.log(id);
}
</code></pre>

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

<p>It seems that the events raised from the DebugElement does not really represent the actual event listeners from the DOM element?</p>

<p>From what Hojou said <a href=""https://github.com/angular/angular/issues/22148#issuecomment-376811217"" rel=""nofollow noreferrer"">on this angular github issue</a>, if you trigger the event from the nativeElement it works. So the following code does send through the event to the directive, just not too sure if its the <em>right</em> way:</p>

<pre><code>describe(`should listen to the events`, () =&gt; {
    it(`should listen to the click event`, () =&gt; {
        // fixture.triggerEventHandler('click', null);
        debugElement.nativeElement.dispatchEvent(newEvent('click'));

        fixture.detectChanges();
        // expect...
    });
});

function newEvent(eventName: string) {
    const customEvent: CustomEvent&lt;any&gt; = document.createEvent('CustomEvent');  // MUST be 'CustomEvent'
    customEvent.initCustomEvent(eventName, false, false, null);
    return customEvent;
}
</code></pre>
",https://stackoverflow.com/questions/57557921/testing-angular-directives,"['angular', 'unit-testing', 'karma-jasmine', 'angular-directive']",729,True,1,3
How to test a function that makes a call to a static function - trying to fake static function,"<p>Please note that I am unit testing VB.NET code using C#. I am trying to mock a interface call which has an implementation that calls a static function.  I am new to unit testing in .NET and mocking/faking in general.</p>

<p>I have tried to use the moq and Microsoft Fakes frameworks but cannot figure out exactly how to make this work.</p>

<p>Project 1 (Static) - Cannot change:</p>

<pre class=""lang-vb prettyprint-override""><code>Public Class CommonCode
    Private Sub New()
    End Sub

    Public Shared Function HelpFunction(objContext, objString) As Integer
        Using objCmd As SqlCommand = objContext.DbConnection.CreateCommand()
            'code - db call
            return number
        End Using
    End Function
End Class
</code></pre>

<p>Project 2:</p>

<pre class=""lang-vb prettyprint-override""><code>Public Class Validate
    Private objHelper As IHelper

    Public Function GetErrors(objContext, objString) As String
        If objHelper.GetHelp(objContext, objString) &lt; 1
            Return ""ERROR""
        End If
    End Function
End Class
</code></pre>

<p>I tried adding an interface to help fake this function as I found I could not fake a static function.</p>

<pre class=""lang-vb prettyprint-override""><code>Public Interface IHelper
    Public Function GetHelp(objContext, objString) As Integer
End Interface
</code></pre>

<pre class=""lang-vb prettyprint-override""><code>Public Class Helper Implements IHelper
    Public Function GetHelp(objContext, objString) As Integer
        Return CommonCode.HelpFunction(objContext, objString)
    End Function
End Class
</code></pre>

<p>Test Case (note that most these items are used for other tests so just have that in mind)</p>

<pre><code>[TestClass]
public class RTATAXSTATUS_01_PRC_Validation_Test
{
    ShimMainObj shimTestObj;
    MainObj testObj;
    Validate objValidation;
    Mock&lt;IHelper&gt; mockHelper;
    IDisposable shimContext;
    bool blnIsValid;

    [TestInitialize]
    public void SetUp()
    {
        mockHelper= new Mock&lt;IHelper&gt;();
        shimContext = ShimsContext.Create();
        shimTestObj= new ShimTest();
        testObj = shimTestObj.Instance;
        objValidation = new Validate ();
        blnIsValid = true;
    }

    [TestCleanup]
    public void TearDown()
    {
        shimContext.Dispose();
    }

    [TestMethod]
    public void Test_StreamID_ExistsInPetrinex()
    {
        string strId = ""TESTME"";

        //for other validation in the GetErrors function
        shimTestObj.Value = () =&gt; { return strId); };

        mockHelper.Setup(m =&gt; m.GetHelp(null, strId)).Returns(1234);

        string strMsgs = objValidation.GetErrors(null, testObj.Value);

        Assert.IsFalse(blnIsValid, ""Errors should have been found."");
        Assert.IsTrue(strMsgs.Contains(""ERROR""));
    }
}
</code></pre>

<p>This ends up returning a NullReferenceException because when trying to use the objContext, it see's object as a null object. Any ideas would be appreciated, I just don't have the knowledge to proceed and could not find anything online that worked for me.</p>

<p>I was wondering if it is possible to have another implementation of this interface in my tests project and somehow force my GetHelp interface to point to the implementation I want to use.  I already created another implementation but am not sure how to use it in place of the original.</p>

<p>Note that the Shims work correctly as they are being tested in prior unit testing code, although I am sure my code is quite bad so any suggestions would be nice.</p>
",https://stackoverflow.com/questions/55405066/how-to-test-a-function-that-makes-a-call-to-a-static-function-trying-to-fake-s,"['c#', 'vb.net', 'unit-testing', 'moq', 'microsoft-fakes']",162,False,0,1
java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null),"<p>I am making some unit testing. but when i want to run that unit test it gave me error like this</p>

<p>""java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)""</p>

<p>what i am doing wrong?</p>

<p>this is my gradle. i wonder if i add wrong dependency into it, please help me :'( </p>

<pre><code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion ""29.0.2""
    defaultConfig {
        multiDexEnabled true
        applicationId ""com.example.androidjetpacksubmission1""
        minSdkVersion 15
        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'
        }

        debug{
            applicationIdSuffix "".debug""
            debuggable true
        }
    }

    testOptions {
        unitTests.returnDefaultValues = true
    }

    androidExtensions {
        experimental = true
    }
}

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.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'com.github.bumptech.glide:glide:4.10.0'
    implementation ""androidx.lifecycle:lifecycle-extensions:2.1.0""
    implementation 'androidx.test.espresso:espresso-idling-resource:3.2.0'
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
    implementation 'com.facebook.shimmer:shimmer:0.5.0'
    implementation ""androidx.arch.core:core-testing:2.1.0""
    implementation ""org.mockito:mockito-android:3.1.0""
    implementation 'androidx.multidex:multidex:2.0.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:core:1.2.0'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test:rules:1.2.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.ext:truth:1.2.0'
    androidTestImplementation 'androidx.arch.core:core-testing:2.1.0'
    androidTestImplementation 'com.google.truth:truth:0.42'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-web:3.2.0'
    androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-idling-resource:3.2.0'
    androidTestImplementation 'com.android.support.test:runner'
    androidTestImplementation group: 'org.mockito', name: 'mockito-core', version: '3.1.0'
    androidTestImplementation group: 'org.mockito', name: 'mockito-inline', version: '3.1.0'
    testImplementation ""androidx.arch.core:core-testing:2.1.0""
    androidTestImplementation ""org.mockito:mockito-android:3.1.0""
    androidTestImplementation ""androidx.arch.core:core-testing:2.1.0""
}
</code></pre>

<p>and this is my unit test code</p>

<pre><code>package com.example.androidjetpacksubmission1.ui.detail

import androidx.lifecycle.Observer
import com.example.androidjetpacksubmission1.data.entity.TvShowEntity
import com.example.androidjetpacksubmission1.data.repository.RemoteRepository
import com.example.androidjetpacksubmission1.network.Network
import com.example.androidjetpacksubmission1.network.NetworkListener
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify


class DetailTvShowViewModelTest : NetworkListener {
    override fun onSuccess(msg: String) {
    }

    override fun onFailure(msg: String?) {
    }

    @get:Rule
    var executorRule = androidx.arch.core.executor.testing.InstantTaskExecutorRule()
    private lateinit var detailTvShowViewModel: DetailTvShowViewModel
    private lateinit var remoteRepository: RemoteRepository
    private lateinit var observer: Observer&lt;*&gt;
    private val tvShowTitleExample = ""Jumanji: The Next Level""

    @Before
    fun setup(){
        observer = mock(Observer::class.java)
        remoteRepository = RemoteRepository(Network.routes())
        detailTvShowViewModel = DetailTvShowViewModel(remoteRepository,tvShowTitleExample)
        detailTvShowViewModel.networkListener = this
    }

    @Test
    fun getDetailMovie() {
        detailTvShowViewModel.getDetailTvShow().observeForever(observer as Observer&lt;in TvShowEntity&gt;)

        detailTvShowViewModel.fetchDetailTvShow()

        verify(observer).onChanged()
    }
}

private fun &lt;T&gt; Observer&lt;T&gt;.onChanged() {

}
</code></pre>
",https://stackoverflow.com/questions/59388864/java-lang-illegalstateexception-could-not-initialize-plugin-interface-org-mock,"['android', 'unit-testing', 'mockito']",611,False,3,0
When does boost::lexical_cast to std::string fail?,"<p>I'm writing unit tests and trying to have all my code covered.</p>

<p>I have in my code something like this:</p>

<pre><code>template&lt;typename ValueType&gt;
std::string ConvertToStringUsingBoost(ValueType const&amp; v)
{
    try 
    {
        return boost::lexical_cast&lt;std::string, ValueType&gt;(v);
    }
    catch(boost::bad_lexical_cast const&amp; e)
    {
        LOG_ERR(""Fail to cast %s to string"", e.source_type().name);
        return std::string();
    }
}
</code></pre>

<p>I was reading <a href=""https://www.boost.org/doc/libs/1_55_0/doc/html/boost_lexical_cast/"" rel=""nofollow noreferrer"">these docs</a> and couldn't find any information about when <code>boost::lexical_cast</code> to <code>std::string</code> can throw an exception.</p>

<p>Can you please help me with that?</p>

<p>If it's impossible I'll simply delete this try-catch. If it's possible, I'd prefer to cover this in unit testing.</p>
",https://stackoverflow.com/questions/55935576/when-does-boostlexical-cast-to-stdstring-fail,"['c++', 'boost', 'lexical-cast']",2243,True,9,3
How to test: onClick event - Jest/ Enzyeme,"<p>I am new to unit testing and I just ran a test coverage. This is the only line missing at the moment.</p>

<p>How could I test this line and make sure 100 % is covered</p>

<pre><code>   export default class Normalize extends Component {

 constructor(props) {
super(props)
this.state = {}
 //    this.handleChange = this.handleChange.bind(this)
}

 componentDidMount() {
 this.props.normalizeData(null)    
}

 render () {
return (
  &lt;div id='normalize-container'&gt;
    &lt;div id='normalize-header'&gt;
    &lt;/div&gt;
    &lt;br /&gt;&lt;br /&gt;
    &lt;h3 className='normalized-header'&gt;{this.props.newResponse ? 'Raw Data' : 'Normalized Data'}&lt;/h3&gt;&lt;br/&gt;
    &lt;div&gt;
      {this.props.newResponse ? null :
        this.props.THead ?
          &lt;div&gt;
            {!this.props.datasourceCatalog ? 
              &lt;div id='next-button-modal'&gt;
                {/*&lt;button title='Proceed To Shape' className='request-button' id='next-btn-ready-modal' onClick={this.props.nextTab}&gt;&lt;img src={nextImg}/&gt;&lt;/button&gt;*/}
                &lt;button title='Proceed To Shape' className='request-button' id='next-btn-ready-modal' onClick={(e) =&gt; {this.props.toggleModal(); this.props.nextTab();}}&gt;
                  &lt;FontAwesome
                  className='fa-angle-right'
                  name='view-externallink-img'
                  size='2x'/&gt;                  
                &lt;/button&gt;

                &lt;h4&gt;Proceed To Shape&lt;/h4&gt;
              &lt;/div&gt; : 
            null}

            &lt;div className='normalize-table-container'&gt;
              &lt;div className=""data-table-wrapper""&gt;
                &lt;table&gt;
                  &lt;thead dangerouslySetInnerHTML={{__html: this.props.THead}} /&gt;
                  &lt;tbody dangerouslySetInnerHTML={{__html: this.props.TBody}} /&gt;
                &lt;/table&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        : null
      }
    &lt;/div&gt;
  &lt;/div&gt;
</code></pre>

<p>Using React JS -  jest and enzyme</p>

<p>Testing file :</p>

<pre><code>// jest mock functions (mocks this.props.func)
const normalizeData =  jest.fn();
const toggleModal =  jest.fn();
const nextTab =  jest.fn();
const onClick =  jest.fn();

// defining this.props
const baseProps = {
normalizeData,
newResponse:{},
THead:{},
TBody:{},
datasourceCatalog:{},
toggleModal,
nextTab,
onClick,

describe(' Normalize Test', () =&gt; {
let wrapper;
let tree;

beforeEach(() =&gt; wrapper = shallow(&lt;Normalize  {...baseProps} /&gt;));

it(' Should render with all of the props', () =&gt; { 
</code></pre>

<p>Render with all props are working - but just need to make sure how to test the line above, on click with 2 props.</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/54607307/how-to-test-onclick-event-jest-enzyeme,"['javascript', 'reactjs', 'unit-testing']",42572,True,9,1
"Laravel Feature Testing. Cache mocking not working! CacheManager::driver(), but no expectations were specified","<p>When I test my application with unit-testing cache moking works well. But when I try test my api through feature tests I got an exception.</p>

<pre><code>public function testGet()
{
    Cache::shouldReceive('rememberForever')-&gt;times(5)-&gt;andReturn([]);

    Cache::shouldReceive('has')
        -&gt;once()
        -&gt;andReturn(false);

    Cache::shouldReceive('forever')
        -&gt;once()
        -&gt;andReturn([]);

    $response = $this-&gt;getJson('/api/table/get');
    $response-&gt;assertOk();

    $responseArr = $response-&gt;getOriginalContent();
    $this-&gt;assertEmpty($responseArr['table']);
}
</code></pre>

<blockquote>
  <p>Tests\Feature\Controller\API\Site\TableApiControllerTest::testGet
  Mockery\Exception\BadMethodCallException: Received
  Mockery_2_Illuminate_Cache_CacheManager::driver(), but no expectations
  were specified</p>
</blockquote>

<p>Exactly the same mocking in other unit-tests works without errors.</p>
",https://stackoverflow.com/questions/56234834/laravel-feature-testing-cache-mocking-not-working-cachemanagerdriver-but,"['laravel', 'testing', 'mocking', 'phpunit', 'laravel-5.8']",2936,True,1,1
How to handle external modules when writing unit tests for server-side Javascript,"<p>I am unit testing a JS file that has a <code>require</code> that points to an external module. How do I handle the external module when running UT if it keeps on looking for that external module locally?</p>

<p>I already tried mocking a function from the script, but I do not think that is the proper way to test its components. What I really want is for my test file to point to the script file, and that script file will either skip the call for the <code>require</code> part that calls the external modules OR find a way to override or ignore that line so that I can start referencing the functions and components I need in the script file for unit testing.</p>

<p><strong>Deal.js</strong></p>

<pre><code>var cordra = require('cordra');
var util = require('util');

exports.beforeSchemaValidation = beforeSchemaValidation;

function beforeSchemaValidation(deal, context) {
...
return deal;
}
</code></pre>

<p><strong>DealTest.js</strong></p>

<pre><code>var assert = require('chai').assert;
const beforeSchemaValidation = require('../rules/Deal').beforeSchemaValidation;

describe('Deal', function() {
  it('beforeSchemaValidation should return object', function() {
    let result = beforeSchemaValidation();
    assert.typeOf(result, Object);
  });
});
</code></pre>

<p>I want my test file to run through <code>../rules/Deal</code> without getting a thrown error of <code>Error: Cannot find module 'cordra'</code> and/or <code>'util'</code> so I can test the rest of its components.</p>
",https://stackoverflow.com/questions/54624756/how-to-handle-external-modules-when-writing-unit-tests-for-server-side-javascrip,"['javascript', 'unit-testing', 'mocha.js', 'chai']",124,False,0,1
CompileError: AsyncCompile: Wasm decoding failed: expected magic word,"<p>While running my wasm code in unit testing a function, I am getting this error:</p>

<pre><code>CompileError: AsyncCompile: Wasm decoding failed: expected magic word 00 61 73 6d, found 3c 21 44 4f @+0
</code></pre>

<p>Though I have successfully added the compiled wasm file to the directory and the main part is code is running with browser but not with tests.</p>

<p>The tests are running with tape and browserified.  </p>

<pre class=""lang-js prettyprint-override""><code>const imports = {
      env:{
        // paceOp: require('pace').op,
        consoleLog:console.log,
        perform: function(x,y){
          let pixel = options.changePixel(
            pixels.get(x, y, 0),
            pixels.get(x, y, 1),
            pixels.get(x, y, 2),
            pixels.get(x, y, 3),
            x,
            y
          );

          pixels.set(x, y, 0, pixel[0]);
          pixels.set(x, y, 1, pixel[1]);
          pixels.set(x, y, 2, pixel[2]);
          pixels.set(x, y, 3, pixel[3]);
        }
      }
    };
    const inBrowser = (options.inBrowser)?1:0;
    const test = (process.env.TEST)?1:0;
    fetch('./test.wasm').then(response =&gt;
      response.arrayBuffer()
    ).then(bytes =&gt;
      WebAssembly.instantiate(bytes, imports)
    ).then(results =&gt; {
      results.instance.exports.manipulatePixel(pixels.shape[0],pixels.shape[1],inBrowser, test);
        extraOperation();
    }).catch(err=&gt;{
      console.log(err)
    });
</code></pre>

<p>Can someone please help me with it!!
Thanks in advance..</p>
",https://stackoverflow.com/questions/56427897/compileerror-asynccompile-wasm-decoding-failed-expected-magic-word,"['javascript', 'unit-testing', 'testing', 'webassembly']",1538,False,2,1
Angular 7 swUpdate breaks unit testing and cannot be mock / override for testing (PWA),"<p>Here is my component for implementing the <code>swUpdate</code> :</p>

<pre><code>public thereIsUpdate: boolean;

constructor(public swUpdate: SwUpdate) {
    this.checkForUpdates();
}

checkForUpdates() {
  this.swUpdate.checkForUpdate().then(() =&gt; {
    this.swUpdate.available.subscribe(swEvt =&gt; {
      // an update is available
      this.thereIsUpdate = true;
    });
  });
}
</code></pre>

<p>and here is my unit testing :</p>

<pre><code>class MockSwUpdate {
  available = new Subject&lt;{ available: { hash: string } }&gt;().asObservable();
  activated = new Subject&lt;{ current: { hash: string } }&gt;().asObservable();

  public checkForUpdate(): Promise&lt;void&gt; {
    console.log('This is not working');
    return new Promise((resolve) =&gt; resolve());
  }
  public activateUpdate(): Promise&lt;void&gt; {
    return new Promise((resolve) =&gt; resolve());
  }

  constructor(public isEnabled: boolean) {
  }
}

class MockApplicationRef {
  isStable = new Subject&lt;boolean&gt;();
}

describe('xComponent', () =&gt; {
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        xComponent
      ],
      imports: [
        RouterTestingModule,
        ServiceWorkerModule.register('', {enabled: false})
      ],
      providers: [
        {provide: SwUpdate, useValue: MockSwUpdate},
        {provide: ApplicationRef, useClass: MockApplicationRef}
      ]
    }).compileComponents();
  }));
}
</code></pre>

<p><strong>My problem is cannot doing the ""mock"" for <code>swUpdate</code>, somehow it is not working.</strong></p>

<p>Somehow the <code>SwUpdate</code> is not mocked even i have specify it.</p>

<p>When i run <code>ng test</code>, it is showing this error :</p>

<pre><code>Uncaught TypeError: this.swUpdate.checkForUpdate is not a function thrown
    TypeError: this.swUpdate.checkForUpdate is not a function
</code></pre>

<p>Please note that : The mock is <strong>only not working for the <code>SwUpdate</code></strong>.</p>
",https://stackoverflow.com/questions/58521010/angular-7-swupdate-breaks-unit-testing-and-cannot-be-mock-override-for-testing,"['angular', 'service-worker', 'progressive-web-apps', 'angular-unit-test', 'angular-pwa']",1119,False,1,1
How do I unit test a Command Handler that returns a void?,"<p>Please see the code below:</p>

<pre><code>public class CreatePersonHandler
        : IRequestHandler&lt;CreatePersonCommand,Unit&gt;
    {

 public async Task&lt;Unit&gt; Handle(CreatePersonCommand message, CancellationToken cancellationToken)
        {
            var person = _enquiryFactory.Create(message.Gender, message.Salary);
            var offers = getAvailableOffers(); 
            person.AssignOffers(offers);
            await _mediator.DispatchDomainEventsAsync(person);
            return Unit.Value;
        }
  }
</code></pre>

<p><strong>Notice that:</strong></p>

<blockquote>
  <p>1) The command does not have any state.<br>
  2) The command method
  has no return value.</p>
</blockquote>

<p>I have read a few similar questions on here e.g. this one: <a href=""https://stackoverflow.com/questions/246038/unit-testing-void-methods"">Unit testing void methods?</a>.  Are CQRS command handlers that return voids classed as informational and should not be unit tested?</p>
",https://stackoverflow.com/questions/54706427/how-do-i-unit-test-a-command-handler-that-returns-a-void,"['c#', 'cqrs']",1649,True,1,2
How to pass ContainerInterface from test class in symfony 3.4,"<p>I am testing command line application in Symfony Unit testing, in my command class I used container interface via constructor.</p>

<p>When I test it using unit test, it returns the following error
<code>
Too few arguments to function AppBundle\Command\DocumentCommand::__construct(), 0 passed
</code></p>

<h3>My Command class</h3>

<pre><code>use Symfony\Component\DependencyInjection\ContainerInterface as Container;

class DocumentCommand extends Command
{
    private $container;
    // the name of the command (the part after ""bin/console"")
    protected static $defaultName = 'identification-requests:process';

    public function __construct(Container $container, bool $requirePassword = false)
    {
        $this-&gt;container = $container;
        $this-&gt;base_path = $this-&gt;container-&gt;get('kernel')-&gt;getRootDir();

        $this-&gt;requirePassword = $requirePassword;

        parent::__construct();
    }
</code></pre>

<h3>Test class</h3>

<pre><code>use Symfony\Component\DependencyInjection\ContainerInterface;

class DocumentCommandTest extends KernelTestCase
{
    /** @var  Application $application */
    protected static $application;

    /** @var  Client $client */
    protected $client;

    /** @var  ContainerInterface $container */
    protected $container;

    /**
     * Test Execute
     *
     */
    public function testExecute()
    {
        $kernel = static::createKernel();
        $kernel-&gt;boot();

        $application = new Application($kernel);
        $application-&gt;add(new DocumentCommand());

        $command = $application-&gt;find('identification-requests:process');
        $commandTester = new CommandTester($command);
        $commandTester-&gt;execute(array(
            'command' =&gt; $command-&gt;getName(),
            'file' =&gt; 'input.csv'
        ));

        $output = $commandTester-&gt;getOutput();
        $this-&gt;assertContains('valid',$output);
    }
}
</code></pre>

<p>I tried to pass the container interface from test class but didn't work. Following is the error message </p>

<pre><code>1) Tests\AppBundle\Command\DocumentCommandTest::testExecute
ArgumentCountError: Too few arguments to function AppBundle\Command\DocumentCommand::__construct(), 0 passed in \tests\AppBundle\Command\DocumentCommandTest.php on line 34 and at least 1 expected
</code></pre>
",https://stackoverflow.com/questions/57698293/how-to-pass-containerinterface-from-test-class-in-symfony-3-4,"['php', 'unit-testing', 'phpunit', 'console-application', 'symfony-3.4']",791,True,1,1
Mocking class with no virtual methods,"<p>I have just started to use google mock for unit testing production code. The classes I want to mock have no virtual methods inside. From reading a little on google mock, is it not possible to mock a class like this? Bear in mind I don't want to make any changes to the source.</p>

<pre><code>class Test
{
    Test(void);
    virtual ~Test() {}
    Add();
};

int Test::Add()
{
    return 1;
}

class MockTest : public Test
{
public:
    MOCK_METHOD0(Add,int(void));
};
</code></pre>
",https://stackoverflow.com/questions/54336916/mocking-class-with-no-virtual-methods,"['c++', 'googletest', 'googlemock']",1935,True,1,1
Is there a Shim solution (like Microsoft Fakes) that is compatible with xUnit?,"<p>I'm looking for a good .Net Shim solution for unit testing that is compatible with xUnit. I've used Pose before (<a href=""https://github.com/tonerdo/pose"" rel=""nofollow noreferrer"">https://github.com/tonerdo/pose</a>), but it only occasionally works - I have run into multiple cases where it fails to generate working CIL (you just get a System.InvalidProgramException when the test executes). Based on the project's forum, this is apparently a known issue for some time now, supposedly fixed a couple of times, but still open because it keeps coming up.</p>

<p>So, I'm looking for a more reliable Shim solution. It must be usable from xUnit, because that is the unit testing framework imposed upon the department - apparently our automated build pipeline has some kind of issues that I don't know the details of with the QualityTools assembly, so that's not an option for us. Pose is great when it works, but I have run into too many instances where it didn't work, and I'm looking for something more reliable.</p>
",https://stackoverflow.com/questions/57117676/is-there-a-shim-solution-like-microsoft-fakes-that-is-compatible-with-xunit,"['.net', 'unit-testing', 'microsoft-fakes', 'shim']",592,False,3,0
Failed unit /functional testing symfony 4.2,"<p>I am writing codes for performing unit testing in symfony 4.2, actually am using JWT Authentication bundle for generating token. i want to test whether token is generated successfully or not. Kindly have a look on to it and suggest me if there is any improvements needed.</p>

<p>Codes in Login COntroller</p>

<pre><code>&lt;?php

namespace App\Controller;

use App\Entity\Organization;
use Doctrine\Common\Annotations\AnnotationReader;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class LoginController extends AbstractController
{
protected $serializer;

protected $logger;

public function __construct(LoggerInterface $logger)
{
    $this-&gt;logger = $logger;
    $encoders = array(new XmlEncoder(), new JsonEncoder());
    $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
    $normalizer = new ObjectNormalizer($classMetadataFactory);
    $normalizer-&gt;setCircularReferenceLimit(2);
    $normalizer-&gt;setCircularReferenceHandler(function ($object) {
        return $object-&gt;getId();
    });
    $normalizers = array($normalizer);
    $this-&gt;serializer = new Serializer($normalizers, $encoders);
}

/**
 * Check the credentials are valid
 * Check whether the user is verified
 * Generate JWT token for authentic users and return
 *
 * @Route(""/api/login_check"", name=""login_check"")
 */
public function login(Request $request, JWTTokenManagerInterface $JWTTokenManager, UserProviderInterface $userProvider, UserPasswordEncoderInterface $encoder)
{
    try {
        $data = json_decode($request-&gt;getContent());
        $user = $userProvider-&gt;loadUserByUsername($data-&gt;email);
        $passwordValid = $encoder-&gt;isPasswordValid($user, $data-&gt;password);
        if ($passwordValid) {
            if ($user-&gt;getVerified()) {
                $organization = $user-&gt;getOrganization();
                $organization = $this-&gt;getDoctrine()-&gt;getRepository(Organization::class)-&gt;findOneBy(array('id' =&gt; $organization-&gt;getId()));
                $token = $JWTTokenManager-&gt;create($user);
                return new JsonResponse(['token' =&gt; $token, 'user' =&gt; $this-&gt;serializer-&gt;normalize($user, 'json')]);
            } else {
                $array = array('message' =&gt; 'User not verified');
                $response = new Response(json_encode($array), 401);
                $response-&gt;headers-&gt;set('Content-Type', 'application/json');
                return $response;
            }
        } else {
            $array = array('message' =&gt; 'Bad credentials');
            $response = new Response(json_encode($array), 401);
            $response-&gt;headers-&gt;set('Content-Type', 'application/json');
            return $response;
        }
    } catch (\Exception $e) {
        return new Response($e-&gt;getMessage());
    }
}
}
</code></pre>

<p>Codes in Test/controller Folder</p>

<pre><code>    namespace App\Tests\Controller

use App\Controller\Log;
use App\Controller\LoginController;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;

class LoginTest extends TestCase{

    protected $logger;
    protected $controller;
/**
 *
 */
public function setUp()
{
    $this-&gt;logger = $this-&gt;createMock(LoggerInterface::class);

    $this-&gt;controller = new LoginController(
        $this-&gt;logger
    );

    parent::setUp();
}

public function testlogin()
{
    $result = $this-&gt;controller-&gt;login('Test');
    $this-&gt;assertEquals( 'TEST1548303737',$result);
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/54342738/failed-unit-functional-testing-symfony-4-2,"['php', 'unit-testing', 'symfony']",592,True,2,2
How to get value from Task,"<p>Need to extract the value from the System.Threadding.Tasks.Task as when i call a method its returning a Task as return value.</p>

<p>Am using the Task to find any property inside to get the value but there is no property i find to get the value.</p>

<p>The target method is like below.</p>

<pre><code>public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            object response = null;
            ResponseCollection&lt;Model&gt; data = (ResponseCollection&lt;Model&gt;)context.Object;
            if (data != null &amp;&amp; data.Records != null)
            {
                List&lt;Response&gt; Response = Mapper.Map&lt;List&lt;Model&gt;, List&lt;Response&gt;&gt;(data.Records);
                response = Response;
            }
            DefaultContractResolver contractResolver = new DefaultContractResolver
            {
                NamingStrategy = new CamelCaseNamingStrategy()
            };

            return context.HttpContext.Response
            .WriteAsync(JsonConvert.SerializeObject(response,
            new JsonSerializerSettings
            {
                ContractResolver = contractResolver,
                Formatting = Formatting.Indented
            }), selectedEncoding);
        }
</code></pre>

<p>and I tried to call the method in the below fashion but all am getting is the task but I need to get the response from the task.</p>

<pre><code>[TestMethod]
public void SuccessTest()
{
    MyFormatter formatter = new MyFormatter();

    var httpContext = new DefaultHttpContext();
    httpContext.Request.Headers.Add(""customheader1"", ""9"");
    httpContext.Request.Headers.Add(""customheader2"", ""10"");
    Func&lt;Stream, Encoding, TextWriter&gt; func = NewMethod;
    OutputFormatterWriteContext context = new OutputFormatterWriteContext(httpContext, func, null, GetModel());

    Mapper.Initialize(cfg =&gt;
    {
        cfg.CreateMap&lt;Model, Response&gt;();
    });

    formatter.WriteResponseBodyAsync(context, Encoding.BigEndianUnicode).Wait();

    string responseBody = new StreamReader(context.HttpContext.Response.Body).ReadToEnd();
    Assert.AreEqual(1, 1);
}

private TextWriter NewMethod(Stream arg1, Encoding arg2)
{
    return new StreamWriter(arg1, arg2);
}
</code></pre>

<p>now, how can I find the response from the result which is of type Task?</p>

<p>This is noting but building a custum media formatter and unit testing the same. I built the formatter but when unit testing i need the response object as i need to assert.
I cant return a Task as you can see the return type of WriteAsync method is Task and i have to return that.</p>
",https://stackoverflow.com/questions/56523349/how-to-get-value-from-task,['c#'],979,True,0,2
TypeError: Cannot read property &#39;baseVal&#39; of undefined,"<p>I am unit testing my react component using renderer of react-test-renderer. it was working fine, but after using ReactCssTransitionGroup I am getting the following error ""TypeError: Cannot read property 'baseVal' of undefined"". not sure how to resolve this issue</p>

<p>I verified this issue is caused by ReactCssTransitionGroup</p>

<p>Below is my component file:</p>

<pre><code>import React from 'react';
import PropTypes from 'prop-types';
import {List, ListItem, Spinner} from '@stores/reactCommon';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';

import BagListItem from './bag-list-item';

const BagList = ({bagList, loading}) =&gt; {
  const items = bagList.map((item, key) =&gt; (
    &lt;ListItem key={key}&gt;
      &lt;BagListItem
        upc={item.upc}
        price={item.sellingPrice}
        description={item.description}
      /&gt;
    &lt;/ListItem&gt;
  ));
  return (
    &lt;div className=""bag-list""&gt;
      {loading ? (
        &lt;span className=""bag-list__spinner""&gt;
          &lt;Spinner size=""extra-large"" /&gt;
        &lt;/span&gt;
      ) : null}
      &lt;div className=""bag-list__story-default-spacer""&gt;
        &lt;List maxHeight=""70vh""&gt;
          &lt;ReactCSSTransitionGroup
            transitionName=""bagList""
            transitionAppear={true}
            transitionAppearTimeout={500}
            transitionEnterTimeout={500}
            transitionLeaveTimeout={300}
          &gt;
            {items}
          &lt;/ReactCSSTransitionGroup&gt;
        &lt;/List&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
};

BagList.propTypes = {
  bagList: PropTypes.array.isRequired,
  loading: PropTypes.bool
};

export default BagList;

</code></pre>

<p>Below is my unit test file</p>

<pre><code>import React from 'react';
import renderer from 'react-test-renderer';
import BagList from '../../../../src/client/js/components/bag-list/bag-list';

describe('&lt;BagList /&gt;', function() {
  this.items = [
    {
      upc: '123222123',
      sellingPrice: '12',
      description: 'this is a description'
    },
    {
      upc: '555123',
      price: '23',
      description: 'this is a description'
    }
  ];
  this.getComponent = items =&gt; {
    return &lt;BagList bagList={items} loading={false} /&gt;;
  };

  it('Should render &lt;BagList /&gt; with bagList', () =&gt; {
    // this line is generating the error
    const items = renderer.create(this.getComponent(this.items)).toJSON();
    expect(items).toMatchSnapshot();
  });
});

</code></pre>
",https://stackoverflow.com/questions/55380937/typeerror-cannot-read-property-baseval-of-undefined,"['reactjs', 'unit-testing', 'jestjs', 'reactcsstransitiongroup', 'react-test-renderer']",5817,True,5,2
Mockk - MockKException when testing password against regex,"<p>I've just started to do Unit testing in Kotlin using Mockk.
I'm trying to test the following function:</p>

<pre><code>    fun evaluatePredicate(regEx: String, passwordInserted: String) : Boolean {
        return passwordInserted.matches(regEx.toRegex())
    }
</code></pre>

<p>My test look like this:</p>

<pre><code>    @Test
    fun evaluatePredicate_shouldContainLowerCase_trueExpected() {

        //given
        val regEx = "".*[a-z]+.*"" //lower case
        val password = ""password""

        every { password.matches(regEx.toRegex()) } returns true
        every { SUT.evaluatePredicate(regEx, password) } returns true

        //when
        val evaluate = password.matches(regEx.toRegex())
        val result = SUT.evaluatePredicate(regEx, password)

        //then
        assertEquals(evaluate, result)
    }
</code></pre>

<p>But I'm getting :</p>

<pre><code>io.mockk.MockKException: Missing calls inside every { ... } block.
</code></pre>

<p>at line:</p>

<pre><code>every { password.matches(regEx.toRegex()) } returns true
</code></pre>

<p>I've tried to use Mockk Matcher <code>any()</code> instead of <code>matches(regEx.toRegex())</code> but nothing changed.</p>

<p>I'm not sure if I'm using the right tools for the job here.
Any suggestion is welcome.</p>
",https://stackoverflow.com/questions/56795310/mockk-mockkexception-when-testing-password-against-regex,"['android', 'unit-testing', 'mockk']",278,False,2,0
jdbcTemplate Mockito unit testing,"<p>I'm trying to perform unit testing and write a test for <code>jdbctemplate.query</code>. I need the code coverage for the below method.</p>
<h3>Code:</h3>
<pre><code>   ` public List&lt;User&gt; UserInfo(final Long runId){
    jdbcTemplate.setFetchSize(10);
    List&lt;User&gt; userList = jdbcTemplate.query(con -&gt; con.prepareStatement(GET_USER_INFO)
            , (rs, rowNum) -&gt; {
                String userName = rs.getString(&quot;username&quot;);
                String shoppingItems = rs.getString(&quot;shopingItems&quot;);
                Long shoppingid = rs.getLong(&quot;shoppingid&quot;);
                User user= new User();
                user.setCmts(userName);
                user.setNodeid(shoppingItems);
                user.setNodename(shoppingid);
                user.setRunId(runId);
                return user;
            });
    return userList;

}`
</code></pre>
<p>I have written the test as below, but running the test &quot;coverage as junit&quot; doesn't show me any code coverage for method which is inside the <code>(rs, rowNum) -&gt; {</code></p>
<h3>Test:</h3>
<pre><code>`@InjectMocks
private OracleRepository oracleRepository;

@Mock
private JdbcTemplate jdbcTemplate;

@Mock
private ResultSet rs;

@Mock
private Connection connection;

@Mock
private PreparedStatement stmt;

@Mock
private RowMapper rowMapper;

@Test
public void UserInfoTest() throws SQLException {
    String username= &quot;joe&quot;;
    String shoppingItems= &quot;3&quot;;
    long shoppingId = 1123456778;
    long runId = 2;
    List&lt;User&gt; listUser = new ArrayList&lt;User&gt;();
    Mockito.when(rs.getString(&quot;cmts&quot;)).thenReturn(cmts);
    Mockito.when(rs.getString(&quot;node&quot;)).thenReturn(node);
    Mockito.when(rs.getLong(&quot;nodeid&quot;)).thenReturn(nodeid);
     User user= new User();
     user.setUserName(username);
     user.setShoppingItems(shoppingItems);
     user.setShoppingId(shoppingId);
     user.setRunId(runId);
     listUser.add(user);
    Mockito.when(connection.prepareStatement(Mockito.any(String.class))).thenReturn(stmt);
    Mockito.when(rowMapper.mapRow(Mockito.any(ResultSet.class), Mockito.any(Integer.class))).thenReturn(user);
    Mockito.when(jdbcTemplate.query(Mockito.anyString(), Mockito.any(RowMapper.class))).thenReturn(listUser);
    List&lt;User&gt; list = oracleRepository.UserInfo(runId);
}`
</code></pre>
<p>How do I solve this problem?</p>
",https://stackoverflow.com/questions/55787901/jdbctemplate-mockito-unit-testing,"['java', 'unit-testing', 'mockito']",1104,False,-1,1
Android Espresso Testing for matching text content between two EditTexts,"<p>I have created a Android app which has Login Edit Text &amp; Password EditText with condition that if both contents in Login EditText &amp; Password EditText matches then its true else false . How to test it using Espresso Unit Testing </p>

<p>I have used below code .</p>

<pre><code> @Test
    public void validLogin() {
        onView(withId(R.id.edtUserId))
                .perform(typeText(mStringToBetyped), closeSoftKeyboard());
        onView(withId(R.id.edtPass))
                .perform(typeText(mValidPass), closeSoftKeyboard());
        onView(withId(R.id.loginBtn)).perform(click());

      //  onView(allOf(withId(R.id.edtUserId))).check(matches(withText(String.valueOf(allOf(withId(R.id.edtPass))))));

        onView(withId(R.id.edtUserId)).check(matches(isEditTextValueEqualTo(R.id.edtPass, mStringToBetyped)));

     /*   onView(allOf(withId(R.id.edtUserId)))
                .check(matches(withText(String.valueOf(withId(R.id.edtPass)))));*/


        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

Matcher&lt;View&gt; isEditTextValueEqualTo(final int viewId, final String content) {

    return new TypeSafeMatcher&lt;View&gt;() {

        @Override
        public void describeTo(Description description) {
            description.appendText(""Match Edit Text Value with View ID Value : :  "" + content);
        }

        @Override
        public boolean matchesSafely(View view) {
            if (view != null) {
                String editTextValue = ((EditText) view.findViewById(viewId)).getText().toString();

                if (editTextValue.equalsIgnoreCase(content)) {
                    return true;
                }
            }
            return false;
        }
    };
}
</code></pre>

<p>But it gives me error for Matcher as seen below </p>

<pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.test.espressodemo.MainActivityTest$1.matchesSafely(MainActivityTest.java:90)
at com.test.espressodemo.MainActivityTest$1.matchesSafely(MainActivityTest.java:80)
at org.hamcrest.TypeSafeMatcher.matches(TypeSafeMatcher.java:65)
at android.support.test.espresso.matcher.ViewMatchers.assertThat(ViewMatchers.java:526)
at android.support.test.espresso.assertion.ViewAssertions$MatchesViewAssertion.check(ViewAssertions.java:103)
at android.support.test.espresso.ViewInteraction$SingleExecutionViewAssertion.check(ViewInteraction.java:415)
at android.support.test.espresso.ViewInteraction$2.call(ViewInteraction.java:279)
at android.support.test.espresso.ViewInteraction$2.call(ViewInteraction.java:265)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code></pre>
",https://stackoverflow.com/questions/54569464/android-espresso-testing-for-matching-text-content-between-two-edittexts,"['android', 'unit-testing', 'android-espresso']",2138,True,0,2
Karma: How to debug a RangeError: Maximum call stack size exceeded?,"<p>I am developing an Angular App and use Jasmine with Karma in my Unit testing. In one of my component specs I started to get the error: <code>Uncaught RangeError: Maximum call stack size exceeded</code>.</p>

<p>I am having a hard time finding/ understanding the cause of this stack overflow and would be happy for a structured way to debug this error.</p>

<hr>

<p>The code of the problematic component (<code>...component.spec.ts</code>) is given by:</p>

<pre><code>import {
  ComponentFixture,
  TestBed,
  fakeAsync,
  tick
} from ""@angular/core/testing"";
import ""hammerjs"";

import { RegisterStudentComponent } from ""./register-student.component"";

import { MaterialModule } from ""../../modules/material/material.module"";
import { RouterTestingModule } from ""@angular/router/testing"";
import { ReactiveFormsModule } from ""@angular/forms"";
import { UserService } from ""src/app/core/user.service"";
import { userServiceStub } from ""src/testing/user-service-stub"";
import { LoadingComponent } from ""src/app/loading/loading.component"";
import { Location } from ""@angular/common"";
import { Routes } from ""@angular/router"";

const routes: Routes = [
  {
    path: ""schüler"",
    component: RegisterStudentComponent
  }
];

describe(""RegisterStudentComponent"", () =&gt; {
  let component: RegisterStudentComponent;
  let fixture: ComponentFixture&lt;RegisterStudentComponent&gt;;
  let registerStudent: HTMLElement;
  let location: Location;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [RegisterStudentComponent, LoadingComponent],
      imports: [
        MaterialModule,
        RouterTestingModule.withRoutes(routes),
        ReactiveFormsModule
      ],
      providers: [{ provide: UserService, useValue: userServiceStub }]
    }).compileComponents();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(RegisterStudentComponent);
    component = fixture.componentInstance;
    registerStudent = fixture.nativeElement;

    fixture.detectChanges();

    location = TestBed.get(Location);
  });

  const setupValidForm = () =&gt; {
    component.subjects = [""Physics""];
    component.selectedSubjects = [""Physics""];
    component.form.setValue({
      agb: true,
      email: ""test@test.de"",
      hourlyRate: 5,
      password: ""test"",
      name: ""test""
    });
  };

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

  it(""should add subject if click on subject button"", () =&gt; {
    component.subjects = [""Physics""];
    fixture.detectChanges();

    let physicsButton = registerStudent.querySelector(""div[class=subjects]"")
      .children[0];
    physicsButton.dispatchEvent(new Event(""click""));

    expect(component.selectedSubjects.includes(""Physics"")).toBeTruthy();
  });

  it(""should remove subject if selected subject is clicked"", () =&gt; {
    component.subjects = [""Physics""];
    component.selectedSubjects = [""Physics""];
    fixture.detectChanges();

    let physicsButton = registerStudent.querySelector(""div[class=subjects]"")
      .children[0];
    physicsButton.dispatchEvent(new Event(""click""));

    expect(component.selectedSubjects).toEqual([]);
  });

  it(""should be initialized invalid"", () =&gt; {
    expect(component.isValid()).not.toBeTruthy();
  });

  it(""should be valid if filled out"", () =&gt; {
    setupValidForm();
    fixture.detectChanges();

    expect(component.isValid()).toBeTruthy();
  });

  it(""should be invalid if no subject is selected"", () =&gt; {
    setupValidForm();
    component.selectedSubjects = [];
    fixture.detectChanges();
    expect(component.isValid()).not.toBeTruthy();
  });

  it(""should not be valid if email is not valid"", () =&gt; {
    setupValidForm();
    component.form.setValue({ ...component.form.value, email: ""test"" });
    fixture.detectChanges();
    expect(component.isValid()).not.toBeTruthy();
  });

  it(""should not be valid if email is empty"", () =&gt; {
    setupValidForm();
    component.form.setValue({ ...component.form.value, email: """" });
    fixture.detectChanges();
    expect(component.isValid()).not.toBeTruthy();
  });

  it(""should not be valid if password is empty"", () =&gt; {
    setupValidForm();
    component.form.setValue({ ...component.form.value, password: """" });
    fixture.detectChanges();
    expect(component.isValid()).not.toBeTruthy();
  });

  it(""should not be valid if agbs are not checked"", () =&gt; {
    setupValidForm();
    component.form.setValue({ ...component.form.value, agb: false });
    fixture.detectChanges();
    expect(component.isValid()).not.toBeTruthy();
  });

  // it(""should load until user registration is complete"", fakeAsync(() =&gt; {
  //   setupValidForm();
  //   let submitButton = registerStudent.querySelector&lt;HTMLButtonElement&gt;(
  //     ""main &gt; button""
  //   );
  //   submitButton.click();
  //   tick();
  //   expect(component.isLoading).toBeTruthy();
  // }));

  it(""should redirect to student profile after click on registration button"", fakeAsync(() =&gt; {
    setupValidForm();
    let submitButton = registerStudent.querySelector&lt;HTMLButtonElement&gt;(
      ""main &gt; button""
    );
    submitButton.click();
    tick();
    expect(location.path()).toBe(""/sch%C3%BCler"");
  }));
});

</code></pre>
",https://stackoverflow.com/questions/59016957/karma-how-to-debug-a-rangeerror-maximum-call-stack-size-exceeded,"['angular', 'unit-testing', 'debugging', 'testing', 'karma-jasmine']",7112,True,5,2
Should I be using the test classes on Android Studio?,"<p>Should I be using the test classes on Android Studio for my small application?
What can unit testing tell me that I can't already see in logs when I run the App? Can you give an example of something I should test by writing testing code rather than just manually testing stuff on my device?</p>
",https://stackoverflow.com/questions/57582195/should-i-be-using-the-test-classes-on-android-studio,"['android', 'unit-testing', 'testing']",30,False,0,1
Testing with Mocha Chai async function,"<p>I have a Hapi JS server with routes, this is my Hapi js Server</p>

<pre><code>const Hapi = require('hapi');

import { Users } from './users';

const port  3000;

const server = new Hapi.Server();

server.connection({ port });

export async function HapiServer() {

  server.route([
    {
      method: 'GET',

      path: '/getUsers',
      config: {
        handler: async (req: any, reply: any) =&gt; {
          try {


            await Users.getUsers(req.params.id)
              .then((result) =&gt; {
                reply(result);
              });
          } catch (error) {
            reply(error);
          }
        },



      },
    },
  ]);
  await server.start();
  console.log('server running at', server.info.port);
}


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

<p>I use Mocha and Chai for make a Unit Testing as follow:</p>

<pre><code>'use strict';
import { should } from 'chai';
import { HapiServer } from '../../server';
const chai = require('chai');
const chaiHttp = require('chai-http');

chai.use(chaiHttp);

describe('testing users ', () =&gt; {
    it('can get all users', async (done) =&gt; {
        const result = await chai
        .request(HapiServer)
            .get(/getUsers)
        .then((error, response) =&gt; {
            if (error) { done(error); }
            response.should.have.status(200);
            done();            
        }).catch(done);
    });
});
</code></pre>

<p>When run the test always have this:</p>

<pre><code>Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure ""done()"" is called; if returning a Promise, ensure it resolves. (./server.test.ts)
</code></pre>

<p>I already try change my mocha config in package.json </p>

<pre><code>mocha --timeout 10000
</code></pre>

<p>What could I be doing wrong? I understand that Mocha supports promises.</p>
",https://stackoverflow.com/questions/54848910/testing-with-mocha-chai-async-function,"['typescript', 'mocha.js', 'tdd', 'chai']",4199,True,0,1
How to get all the child elements inside a component in unit test using react and enzyme?,"<p>During unit testing, I am getting error:
 TeamMemberList › should show an empty section if the team has no members.</p>

<pre><code>expect(received).toBe(expected) // Object.is equality

Expected: 1
Received: 0
</code></pre>

<p>But the element is present in the component. Is there any way to get the structure of the component and see all the element present in it?</p>

<p>My component code (TeamMembersList.js) :</p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import React, { useState } from 'react'
import { withRouter } from 'react-router-dom'
import styled from 'styled-components'
import Card from '../../components/common/Card'
import { tiffanyBlueColor } from '../../styles'
import TeamMemberListItem from './TeamMemberListItem'
import Button from '../../components/common/Button'
import { AddMemberListItem } from './AddMemberListItem'
import { addUserToTeam } from '../create-team/EnterpriseCreateTeamActions'
import i18n from '../../i18n/i18n'
import EmptySection from '../../components/common/EmptySection'
import { FaUserSlash, FaInfoCircle } from 'react-icons/fa'
import { parsePhoneNumberFromString } from 'libphonenumber-js'

function TeamMembersList(props) {
  const [isAddingMember, setIsAddingMember] = useState(false)
  const [loadingAddingMember, setLoadingAddingMember] = useState(false)
  const [addMemberError, setAddMemberError] = useState('')
  const { team, loading } = props
  let users = []
  let teamId = ''
  if (team &amp;&amp; team.users) {
    users = Object.keys(team.users)
  }
  if (team &amp;&amp; team.id) {
    teamId = team.id
  }
  const onPressAddMember = () =&gt; {
    setIsAddingMember(true)
  }

  const onPressSave = async ({ phoneNumber, name }) =&gt; {
    setAddMemberError('')
    setLoadingAddingMember(true)
    try {
      const parsedNumber = parsePhoneNumberFromString(phoneNumber, 'NL')
      const response = await addUserToTeam({
        teamId,
        phoneNumber: parsedNumber.number,
        name
      })

      if (response.statusCode === 200) {
        setIsAddingMember(false)
      } else {
        if (response.code === 'already-exists') {
          const {
            currentTeam: { name: teamName }
          } = response.details
          setAddMemberError(
            i18n.t('enterprise.teamMember.UserAlreadyInTeam', { teamName })
          )
        } else {
          setAddMemberError(i18n.t('enterprise.teamMember.CouldNotAddUser'))
        }
      }
    } catch (error) {
      setAddMemberError(i18n.t('enterprise.teamMember.CouldNotAddUser'))
    } finally {
      setLoadingAddingMember(false)
    }
  }

  const onPressCancel = () =&gt; {
    setIsAddingMember(false)
    setLoadingAddingMember(false)
    setAddMemberError('')
  }
  const renderTooltip = () =&gt; {
    return (
      &lt;div&gt;
        &lt;FaInfoCircle
          data-tip={i18n.t('enterprise.teamMember.TooltipInfo')}
          size={20}
          color={tiffanyBlueColor}
        /&gt;
      &lt;/div&gt;
    )
  }
  return (
    &lt;Card
      title={i18n.t('enterprise.teamMember.TeamMembers')}
      containerStyle={{ minWidth: '1024px' }}
      renderHeaderRight={renderTooltip}
      isLoading={loading}
    &gt;
      &lt;UsersContentContainer&gt;
        {users.length === 0 ? (
          &lt;EmptySection
            text={i18n.t('enterprise.teamMember.NoTeamMembersYet')}
            Icon={FaUserSlash}
          /&gt;
        ) : null}
        {users.map(userId =&gt; (
          &lt;TeamMemberListItem userId={userId} key={userId} /&gt;
        ))}

        {isAddingMember ? (
          &lt;AddMemberListItem
            onPressCancel={onPressCancel}
            onPressSave={onPressSave}
            isLoading={loadingAddingMember}
            error={addMemberError}
          /&gt;
        ) : (
          &lt;AddMemberButtonContainer&gt;
            &lt;Button
              testId=""button-add-member""
              buttonText={i18n.t('enterprise.teamMember.AddMember')}
              onPress={onPressAddMember}
            /&gt;
          &lt;/AddMemberButtonContainer&gt;
        )}
      &lt;/UsersContentContainer&gt;
    &lt;/Card&gt;
  )
}
export default withRouter(TeamMembersList)

const UsersContentContainer = styled.div`
  flex-grow: 1;
  display: flex;
  justify-content: center;
  flex-direction: column;
`

const AddMemberButtonContainer = styled.div`
  margin-top: 0.5rem;
  width: 150px;
  align-self: flex-end;
`</code></pre>
</div>
</div>
</p>

<p>My component test code (TeamMembersList.test.js) :</p>

<pre><code> import React from 'react'
 import { BrowserRouter as Router } from 'react-router-dom'
 import { shallow } from 'enzyme'
 import { EmptySection } from '../../../components/common'
 import TeamMembersList from '../TeamMembersList'
 import TeamMemberListItem from '../TeamMemberListItem'

 describe('TeamMemberList', () =&gt; {
   beforeEach(() =&gt; {
      expect.hasAssertions()
      jest.clearAllMocks()
   })
   it('should show an empty section if the team has no members.', () =&gt; {
      const team = {
      name: 'Test team',
      phoneNumber: '+31851234567',
      status: 'active',
      users: {}
      }
      const loading = false
      const wrapper = shallow(
      &lt;Router&gt;
        &lt;TeamMembersList team={team} loading={loading} /&gt;
      &lt;/Router&gt;
      )

      expect(wrapper.find(EmptySection).length).toBe(1)
   })
 })
</code></pre>
",https://stackoverflow.com/questions/57785010/how-to-get-all-the-child-elements-inside-a-component-in-unit-test-using-react-an,"['reactjs', 'enzyme']",1215,True,0,2
How to perform unit testing on a void method in web api controller,"<p>Hi I have a update method in webAPI and that is a void method and I want to perform unit testing on that method.How do I do that??</p>

<p>Not Found any solution.</p>

<p>Below is webapi controller method :-</p>

<pre><code>[HttpPut]      
public void UpdatePushNotification(PushNotificationQueueBO pushnotificationqueueBO)
{
   PushNotificationQueueBO.UpdatePushNotificationQueue(pushnotificationqueueBO);
}
</code></pre>

<p>Below is the unit test case for above method</p>

<pre><code>[TestMethod]
public void UpdatePushNotificationQueue_ShouldUpdate()
{        
    var item = GetDemoPushNotificationQueue();      

    var controller = new PushNotificationQueueController();

    var result = controller.UpdatePushNotification(item) as ;

    Assert.IsNotNull(result);       
}
</code></pre>

<p>I want what do I write after as in </p>

<pre><code>var result = controller.UpdatePushNotification(item) as ???
</code></pre>
",https://stackoverflow.com/questions/57882700/how-to-perform-unit-testing-on-a-void-method-in-web-api-controller,"['asp.net-mvc', 'unit-testing', 'asp.net-web-api']",856,True,-1,2
Native element null at Angular test,"<p>I was trying to emulate a click inside my component for unit testing following Angular Documentation but for some reason my native element is returning empty: <code>HTMLButtonElement {}</code></p>

<p>At first I had to add the detectChanges function because of my ngIf but later on no changes were reflecting.</p>

<p>Here's also my HTML:</p>

<pre><code>&lt;div class=""money-transfer-options"" *ngIf=""card""&gt;
    &lt;div class=""alert alert__info"" role=""alert""&gt;
        &lt;i class=""nc nc-icon-alert-circle-i""&gt;&lt;/i&gt; Haremos un cargo con la cantidad seleccionada a la tarjeta con
        terminación:
        {{ card.card_number | bankAccountLastFourDigits }}
    &lt;/div&gt;

    &lt;form class=""money-transfer-options__form"" [formGroup]=""form"" (ngSubmit)=""onSubmit()""&gt;
        &lt;label
            [for]=""'moneyTransferAmount' + i""
            class=""money-transfer-options__card""
            *ngFor=""let amount of amounts; index as i""
            (click)=""toggleActiveClass(i)""
        &gt;
            &lt;input
                type=""radio""
                class=""money-transfer-options__card-radio""
                [id]=""'moneyTransferAmount' + i""
                [value]=""amount""
                formControlName=""amountTransfer""
                required
            /&gt;
            &lt;span class=""money-transfer-options__card-amount""&gt;
                &lt;span class=""money-transfer-options__card-icon""&gt;&lt;/span&gt;
                &lt;span class=""money-transfer-options__card-currency-symbol""&gt;$&lt;/span&gt;
                &lt;span class=""money-transfer-options__card-total""&gt;{{ amount | currency: 'MXN':'':'1.0-0' }}&lt;/span&gt;
                &lt;span class=""money-transfer-options__card-comission""&gt;
                    Comisión: &lt;br /&gt;
                    &lt;span class=""money-transfer-options__card-comission-amount""&gt;
                        {{ amount * commission + fee | currency: 'MXN':'symbol':'1.2-2' }}
                    &lt;/span&gt;
                &lt;/span&gt;
            &lt;/span&gt;
        &lt;/label&gt;
        &lt;button
            type=""submit""
            class=""button button__primary money-transfer-options__submit""
            aria-label=""Agregar fondos a mi cuenta""
            [disabled]=""!form.valid""
        &gt;
            Agregar Fondos
        &lt;/button&gt;
    &lt;/form&gt;

    &lt;small class=""money-transfer-options__disclaimer""&gt;
        *Las transacciones tardan en promedio hasta 5 minutos en verse reflejadas.
    &lt;/small&gt;
&lt;/div&gt;
</code></pre>

<p>Here's my spec.ts file:</p>

<pre><code>beforeEach(async(() =&gt; {
    const configure: ConfigureFn = testBed =&gt; {
        TestBed.configureTestingModule({
            imports: [ReactiveFormsModule],
            declarations: [MoneyTransferOptionsComponent, BankAccountLastFourPipe],
            providers: []
        }).compileComponents();
    };

    configureTests(configure).then(testBed =&gt; {
        fixture = testBed.createComponent(MoneyTransferOptionsComponent);
        component = fixture.componentInstance;
        component.card = expectedTokenizedCard;
        component.amounts = expectedAmounts;

        fixture.detectChanges();
    });
}));

it('should emit the payload for the request', async () =&gt; {
    component.card = expectedTokenizedCard;

    fixture.detectChanges();

    await fixture.whenStable();

    const submitButton = fixture.debugElement.query(By.css('.money-transfer-options__submit'));
    let submitButtonEl = submitButton.nativeElement;

    let testPayload: Common.TokenizedCardDeposit;

    console.log(submitButtonEl);


    //component.onFormSubmit.subscribe((payload: Common.TokenizedCardDeposit) =&gt; (testPayload = payload));

    //submitButtonEl.triggerEventHandler('click', null);
    // expect(testPayload).toBe(expectedPayload);
});
</code></pre>
",https://stackoverflow.com/questions/58289788/native-element-null-at-angular-test,"['angular', 'unit-testing', 'jestjs']",554,False,0,0
Providing/Injecting third party service to component while angular component unit testing,"<p>I have just started with Angular Unit testing, <code>LoginComponent</code> is dependent on third party module's (Fuse) service <code>FuseConfigService</code>. </p>

<p>Here is how <code>FuseConfigService</code> look like</p>

<pre><code>@Injectable({
    providedIn: 'root'
})
export class FuseConfigService
{
    private _configSubject: BehaviorSubject&lt;any&gt;;
    private readonly _defaultConfig: any;

    /**
     * Constructor
     *
     * @param {Platform} _platform
     * @param {Router} _router
     * @param _config
     */
    constructor(
        private _platform: Platform,
        private _router: Router,
        @Inject(FUSE_CONFIG) private _config
    )
    {
</code></pre>

<p>And here is how <code>LoginComponent</code> <code>constructor</code> look like</p>

<pre><code>constructor(
        private fuseConfig: FuseConfigService,
        private formBuilder: FormBuilder,
        private router: Router,
        private authenticationService: AuthService,
        private route: ActivatedRoute,
        private snackBar: MatSnackBar,
        private fuseNavigationService: FuseNavigationService,
        private pbiService: PbiService,
        private translateService: TranslateService
    ) {
        this.incorrectCredentials = false;
        this.loginFormErrors = {
            email: {},
            password: {},
        };
    }
</code></pre>

<p>I don't know how to configure testing module using TestBed, as it is throwing error like</p>

<pre><code>Error: StaticInjectorError(DynamicTestModule)[FuseConfigService -&gt; InjectionToken fuseCustomConfig]: 
  StaticInjectorError(Platform: core)[FuseConfigService -&gt; InjectionToken fuseCustomConfig]: 
    NullInjectorError: No provider for InjectionToken fuseCustomConfig!
</code></pre>

<p>This is what I am trying</p>

<pre><code>TestBed.configureTestingModule({
            declarations: [LoginComponent],
            imports: [FormsModule, ReactiveFormsModule, MatFormFieldModule,
                MatInputModule,
                MatCheckboxModule,
                MatSnackBarModule,
                MatButtonModule,
                MatRadioModule],
            providers: [
                FuseConfigService,
                { provide: Router, useClass: class { navigate = jasmine.createSpy(""navigate""); } },
                FuseNavigationService
            ]
        });
</code></pre>

<p>Any help will be appreciated.</p>
",https://stackoverflow.com/questions/57524902/providing-injecting-third-party-service-to-component-while-angular-component-uni,"['angular', 'unit-testing', 'dependency-injection', 'karma-jasmine']",1505,True,-1,1
Symfony 4.2 unit testing wont works,"<p>I am doing unit testing / functional testing, but my code gives me an error. Kindly have a look on my code and suggest a solution.</p>

<p>Codes On Controller</p>

<pre><code>    &lt;?php

namespace App\Controller;


use App\Entity\Organization;
use App\Entity\User;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Psr\Log\LoggerInterface;
use Swift_Mailer;
use Swift_Message;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

class RegisterController extends AbstractController
{

    protected $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this-&gt;logger = $logger;
    }

    /**
     * Validate the data
     * Encodes the password
     * Creates new organization if evaplyId does not exists
     * Create user and send verification email.
     * return status
     *
     * @param Request $request
     * @param UserPasswordEncoderInterface $userPasswordEncoder
     * @param ValidatorInterface $validator
     * @param Swift_Mailer $mailer
     * @return Response
     */
    public function register(Request $request, UserPasswordEncoderInterface $userPasswordEncoder, ValidatorInterface $validator, Swift_Mailer $mailer)
    {
        try {
            $form = $request-&gt;getContent();
            $form = json_decode($form);
            $entityManager = $this-&gt;getDoctrine()-&gt;getManager(); //doctrine manager for entity managing
            $user = new User();
            $user-&gt;setEmail($form-&gt;email);
            if (!$this-&gt;checkEmail($form-&gt;email)) {
                return new JsonResponse(['status' =&gt; false, 'message' =&gt; 'Email already exists']);
            }
            $user-&gt;setFirstName($form-&gt;first_name);
            $user-&gt;setLastName($form-&gt;last_name);
            $user-&gt;setPassword($form-&gt;plain_password);
            if (!$form-&gt;evaply_id) {
                if(!$form-&gt;organization_name)
                    return new JsonResponse(['status' =&gt; false, 'message' =&gt; 'Missing field Organization']);
                $organization = new Organization();
                $organization-&gt;setName($form-&gt;organization_name);
                $startGuideStatus['status'] = false;
                $startGuideStatus['add_company'] = false;
                $startGuideStatus['first_connection'] = false;
                $startGuideStatus['first_scorecard'] = false;
                $startGuideStatus['first_order'] = false;
                $organization-&gt;setStartGuideStatus(($startGuideStatus));
                $organization-&gt;setCustOrSupplier($form-&gt;cust_or_supplier);
                $evaply_id = $this-&gt;generateEvaplyId($form-&gt;organization_name);
                $organization-&gt;setEvaplyId($evaply_id);
                $entityManager-&gt;persist($organization);
                $entityManager-&gt;flush();
            } else {
                $organization = $this-&gt;getDoctrine()-&gt;getRepository(Organization::class)-&gt;findOneBy(array('evaplyId' =&gt; $form-&gt;evaply_id));
                if (!$organization) {
                    return new JsonResponse(['status' =&gt; false, 'message' =&gt; 'Invalid Evaply ID']);
                }
            }
            $user-&gt;setOrganization($organization);
            $user-&gt;setUuid($this-&gt;generateUUID());
            $user-&gt;setRoles(['Admin']);
            $error = $validator-&gt;validate($user);
            if (count($error) &gt; 0) {
                return new JsonResponse(['status' =&gt; false, 'message' =&gt; 'Validation error']);
            }
            if ($form-&gt;plain_password != $form-&gt;confirm_password) {
                return new JsonResponse(['status' =&gt; false, 'message' =&gt; 'Password miss match']);
            }
            $user-&gt;setPassword(
                $userPasswordEncoder-&gt;encodePassword(
                    $user,
                    $form-&gt;plain_password
                )
            );
            $token = $this-&gt;generateVerificationToken($user);
            $this-&gt;logger-&gt;info($token);
            $verificationUrl = $this-&gt;getParameter('app_url') . ""account/verify/"" . $token;
            $entityManager = $this-&gt;getDoctrine()-&gt;getManager();
            $entityManager-&gt;persist($user);
            $entityManager-&gt;flush();
            $this-&gt;sendUserRegisteredMail($user, $verificationUrl, $mailer);

            return new JsonResponse(['status' =&gt; true, 'message' =&gt; ""Successfully registered""]);
        } catch (\Exception $e) {
            $this-&gt;logger-&gt;error($e-&gt;getMessage());
            return new Response($e-&gt;getMessage());
        }
    }

    /**
     * Check email duplication in database
     *
     * @param $email
     * @return bool
     */
    public function checkEmail($email)
    {
        $user = $this-&gt;getDoctrine()-&gt;getRepository(User::class)-&gt;findOneBy(array('email' =&gt; $email));
        if ($user)
            return false;
        else
            return true;
    }

    /**
     * Generate a unique id using organization name and timestamp
     *
     * @param $orgName
     * @return string
     */
    public function generateEvaplyId($orgName)
    {
        $org = strtoupper(substr($orgName, 0, 3));
        $dateTime = time();
        $evaply_id = $org . $dateTime;
        return $evaply_id;
    }

    /**
     * Generate unique uuid for user
     * Recursive function
     *
     * @return int
     */
    public function generateUUID()
    {
        $uuid = rand(1000000000, 9999999999);
        $user = $this-&gt;getDoctrine()-&gt;getRepository(User::class)-&gt;findOneBy(array('uuid' =&gt; $uuid));
        if ($user) {
            return $this-&gt;generateUUID();
        } else {
            return $uuid;
        }
    }

    /**
     * Send email to user after a successfull registartion.
     *
     * @param User $user
     * @param Swift_Mailer $mailer
     * @return int
     */
    public function sendUserRegisteredMail(User $user, $verificationUrl, Swift_Mailer $mailer)
    {
        $message = (new Swift_Message(""Successfully Registered""))
            -&gt;setFrom('admin@evaply.com')
            -&gt;setTo($user-&gt;getEmail())
            -&gt;setBody(
                $this-&gt;renderView(
                    'emails/registration.html.twig',
                    array('firstName' =&gt; $user-&gt;getFirstName(), 'lastName' =&gt; $user-&gt;getLastName(), 'verificationUrl' =&gt; $verificationUrl)
                ),
                'text/html'
            );
        return $mailer-&gt;send($message);
    }

    /**
     * Generates a verification token using aes-128-gcm encryption
     * encrypts email and uuid
     * encode ciphertext with base64 encoder
     *
     * @param User $user
     * @return string
     */
    public function generateVerificationToken(User $user)
    {
        $data = array();
        $data['email'] = $user-&gt;getEmail();
        $data['uuid'] = $user-&gt;getUuid();
        $plaintext = json_encode($data);
        $cipher = $this-&gt;getParameter('cipher');
        if (in_array($cipher, openssl_get_cipher_methods())) {

            $this-&gt;logger-&gt;info(""inside cipher"");
            //$ivlen = openssl_cipher_iv_length($cipher);
            $iv = $this-&gt;getParameter('secretIV');
            $key = $this-&gt;getParameter('cipher_key');
            //$tag = $this-&gt;getParameter('tagg');
            $ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options = 0, $iv);
            $original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options = 0, $iv);
            return $token = base64_encode($ciphertext);
        }
    }
}
</code></pre>

<p>Codes On Tests/Controller Folder</p>

<pre><code>   &lt;?php
/**
 * Created by PhpStorm.
 * User: xavier-phases
 * Date: 22/1/19
 * Time: 5:09 PM
 */

namespace App\Tests\Controller;
use App\Controller\RegisterController;
use PHPUnit\Framework\TestCase;

class EvaplyTest extends TestCase
{

    public function testGenerate_evaply_clid(LoggerInterface $logger)
    {
        $id= new RegisterController();
        $org_name=$id-&gt;generateEvaplyId('Tset');
        $org = strtoupper(substr($org_name, 0, 3));
        $dateTime = time();
        $evaply_id = $org . $dateTime;
        return $evaply_id;
    }
}`
</code></pre>

<p>I am calling the <code>generateEvaplyId()</code> method from the register controller. I have installed all test packages. It gives me the following error:</p>

<pre><code>""ArgumentCountError: Too few arguments to function App\Tests\Controller\EvaplyTest::testGenerate_evaply_clid(), 0 passed and exactly 1 expected"".  KIndly have a look and suggest me a solution.
</code></pre>
",https://stackoverflow.com/questions/54320076/symfony-4-2-unit-testing-wont-works,"['php', 'unit-testing', 'symfony', 'functional-testing']",1008,True,-2,1
PHP Unit test assertJSON(,"<p>When unit testing a JSON response I am using assertJson(...)</p>

<pre><code>assertJson([
                $booking1-&gt;only(['user_id', 'service_id','start', 'end']), 
                $booking2-&gt;only(['user_id', 'service_id','start', 'end']), 
                $booking3-&gt;only(['user_id', 'service_id','start', 'end']), 
                $booking4-&gt;only(['user_id', 'service_id','start', 'end']),
            ]);
</code></pre>

<p>My failure message is:</p>

<pre><code>Failed asserting that an array has the subset Array &amp;0 (
0 =&gt; Array &amp;1 (
    'user_id' =&gt; 25
    'service_id' =&gt; 16
    'start' =&gt; '2019-12-02 09:41:58'
    'end' =&gt; '2019-12-02 09:56:58'       
)
1 =&gt; Array &amp;2 (
    'user_id' =&gt; 25
    'service_id' =&gt; 16
    'start' =&gt; '2019-12-02 10:26:58'
    'end' =&gt; '2019-12-02 10:36:58'        
)
2 =&gt; Array &amp;3 (
    'user_id' =&gt; 26
    'service_id' =&gt; 16
    'start' =&gt; '2019-12-02 09:41:58'
    'end' =&gt; '2019-12-02 09:56:58'        
)
3 =&gt; Array &amp;4 (
    'user_id' =&gt; 26
    'service_id' =&gt; 16
    'start' =&gt; '2019-12-02 10:26:58'
    'end' =&gt; '2019-12-02 10:36:58'        
)
).
--- Expected
+++ Actual
@@ @@
 array (
-  0 =&gt;
-  array (
-    'user_id' =&gt; 25,
-    'service_id' =&gt; 16,
-    'start' =&gt; '2019-12-02 09:41:58',
-    'end' =&gt; '2019-12-02 09:56:58',
-  ),
-  1 =&gt;
-  array (
-    'user_id' =&gt; 25,
-    'service_id' =&gt; 16,
-    'start' =&gt; '2019-12-02 10:26:58',
-    'end' =&gt; '2019-12-02 10:36:58',
-  ),
-  2 =&gt;
-  array (
-    'user_id' =&gt; 26,
-    'service_id' =&gt; 16,
-    'start' =&gt; '2019-12-02 09:41:58',
-    'end' =&gt; '2019-12-02 09:56:58',
-  ),
-  3 =&gt;
-  array (
-    'user_id' =&gt; 26,
-    'service_id' =&gt; 16,
-    'start' =&gt; '2019-12-02 10:26:58',
-    'end' =&gt; '2019-12-02 10:36:58',
-  ),
 )
</code></pre>

<p>There are a few differences here ""Array &amp;0 ( vs array ("" Other than that the data look to be the same. </p>

<p>Can anyone tell me what the significance of these differences are? Or am I missing something else here as well? </p>

<p>Thanks</p>
",https://stackoverflow.com/questions/59136125/php-unit-test-assertjson,"['php', 'laravel', 'phpunit']",465,False,0,1
How to verify store function call?,"<p>Start practices unit testing.</p>

<p>And faced with such problem:
I am trying to test store method call.</p>

<p>When I run this test:</p>

<pre class=""lang-js prettyprint-override""><code>
import * as React from 'react';
import {observer} from 'mobx-react';
import {mount} from 'enzyme';
import {instance, mock, verify, when} from 'ts-mockito';

class TestStore {
    onClick = () =&gt; {};
}

interface Props {
    store: any;
}

@observer
export class Test extends React.Component&lt;Props, any&gt; {
    render() {
        return (
            &lt;div
                className={'test'}
                onClick={this.props.store.onClick}/&gt;
        );
    }
}

describe('onclick test', () =&gt; {
    let testStoreMocked: any;
    let testStoreInst: any;
    let testElem: any;

    beforeEach(() =&gt; {
        testStoreMocked = mock(TestStore);
        testStoreInst = instance(testStoreMocked);
        testElem = mount&lt;Test&gt;(&lt;Test
            store={testStoreInst}
        /&gt;);
    });

    test('test', () =&gt; {
        when(testStoreMocked.onClick).thenReturn();
        console.log(testElem.find('div.test').html());
        testElem.find('div.test').simulate('click');
        verify(testStoreMocked.onClick()).once();
    });
});
</code></pre>

<p>but have such error</p>

<pre><code>Expected ""onClick()"" to be called 1 time(s). But has been called 0 time(s).

      50 |         console.log(testElem.find('div.test').html());
      51 |         testElem.find('div.test').simulate('click');
    &gt; 52 |         verify(testStoreMocked.onClick()).once();
         |                                           ^
      53 |     });
      54 | });

</code></pre>

<p>If I wrap store method by component method like this:</p>

<pre class=""lang-js prettyprint-override""><code>import * as React from 'react';
import {observer} from 'mobx-react';
import {mount} from 'enzyme';
import {instance, mock, verify, when} from 'ts-mockito';

class TestStore {
    onClick = () =&gt; {};
}

interface Props {
    store: any;
}

@observer
export class Test extends React.Component&lt;Props, any&gt; {
    onClick = () =&gt; {
        this.props.store.onClick();
    };

    render() {
        return (
            &lt;div
                className={'test'}
                onClick={this.onClick}/&gt;
        );
    }
}

describe('onclick test', () =&gt; {
    let testStoreMocked: any;
    let testStoreInst: any;
    let testElem: any;

    beforeEach(() =&gt; {
        testStoreMocked = mock(TestStore);
        testStoreInst = instance(testStoreMocked);
        testElem = mount&lt;Test&gt;(&lt;Test
            store={testStoreInst}
        /&gt;);
    });

    test('test', () =&gt; {
        when(testStoreMocked.onClick).thenReturn();
        console.log(testElem.find('div.test').html());
        testElem.find('div.test').simulate('click');
        verify(testStoreMocked.onClick()).once();
    });
});
</code></pre>

<p>Test passed and all is fun.
Is there any possibility to verify store method without wrapping it by component method?</p>
",https://stackoverflow.com/questions/56662421/how-to-verify-store-function-call,"['reactjs', 'typescript', 'jestjs', 'ts-mockito']",357,False,1,1
How to test if a function inside function called with right parameter,"<p>I got this kind of function:</p>

<pre class=""lang-js prettyprint-override""><code>const plus1 = x =&gt; x + 1;

const plus2 = x =&gt; x + 2;

const returnPlus1OrPlus2 = (number, code) =&gt;
  code === 1 ? plus1(number * 3) : plus2(number);
// if the parameter code is 1 then call function plus1 with param number*3,
// if not then just call function plus2 with param number

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

<p>I have to create a unit testing using jest for that function and I need to test if the function <code>returnPlus1OrPlus2</code> calls the right function whether <code>plus1</code> or <code>plus2</code> based on the parameter code invoked.</p>

<pre><code>    test('function returnPlus1OrPlus2 should call function plus1'()=&gt;{
        expect(returnPlus1OrPlus2(2, 1)).toBe(7);
        //expect(function plus 1 was called with 6)
    })
</code></pre>

<p><em>How to mock functions <code>plus1</code> and <code>plus2</code> and write something like this in test?</em></p>

<blockquote>
  <p>//expect(function <code>plus1</code> was called with <strong>6</strong>)</p>
</blockquote>
",https://stackoverflow.com/questions/59168766/how-to-test-if-a-function-inside-function-called-with-right-parameter,['jestjs'],89,True,1,1
vcpkg: Specify struct member alignment,"<p>I have some old code which is compiled with packing of 1-byte (argument <code>/Zp1</code>) <a href=""https://learn.microsoft.com/en-us/cpp/build/reference/zp-struct-member-alignment?view=vs-2019"" rel=""nofollow noreferrer"">Struct Member Alignment</a> and I'm adding unit testing with gTest to them. I'm using <code>vcpkg</code> to install gTest, but it is compiled using the default setting of 8-byte packing. I'm on Windows with VS2019.</p>

<p>Is it possible to specify which packing to use (parameter <code>/Zp</code>) with <code>vcpkg</code>?</p>
",https://stackoverflow.com/questions/58458811/vcpkg-specify-struct-member-alignment,"['c++', 'visual-studio', 'vcpkg', 'struct-member-alignment']",103,False,1,1
Testing subscriptions for Angular 8 ngOnInit,"<p>I am trying to learn angular unit testing with Karma and Jasmine.</p>

<p>My problem is that when I try to test the component is created, I get: 'TypeError: Cannot read property 'subscribe' of undefined'
Because I have subscriptions in the ngOnInit() and I dont know how to test subscriptions inside a method.</p>

<p>Thanks for your help :)</p>
",https://stackoverflow.com/questions/58408520/testing-subscriptions-for-angular-8-ngoninit,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",591,True,1,1
How to mock a callback function for testing which is inside the arguments of another function,"<p>My requirement is to mock the callback function which is inside the arguments of another function for unit testing.</p>

<pre><code> var jwt = require(""jsonwebtoken"");
 var APICall = require('./requestFile');

 function Helper(){
 this.request = new APICall();
  }

 Helper.prototype.getData = function (done) {
    var headers = {
        'content-type': ""application/json"",
    };
    var _self = this;
    this.request.get(this.pub_URL, get_headers, function (err, res, body) {
        if (!err &amp;&amp; res.statusCode === 200) {
            console.log(""Got data: "", body);
            done(null, body);
        }
        else {
            console.log(""Error occured while fetching data: "" + err)
            done(err, null);
        }
    });
  }
 }
</code></pre>

<p>I want to mock the callback function which this.request.get() calls as an argument so that my testing can cover the else block 
        console.log(""Error occured while fetching data: "" + err).</p>

<p>Here is my test file with the code base </p>

<pre class=""lang-js prettyprint-override""><code>const Helper = require('../Helper');
var APICall = require('../requestFile');

let hlp = new Helper();

describe('APP', function() {
  before(function() {
    let res = {
      statusCode: 500
    }
    let err = {
      message: 'errors present'
    };
    var get_headers = {
      'content-type': ""application/json"",
    };
    sinon.stub(APICall.prototype, 'get').callsFake(function(done) {
      done(err, res)
    })

  })

  after(function() {
    APIRequester.prototype.get.restore();
  });
  it('should tell errors when request gets called for', function(done) {

    hlp.getData(function(err, data) {
      expect(data).to.be.a('string')
      done()
    })
  })

})
</code></pre>


",https://stackoverflow.com/questions/56827977/how-to-mock-a-callback-function-for-testing-which-is-inside-the-arguments-of-ano,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'chai']",779,False,1,1
console.log(Wrapper.debug()) showing &lt;ContextConsumer&gt; [function] &lt;/ContextConsumer&gt;,"<p>I am using jest and enzyme for the unit testing in the react js.
When I console log the wrapper returned by shallow function by using ""console.log(wrapper.debug())"" it returns [function] and  I am not able to find attribute in the component.</p>

<p>This is my signUp component</p>

<p>signUp.js</p>

<pre><code>import React, { Component } from 'react'
import { withStyles, Card, CardContent, Typography, MenuItem } from '@material-ui/core';
import { darken } from '@material-ui/core/styles/colorManipulator';
import { FuseAnimate } from '@fuse';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux';
import { Link, withRouter } from 'react-router-dom';
import classNames from 'classnames';
import * as Actions from '../../../auth/store/actions/register.actions';
import * as FuseActions from '../../../store/actions/fuse/message.actions';
import Formsy from 'formsy-react';
import { TextFieldFormsy } from '@fuse';
import { Button, InputAdornment, Icon, Grid } from '@material-ui/core';


const styles = theme =&gt; ({
    root: {
        background: 'linear-gradient(to right, ' + theme.palette.primary.dark + ' 0%, ' + darken(theme.palette.primary.dark, 0.5) + ' 100%)',
        color: theme.palette.primary.contrastText
    }
});

class SignUp extends Component {

    render() {
        const { classes } = this.props;
        const { canSubmit } = this.state;

        return (
            &lt;div data-test=""data-component"" className={classNames(classes.root, ""flex flex-col flex-1 flex-no-shrink p-24 md:flex-row md:p-0"")}&gt;
               .........
            &lt;/div&gt;
        )
    }
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        userSignup: Actions.userSignup,
        disableErrors: Actions.disableErrors,
        showMessage: FuseActions.showMessage
    }, dispatch);
}

function mapStateToProps({ auth }) {
    return {
        register: auth.register
    }
}


export default withStyles(styles, { withTheme: true })(withRouter(connect(mapStateToProps, mapDispatchToProps)(SignUp)));


</code></pre>

<p>This is test file</p>

<p>signUp.test.js</p>

<pre><code>import React from 'react';

import { configure, shallow } from 'enzyme';

import Adapter from 'enzyme-adapter-react-16';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';

import SignUp from './signUp';
import AppContext from '../../../AppContext';

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

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

const setup = (initialState = {}) =&gt; {
    const store = mockStore(initialState);
    const wrapper = shallow(&lt;SignUp store={store} /&gt;).dive().dive();
    console.log(wrapper.debug());

    return wrapper;
}

const findAttrByTest = (wrapper, val) =&gt; {
    return wrapper.find(`[data-test=""${val}""]`);
}

describe(""render &lt;SignUp&gt;"", () =&gt; {
    let wrapper;
    beforeEach(() =&gt; {
        const initialState = {
            error: '',
            success: false
        };
        wrapper = setup(initialState);
    });
    test(""render component without error"", () =&gt; {
        const component = findAttrByTest(wrapper, 'data-component');
        expect(component.length).toBe(1);
    });
});
</code></pre>

<p>Test result is</p>

<pre><code>
 FAIL  signUp.test.js (5.199s)
  render &lt;SignUp&gt;
    ✕ render component without error (45ms)

  ● render &lt;SignUp&gt; › render component without error

    expect(received).toBe(expected) // Object.is equality

    Expected: 1
    Received: 0

      43 |     test(""render component without error"", () =&gt; {
      44 |         const component = findAttrByTest(wrapper, 'data-component');
    &gt; 45 |         expect(component.length).toBe(1);
         |                                  ^
      46 |     });
      47 | });
      48 | 

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        6.722s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.  console.log signUp.test.js:24
    &lt;ContextConsumer&gt;
      [function]
    &lt;/ContextConsumer&gt;

</code></pre>
",https://stackoverflow.com/questions/56168151/console-logwrapper-debug-showing-contextconsumer-function-contextconsu,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",3256,True,1,1
"How to properly mock Hibernate Session get(Class&lt;T&gt; entityType, Serializable id)","<p>I'm unit testing my Hibernate DAO layer with jUnit4 and Mockito and I'm having problems mocking <code>get(Class&lt;T&gt; entityType, Serializable id)</code>.</p>

<p>I have no errors along the way, the only thing is that my assertion fails as <code>actualAddress</code> is <code>null</code>.</p>

<pre><code>// imports here
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = ""classpath:applicationContext.xml"")
public class AddressDAOImplTest {

    @Autowired
    @InjectMocks
    private AddressDAO addressDAO;

    @Mock
    private SessionFactory sessionFactory;

    @Mock
    private Session session;

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

    @Test
    public void getAddress() {
        Address expectedAddress = getTestAddress(1);
        Mockito
                .doReturn(session)
                .when(sessionFactory)
                .openSession();
        Mockito
                .doReturn(expectedAddress)
                .when(session)
                .get(Matchers.eq(Address.class), Matchers.anyInt()); // doesn't match
        Mockito
                .doNothing()
                .when(session)
                .close();

        Address actualAddress = addressDAO.getAddress(1);

        Assert.assertEquals(expectedAddress, actualAddress);
    }
}
</code></pre>

<p>somewhere AddressDAOImpl:</p>

<pre><code>public Address getAddress(Integer id) {
        Session session = sessionFactory.openSession();
        Address address = null;
        try {
            address = session.get(Address.class, id); // returns null as it can't match the mocked method
        } catch (Exception e) {
            // some logging here :)
        } finally {
            session.close();
            return address;
        }
    }
</code></pre>

<p>SessionFactory setup:</p>

<pre><code>&lt;bean id=""sessionFactory""
          class=""org.springframework.orm.hibernate5.LocalSessionFactoryBean""&gt;
        &lt;property name=""dataSource"" ref=""dataSource""/&gt;
        &lt;property name=""packagesToScan"" value=""com.webservices.models""/&gt;
        &lt;property name=""hibernateProperties""&gt;
            &lt;props&gt;
                &lt;prop key=""hibernate.hbm2ddl.auto""&gt;${hibernate.hbm2ddl.auto}&lt;/prop&gt;
                &lt;prop key=""hibernate.dialect""&gt;${hibernate.dialect}&lt;/prop&gt;
                &lt;prop key=""hibernate.show_sql""&gt;${hibernate.show_sql}&lt;/prop&gt;
            &lt;/props&gt;
        &lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=""dataSource""
          class=""org.apache.tomcat.dbcp.dbcp2.BasicDataSource""&gt;
        &lt;property name=""driverClassName"" value=""${jdbc.driverClassName}""/&gt;
        &lt;property name=""url"" value=""${jdbc.url}""/&gt;
        &lt;property name=""username"" value=""${jdbc.username}""/&gt;
        &lt;property name=""password"" value=""${jdbc.password}""/&gt;
    &lt;/bean&gt;

    &lt;bean id=""transactionManager""
          class=""org.springframework.orm.hibernate5.HibernateTransactionManager""&gt;
        &lt;property name=""sessionFactory"" ref=""sessionFactory""/&gt;
    &lt;/bean&gt;
</code></pre>

<p>Hibernate props:</p>

<pre><code>jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:orders;DB_CLOSE_DELAY=-1
jdbc.username=
jdbc.password=

hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.hbm2ddl.auto=create-drop
hibernate.show_sql=true

</code></pre>

<p>To my understanding <code>get(Matchers.eq(Address.class), Matchers.anyInt())</code> doesn't match the actual method, which leads to <code>null</code> as a return value. </p>

<p>I'd greatly appreciate your help!</p>
",https://stackoverflow.com/questions/58206112/how-to-properly-mock-hibernate-session-getclasst-entitytype-serializable-id,"['java', 'spring', 'hibernate', 'unit-testing', 'mockito']",415,False,1,0
Unit testing Authorization header interceptor in angular not working,"<p><strong>error: Expected one matching request for criteria ""Match by function: "", found none.</strong>
I searched for many things and tried a few solutions. But none of them worked. This is my first project for unit testing. Here's my code.</p>

<p><strong>Auth Interceptor</strong></p>

<pre><code>export const API_URL = new InjectionToken&lt;string&gt;('apiUrl');
export class JwtInterceptor implements HttpInterceptor {
  constructor(@Inject(API_URL) private apiUrl: string) {
  }

  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {

request = request.clone({url: this.prepareUrl(request.url)});

let authToken = localStorage.getItem('auth_token');
if (authToken) {
  request = request.clone({
    setHeaders: {
      Authorization: `Bearer ${authToken}`
    }
  });
}
else {
  // use proxy url for cors error
  request = request.clone({url: this.prepareUrl('https://cors-anywhere.herokuapp.com/' + request.url)});
  // Encode the String
  let encodedString = btoa(`${environment.clientId}:${environment.clientSecret}`);
  request = request.clone({
    setHeaders: {
      Authorization: `Basic ${encodedString}`
    }
  });
}
return next.handle(request);

}

  private isAbsoluteUrl(url: string): boolean {
    const absolutePattern = /^https?:\/\//i;
    return absolutePattern.test(url);
  }

  private prepareUrl(url: string): string {
    url = this.isAbsoluteUrl(url) ? url : this.apiUrl + '/' + url;
    return url.replace(/([^:]\/)\/+/g, '$1');
  }

}
</code></pre>

<p><strong>Auth Interceptor Spec</strong></p>

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

let httpTestingController: HttpTestingController;
  let http: HttpClient;      

  beforeEach(()=&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [{
          provide: HTTP_INTERCEPTORS,
          useClass: JwtInterceptor,
          multi: true
        }]
    });

httpTestingController = TestBed.get(HttpTestingController);
http = TestBed.get(HttpClient);
 });

  it('should add Authorization header in each request', ()=&gt; {
http.get('/data').subscribe(response =&gt; {
  expect(response).toBeTruthy();
});

const req = httpTestingController.expectOne(
  req =&gt; req.headers.has('Authorization')
);
expect(req.request.headers.has('Authorization')).toEqual(true);
expect(req.request.method).toEqual('GET');

req.flush({hello: 'world'});
 });    
  afterEach(()=&gt; {
    httpTestingController.verify();
  });    
});
</code></pre>

<p>I also tried by setting authorization headers using mock service. Can anyone help me what I am missing here?</p>
",https://stackoverflow.com/questions/54129330/unit-testing-authorization-header-interceptor-in-angular-not-working,"['javascript', 'angular', 'unit-testing', 'karma-jasmine', 'angular-http-interceptors']",3480,True,4,2
"org.springframework.core.convert.converter.Converter&lt;S, T&gt; give error: Null can not be a value of a non-null type","<p>I try to implement Spring Converter, but I had got the error in unit testing:</p>

<pre><code>Kotlin: Null can not be a value of a non-null type TodoItem
</code></pre>

<p>If I try to change convert method signature from </p>

<pre><code>override fun convert(source: TodoItem): GetTodoItemDto?
</code></pre>

<p>to </p>

<pre><code>override fun convert(source: TodoItem?): GetTodoItemDto?
</code></pre>

<p>that pass null to method I have other errors:</p>

<pre><code>Error:(10, 1) Kotlin: Class 'TodoItemToGetTodoItemDto' is not abstract and does not implement abstract member @Nullable public abstract fun convert(p0: TodoItem): GetTodoItemDto? defined in org.springframework.core.convert.converter.Converter
Error:(14, 5) Kotlin: 'convert' overrides nothing
</code></pre>

<p>Code samples: </p>

<p><strong>TodoItemToGetTodoItemDto.kt</strong></p>

<pre><code>package com.example.todo.converters

import com.example.todo.dtos.todo.GetTodoItemDto
import com.example.todo.model.TodoItem
import org.springframework.core.convert.converter.Converter
import org.springframework.lang.Nullable
import org.springframework.stereotype.Component

@Component
class TodoItemToGetTodoItemDto : Converter&lt;TodoItem?, GetTodoItemDto&gt; {

    @Nullable
    @Synchronized
    override fun convert(source: TodoItem): GetTodoItemDto? {
        if(source == null){
            return null
        }

        return GetTodoItemDto(source.id, source.name, source.isComplete)
    }

}
</code></pre>

<p><strong>TodoItemToGetTodoItemDtoTest.kt</strong></p>

<pre><code>package com.example.todo.converters

import org.junit.Before
import org.junit.Test

import org.junit.Assert.*


class TodoItemToGetTodoItemDtoTest {
    private lateinit var conveter : TodoItemToGetTodoItemDto

    @Before
    fun setUp() {
        conveter = TodoItemToGetTodoItemDto()
    }

    @Test
    fun testNullObject(){
        assertNull(conveter.convert(null))
    }

}
</code></pre>

<p><strong>GetTodoItemDto.kt</strong></p>

<pre><code>package com.example.todo.dtos.todo

data class GetTodoItemDto(val id: Long, val name: String, val isComplete: Boolean)
</code></pre>

<p><strong>TodoItem.kt</strong></p>

<pre><code>package com.example.todo.model

import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id

@Entity
data class TodoItem @JsonCreator constructor(
        @Id
        @GeneratedValue
        @JsonProperty(access = JsonProperty.Access.READ_ONLY)
        var id: Long,
        var name: String,
        var isComplete: Boolean){
    constructor(): this(0, """", false)
    constructor(name:String) : this(0, name, false)
}
</code></pre>

<p>Could you explain to me how it is possible to implement using Kotlin? May be I do something wrong using Kotlin?</p>
",https://stackoverflow.com/questions/56055259/org-springframework-core-convert-converter-converters-t-give-error-null-can,"['spring', 'kotlin']",874,True,4,1
Missing symbols – but symbols exist?,"<p>I'm trying to compile a unit testing target using googletest. While it works in one project, it is failing to link in a different project, and I'm struggling to understand why.</p>

<p>The <code>link.txt</code> generated by CMake:</p>

<pre><code>/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++  -stdlib=libc++ -std=gnu++11 -g -Wl,-search_paths_first -Wl,-headerpad_max_install_names  CMakeFiles/runTests.dir/ATAppTests.cpp.o  -o runTests ../../src/targetLib.a ../../lib/libgtestd.a ../../lib/libgtest_maind.a ../../lib/libgmockd.a ../../lib/libgmock_maind.a ../../lib/libgmockd.a ../../lib/libgtestd.a 
</code></pre>

<p>The result of running that command:</p>

<pre><code>Undefined symbols for architecture x86_64:
  ""testing::internal::MakeAndRegisterTestInfo(char const*, char const*, char const*, char const*, void const*, void (*)(), void (*)(), testing::internal::TestFactoryBase*)"", referenced from:
      ___cxx_global_var_init in ATAppTests.cpp.o
</code></pre>

<p>However, running <code>nm</code> indicates the symbol is there:</p>

<pre><code> $ nm --demangle ../../lib/libgtestd.a | grep 'MakeAndRegister'
000000000000ebe0 T testing::internal::MakeAndRegisterTestInfo(char const*, char const*, char const*, char const*, testing::internal::CodeLocation, void const*, void (*)(), void (*)(), testing::internal::TestFactoryBase*)
</code></pre>

<p>I'm not sure where to go from here!</p>
",https://stackoverflow.com/questions/56656872/missing-symbols-but-symbols-exist,"['c++', 'cmake', 'googletest']",244,True,1,2
Autowiring fails in Junit testing and spring @configuration,"<p>I have two <code>@Configuration</code> classes. I need a bean from one configuration class to another. I have autowired the configuration 1 into 2. All works fine. When executing the unit testing, am getting the below exception.</p>

<pre><code>setUpContext(com.trafigura.titan.framework.services.messaging.loader.SpringLoadTest)
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.xxx.MessagingServicesConfig': Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xxx.EMSJMSConfig com.xxx.MessagingServicesConfig.emsJmsConfig; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type[com.xxx.EMSJMSConfig] found for dependency: 
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code></pre>

<p>Is there anything I need to do additionally to make this working? </p>

<p>Below is the setup for testing.</p>

<pre><code>@Configuration
@Import({MessagingServicesConfig.class,...,EMSJMSConfig.class
})
public class MessagingConfig {}

@Profile(""EMS-MESSAGING"")
@Configuration
public class EMSJMSConfig {
    @Bean
    public javax.jms.ConnectionFactory jmsSubscriberConnectionFactory() throws JMSException {
        SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory(tibjmsConnectionFactory());
        return singleConnectionFactory;
    }
}

@Configuration
public class MessagingServicesConfig {
    @Autowired
    private EMSJMSConfig emsJmsConfig;
    @Bean(destroyMethod = ""shutdown"")
    public MessagingService messagingService() throws JMSException {
        ...
        ConnectionFactory cf=emsJmsConfig.jmsSubscriberConnectionFactory(); // Getting NPE at this line.
    }
}
</code></pre>

<p>and finally the test class,</p>

<pre><code>public class MessagingServicesConfigTest {
    private MessagingServicesConfig config;
    private EMSJMSConfig emsJmsConfig;
    @BeforeMethod
    public void setUp() throws Exception {
        config = new MessagingServicesConfig();
        ... //what needs to be done here to have the EMSJMSConfig
    }
    @Test
    public void testBuildsCorrectService() throws JMSException {
        MessagingService service = config.messagingService();   
        ...
    }
}
</code></pre>
",https://stackoverflow.com/questions/54327368/autowiring-fails-in-junit-testing-and-spring-configuration,"['java', 'spring', 'junit', 'autowired']",2259,True,1,1
Weird RxJS error when trying to use Angular TestBed,"<p>I'm trying to implement unit testing in my Angular project, but I'm running into an error message and I have no idea how to deal with that.</p>

<p>this is the code of my test file:</p>

<pre><code>import {AuthComponent} from './auth.component';
import {ConditionalMerchandising} from '../../common/merchandising/conditionalmerchandising.service';
import {TestBed} from '@angular/core/testing';
import {RouterTestingModule} from '@angular/router/testing';
import {of} from 'rxjs';

describe('Auth base page', () =&gt; {

    let _cm: jasmine.SpyObj&lt;ConditionalMerchandising&gt;;

    beforeEach(() =&gt; {
        _cm = jasmine.createSpyObj('ConditionalMerchandising', [ 'getMerchandising' ]);

        TestBed.configureTestingModule({
            declarations: [ AuthComponent ],
            providers:    [ {provide: ConditionalMerchandising, useValue: _cm } ],
            imports:      [ RouterTestingModule ]
        }).compileComponents();
    });

    it ('loads the picture', () =&gt; {
        TestBed.get(ConditionalMerchandising).getMerchandising.and.returnValue(of(''));

        const fixture = TestBed.createComponent(AuthComponent);
        fixture.detectChanges();

        console.log(fixture.nativeElement.querySelector('.page-contents'));

    });

});
</code></pre>

<p>When I run it, I get this strange error:</p>

<pre><code>ERROR in src/app/web-ui/auth/auth.component.ts(24,17): error TS2345: Argument of type 'import(""C:/Users/Bart/workspace/epicuro-web/node_modules/rxjs/internal/types"").OperatorFunction&lt;any, any&gt;' is not assignable to parameter of type 'import(""C:/Users/Bart/workspace/epicuro-web/src/app/common/node_modules/rxjs/internal/types"").OperatorFunction&lt;any, any&gt;'.
  Types of parameters 'source' and 'source' are incompatible.
    Type 'import(""C:/Users/Bart/workspace/epicuro-web/src/app/common/node_modules/rxjs/internal/Observable"").Observable&lt;any&gt;' is not assignable to type 'import(""C:/Users/Bart/workspace/epicuro-web/node_modules/rxjs/internal/Observable"").Observable&lt;any&gt;'.
      Types of property 'operator' are incompatible.
        Type 'import(""C:/Users/Bart/workspace/epicuro-web/src/app/common/node_modules/rxjs/internal/Operator"").Operator&lt;any, any&gt;' is not assignable to type 'import(""C:/Users/Bart/workspace/epicuro-web/node_modules/rxjs/internal/Operator"").Operator&lt;any, any&gt;'.
          Types of property 'call' are incompatible.
            Type '(subscriber: import(""C:/Users/Bart/workspace/epicuro-web/src/app/common/node_modules/rxjs/internal/Subscriber"").Subscriber&lt;any&gt;, source: any) =&gt; import(""C:/Users/Bart/workspace/epicuro-web/src/app/common/node_modules/rxjs/internal/types"").TeardownLogic' is not assignable to type '(subscriber: import(""C:/Users/Bart/workspace/epicuro-web/node_modules/rxjs/internal/Subscriber"").Subscriber&lt;any&gt;, source: any) =&gt; import(""C:/Users/Bart/workspace/epicuro-web/node_modules/rxjs/internal/types"").TeardownLogic'.
              Types of parameters 'subscriber' and 'subscriber' are incompatible.
                Property '_parentOrParents' is missing in type 'Subscriber&lt;any&gt;' but required in type 'Subscriber&lt;any&gt;'.
</code></pre>

<p>The line it's complaining about is <code>const fixture = TestBed.createComponent(AuthComponent);</code></p>

<p>What is it that I'm doing wrong here?</p>
",https://stackoverflow.com/questions/57407649/weird-rxjs-error-when-trying-to-use-angular-testbed,"['angular', 'rxjs', 'angular-test']",135,True,1,1
How to Mock HttpContext to access an extension method of IIdentity?,"<p>In my MVC project, I am building unit tests for a controller to return a view.</p>

<p>This controller's action result builds a viewmodel, and this viewmodel's constructor calls</p>

<pre><code>HttpContext.Current.User.Identity.NameWithoutDomain().ToUpper();
</code></pre>

<p>Where <code>NameWithoutDomain</code> is an extension method of <code>IIdentity</code>.</p>

<p>Whenever I run it, I keep getting ""the object cannot be found"" and I'm curious how can I Mock this appropriately for unit testing?</p>

<p>Extension method:</p>

<pre><code>public static class SystemWebExtension
{
    public static string NameWithoutDomain(this IIdentity identity)
    {
        return identity.Name.Split('\\').Last();
    }
}
</code></pre>

<p>Model constructor:</p>

<pre><code>public Model()
{
    this.PreparedByUser = HttpContext.Current.User.Identity.NameWithoutDomain().ToUpper();
    this.AuthorizedBy = true;
    this.AuthorizedByUser = HttpContext.Current.User.Identity.NameWithoutDomain().ToUpper();
    this.IssueCredit = true;
    this.CreateUser = string.IsNullOrEmpty(this.CreateUser) ? Environment.UserName.ToLower() : this.CreateUser;
    this.CreateDate = this.CreateDate.HasValue ? this.CreateDate : DateTime.Now;
    this.UpdateUser = string.IsNullOrEmpty(this.CreateUser) ? null : Environment.UserName.ToLower();
    this.UpdateDate = this.CreateDate.HasValue ? DateTime.Now : (DateTime?) null;
}
</code></pre>
",https://stackoverflow.com/questions/54870385/how-to-mock-httpcontext-to-access-an-extension-method-of-iidentity,"['c#', 'asp.net-mvc', 'unit-testing', 'asp.net-mvc-5']",1170,True,4,2
How to initialize ThreeTen Android backport in a Unit test,"<p>I use <a href=""https://github.com/JakeWharton/ThreeTenABP"" rel=""noreferrer"">this library</a> for storing date &amp; time related data in my app. When the application starts, <code>AndroidThreeTen</code> is initialized first to function properly. So I want to ask how to initialize it when unit testing? E.g. I want to test using <code>LocalDate</code>, <code>LocalDateTime</code>, etc.</p>

<p>My current way is like this:</p>

<pre><code>class OverviewViewModelTest {

    @Rule
    @JvmField
    val rule = InstantTaskExecutorRule()

    @Before
    fun setup() {
        AndroidThreeTen.init(Application())
    }

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

<p>But it throws this error:</p>

<pre><code>java.lang.ExceptionInInitializerError
    at org.threeten.bp.ZoneRegion.ofId(ZoneRegion.java:143)
    at org.threeten.bp.ZoneId.of(ZoneId.java:358)
    at org.threeten.bp.ZoneId.of(ZoneId.java:286)
    at org.threeten.bp.ZoneId.systemDefault(ZoneId.java:245)
    at org.threeten.bp.Clock.systemDefaultZone(Clock.java:137)
    at org.threeten.bp.LocalDate.now(LocalDate.java:165)
Caused by: java.lang.RuntimeException: Method getAssets in android.content.ContextWrapper not mocked. See http://g.co/androidstudio/not-mocked for details.
    at android.content.ContextWrapper.getAssets(ContextWrapper.java)
    at com.jakewharton.threetenabp.AssetsZoneRulesInitializer.initializeProviders(AssetsZoneRulesInitializer.java:22)
    at org.threeten.bp.zone.ZoneRulesInitializer.initialize(ZoneRulesInitializer.java:89)
    at org.threeten.bp.zone.ZoneRulesProvider.&lt;clinit&gt;(ZoneRulesProvider.java:82)
    ... 32 more
</code></pre>

<p>So how can I get this library to work in unit tests?</p>
",https://stackoverflow.com/questions/54527311/how-to-initialize-threeten-android-backport-in-a-unit-test,"['android', 'unit-testing', 'threetenbp']",1526,True,7,1
Unit testing a class with dependency that uses getBean(&quot;myService&quot;),"<p>I'm using a Jackson custom serializer which is known to not support Spring dependency injection so my serializer class is as follows:</p>

<pre><code>public class ShippingAddressDataSerializer extends JsonSerializer&lt;ShippingAddressData&gt; {

    /** Jackson serializers don't support Spring dependency injection */
    private CalculatedSettingsService calculatedSettingsService =
            (CalculatedSettingsService) Registry.getApplicationContext().getBean(""calculatedSettingsService"");

    @Override
    public void serialize(ShippingAddressData addressData, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeStartObject();

        jsonGenerator.writeStringField(""id"", addressData.getId());

        CalculatedSettings calculatedSettings = getCalculatedSettingsService()
                .getSettingsForCurrentUser(SettingType.REQUIRE_COUNTY);

        if (calculatedSettings.getIsCountyRequired()) {
            jsonGenerator.writeStringField(""county"", addressData.getCounty());

        }

        jsonGenerator.writeEndObject();
    }

    public CalculatedSettingsService getCalculatedSettingsService() {
        return calculatedSettingsService;
    }

    public void setCalculatedSettingsService(CalculatedSettingsService calculatedSettingsService) {
        this.calculatedSettingsService = calculatedSettingsService;
    }
}
</code></pre>

<p>I'm having trouble unit testing this class because I don't know how to provide a mock version of <code>calculatedSettingsService</code>.</p>

<p>The unit test keeps trying to startup my application context and I get the below error:</p>

<pre><code>java.lang.IllegalStateException: Can not activate tenant &lt;&lt;master&gt;&gt; since it has no application context created 
</code></pre>
",https://stackoverflow.com/questions/55652649/unit-testing-a-class-with-dependency-that-uses-getbeanmyservice,"['java', 'spring', 'junit']",89,True,0,1
How do you abort running the test cases if the ClassInitialize or TestInitalize fails?,"<p>I am using Microsoft unit testing in Visual Studio and I don't want to run the test cases if the ClassInitialize (preconditions) fails. 
Is there a way to stop or skip to run the test cases if ClassInitialize fails? 
The same question if TestInitialize fails but for a single test case.</p>

<p>Test code example in C#:</p>

<pre><code>    [ClassInitialize()]
    public static void MyClassInitialize(TestContext testContext)
    {
        SetupTestSystem();
        if (IsTestSystemOK == false)
        {
            SetFail(); //Don't run test cases. Only highlight that ClassInitialize failed.
        }
    }

    [TestInitialize()]
    public void MyTestInitialize()
    {
        SetupForTesting();
        if (IsTestSystemOK() == false)
        {
            SetFail(); //Don't run test case, only highlight that TestInitialize failed. 
        }
    }

    [TestMethod]
    public void TestMethod1()
    {
        //If ClassInitialize or TestInitialize fails, don't run me.
    }
</code></pre>
",https://stackoverflow.com/questions/56644040/how-do-you-abort-running-the-test-cases-if-the-classinitialize-or-testinitalize,"['c#', '.net', 'unit-testing']",542,False,0,1
Unit testing in angular with various test data,"<p>If I need to do unit testing for any c# method with various sets of data, then I can use the <strong>Theory</strong> and <strong>InlineData</strong> to pass varios inputs for testing a method.</p>

<pre><code>[Theory]
[InlineData(""88X"", ""1234"", ""1234"", ""1234"")]
[InlineData(""888"", ""123X"", ""1234"", ""1234"")]
public void ShouldReturnInValidIfCustomerInformationDoestMatch(
    string locationId,
    string quoteBillTo,
    string quoteSoldTo,
    string quoteShipTo)
{
    ....
}
</code></pre>

<p>Similarly is there any way to unit test in <strong>Angular/Jasmine/Karma</strong> to validate the same functionality/method with various set of input data?</p>
",https://stackoverflow.com/questions/56551789/unit-testing-in-angular-with-various-test-data,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'karma-runner']",778,True,0,1
How to mock DescribeClusterOutput,"<p>I have written a code that will interact with EMR service and based on a clusterId it will return the cluster status.
I am trying to unit test it but I couldn't figure out. </p>

<p>code:</p>

<pre class=""lang-golang prettyprint-override""><code>func (hc *HandlerConfig) Handler(c entities.Cluster) (string, error) {
    clusterID := aws.String(c.ClusterID)

    clusterDetails, err := hc.EMRClient.DescribeCluster(&amp;emr.DescribeClusterInput{ClusterId: clusterID})
    if err != nil {
        return ""error"", err
    }

    clusterStatus := *clusterDetails.Cluster.Status.State

    return fmt.Sprintf(clusterStatus), nil
}
</code></pre>

<p>unit testing code:</p>

<pre class=""lang-golang prettyprint-override""><code>func TestHandler(t *testing.T) {
    emrClient := new(emrtestutils.MockEMR)
    hc := HandlerConfig{
        EMRClient: emrClient,
    }

    input := &amp;emr.DescribeClusterInput{ClusterId: aws.String(""j-dfdslkj3kl213kj"")}

    // I'M STUCK HERE
    output := &amp;emr.DescribeClusterOutput{
        Cluster
    }

    emrClient.On(""DescribeCluster"", input).Return(*output.Status.State)
    res, err := hc.Handler(entities.Cluster{ClusterID: ""j-dfdslkj3kl213kj""})

    assert.NoError(t, err)
    emrClient.AssertExpectations(t)
    assert.Equal(t, res, output)

}
</code></pre>

<p>I want to provide mock value of DescribeClusterOutput.</p>

<p>link: <a href=""https://docs.aws.amazon.com/sdk-for-go/api/service/emr/#EMR.DescribeCluster"" rel=""nofollow noreferrer"">https://docs.aws.amazon.com/sdk-for-go/api/service/emr/#EMR.DescribeCluster</a></p>
",https://stackoverflow.com/questions/58685900/how-to-mock-describeclusteroutput,"['go', 'mocking', 'amazon-emr', 'aws-sdk-go']",168,False,0,0
Expected undefined to be defined error in Karma unit testing while testing a function using .toBeTruthy(),"<p>In the below spec file am covering test case for saveAdmin function but am getting below mentioned error</p>

<p><strong>Expected undefined to be defined</strong> error in Karma unit testing while testing a function using .toBeTruthy() i had given the ts file and spec file also mentioned the error from karma. Thanks in advance </p>

<p><strong>Ts file</strong>  </p>

<pre><code>  import {Component, Inject, OnInit} from ""@angular/core"";
    import {MAT_DIALOG_DATA, MatDialogRef} from ""@angular/material"";
    import {DataService} from ""../../../services/data.service"";
    @Component({
      selector: 'admin-dialog',
      templateUrl: './admin-dialog.component.html',
      styleUrls: ['./admin-dialog.component.scss']
    })
    export class AdminDialogComponent implements OnInit {
      public accessHasSelected : any ='';
      public errorObj : any = {};
      public checkBoxSelected : boolean;
      public adminObj: any = {
        active:true,
        firstName:"""",
        lastName:"""",
       // emailId:"""",
        access:[]
      };
      /***
       *
       * @param dialogRef
       * @param data
       * @param fromGroup
       * @param dataService
       */
      constructor(
        public dialogRef: MatDialogRef&lt;AdminDialogComponent&gt;,
        @Inject(MAT_DIALOG_DATA) public data: any,
        private dataService: DataService) {

        if (this.data.isNew){
          this.newAdmin();
        }
        else {
          this.editAdmin(this.data.adminObj);
        }
      }
      /*
      * This method will get called while loading new admin modal.
      * */
      newAdmin() {
        this.dataService.getAllAdminAccess().subscribe(
          response =&gt; {
            this.adminObj.access = response.access;
          },
          error =&gt; { });
      }
      /***
       * This method will get called while loading edit existing admin modal.
       * @param response
       */
      editAdmin(response){
        console.log(response);
        this.dataService.getAdminDetails(response.emailId).subscribe(
          response =&gt; {
            //component related success actions
            this.adminObj = response;
          },
          error =&gt; {});
      }
      /**
       * This method will run will save is clicked.
       * */
      saveAdmin(){
        this.checkBoxSelected = true;
        this.accessHasSelected = this.adminObj.access.filter(t=&gt;{
          if(this.checkBoxSelected){
            if(t.selected){this.checkBoxSelected = false;}
            else if(t.access !== null){
              t.access.filter(x=&gt;{
                if(x.selected) {this.checkBoxSelected = false;}
              })
            }
          }
        });
        if(!this.checkBoxSelected) {
          this.dataService.saveAdmin(this.adminObj, this.data.isNew).subscribe(
            response =&gt; {
              //component related success actions
              this.dialogRef.addPanelClass('close-modal');
              setTimeout(() =&gt; {
                this.dialogRef.close({
                  data: response
                });
              }, 500);
            },
            error =&gt; {
              this.errorObj = {};
              //component related error actions
              for (var v in error.error.errors) {
                this.errorObj[error.error.errors[v].field] = error.error.errors[v].messageId;
              }
            });
        }else{
            this.errorObj.access = ""requiredAccessError"";
          }
      }
      /**
       *
       */
      ngOnInit() {}
      onModalCancel(): void {
        this.dialogRef.addPanelClass('close-modal');
        setTimeout(()=&gt;{
          this.dialogRef.close();
        },500);
      }
    }
</code></pre>

<p><strong>Spec file:</strong></p>

<pre><code>import { AdminDialogComponent } from ""./admin-dialog.component"";
import { TestBed, ComponentFixture,async,inject  } from '@angular/core/testing';
import { FormsModule } from ""@angular/forms"";
import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing';
import {TranslateModule,TranslateService} from ""@ngx-translate/core"";
import {Inject, NO_ERRORS_SCHEMA} from ""@angular/core"";
import {MAT_DIALOG_DATA, MatDialog, MatDialogModule, MatDialogRef} from '@angular/material/dialog';
import { OverlayContainer } from '@angular/cdk/overlay';
import {HttpClientModule} from ""@angular/common/http"";
import {RouterTestingModule} from ""@angular/router/testing"";
import {DataService} from ""../../../services/data.service"";
import {of} from ""rxjs/internal/observable/of"";

describe('Component: admin-dialog', () =&gt; {

  let component: AdminDialogComponent;
  let fixture: ComponentFixture&lt;AdminDialogComponent&gt;;
  let translate: TranslateService;
  let dialog: MatDialog;
  let overlayContainer: OverlayContainer;
  let dataService: DataService;
  beforeEach(() =&gt; {


    TestBed.configureTestingModule({
      imports: [FormsModule, MatDialogModule, HttpClientModule,RouterTestingModule,TranslateModule.forRoot()],
      declarations: [AdminDialogComponent],
      providers: [TranslateService,
        { provide: MatDialogRef, useValue: {} },
        {
          provide: MAT_DIALOG_DATA, useValue: {
            isNew: false, // I guess it's boolean
            adminObj: {firstName: ""AAAAAA"", lastName: ""AA"", password: null, emailId: ""test@test.com"",
              access : [
                {
                  accessCode: 1,
                  accessName: 'test',
                  path: '/admin/tests',
                  orderBy: 5,
                  access: []
                },
                {
                  accessCode: 3,
                  accessName: 'view-aep-org',
                  path: '/admin/testing',
                  orderBy: 1,
                  access: []
                }]
            }
          }
        },
        {provide: dataService, useValue: {}}
      ],
      schemas: [NO_ERRORS_SCHEMA]
  });
    TestBed.overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [AdminDialogComponent]
      }
    });

    TestBed.compileComponents();

    // create component and test fixture
    fixture = TestBed.createComponent(AdminDialogComponent);

    // get test component from the fixture
    component = fixture.componentInstance;
   // component.ngOnInit();
  });
  beforeEach(inject([MatDialog, OverlayContainer],
    (d: MatDialog, oc: OverlayContainer) =&gt; {
      dialog = d;
      overlayContainer = oc;
    })
  );
  afterEach(() =&gt; {
    overlayContainer.ngOnDestroy();
  });
  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
  it('saveAdmin for requiredAccessError ', () =&gt; {
    component.adminObj = {firstName: ""AAAAAA"", lastName: ""AA"", password: null, emailId: ""test@test.com"",
      access : [
        {
          access: null,
          accessCode: 1,
          accessName: ""test"",
          active: true,
          orderBy: 1,
          parentAccessCode: null,
          path: ""/test/test"",
          selected: false,
          showCheckbox: true
        }]
    };
    expect(component.saveAdmin()).toBeTruthy();
  });

});
</code></pre>

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

<pre><code>Component: admin-dialog &gt; saveAdmin for requiredAccessError
Expected undefined to be defined.
Error: Expected undefined to be defined.
    at &lt;Jasmine&gt;
    at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/webpack:/src/app/dashboard/manage-admin/admin-dialog/admin-dialog.component.spec.ts:150:35)
</code></pre>
",https://stackoverflow.com/questions/57309151/expected-undefined-to-be-defined-error-in-karma-unit-testing-while-testing-a-fun,"['angular', 'typescript', 'unit-testing', 'karma-jasmine']",4632,False,0,1
kotlin @RegisterExtension not working with salesforce kafka-junit5,"<p>I need an embedded kafka for unit testing(UT) purposes.</p>

<p>I am trying to get github.com/salesforce/kafka-junit/tree/master/kafka-junit5 to work with Kotlin.</p>

<pre><code>companion object {
    /**
     * gleefully stolen from: https://github.com/salesforce/kafka-junit/tree/master/kafka-junit5
     *
     * We have a single embedded Kafka server that gets started when this test class is initialized.
     *
     * It's automatically started before any methods are run via the @RegisterExtension annotation.
     * It's automatically stopped after all of the tests are completed via the @RegisterExtension annotation.
     */
        @JvmField
        @RegisterExtension
        var sharedKafkaTestResource: SharedKafkaTestResource = SharedKafkaTestResource().withBrokers(2)

}
</code></pre>

<p>but the <code>BeforeAllCallback#beforeAll</code>, <code>AfterAllCallback#afterAll</code> methods never get invoked.</p>

<ol>
<li>how can i get kafka-junit5 to work, or</li>
<li>is there another embedded kafka solution that already works with kotlin?</li>
</ol>

<p>here's my pom:</p>

<pre><code>&lt;properties&gt;
... snip ...
    &lt;salesforce-kafka-junit.version&gt;3.1.0&lt;/salesforce-kafka-junit.version&gt;
    &lt;salesforce-kafka.version&gt;1.1.1&lt;/salesforce-kafka.version&gt;
    &lt;junit-jupiter.version&gt;5.3.2&lt;/junit-jupiter.version&gt;
    &lt;kotlin.version&gt;1.2.71&lt;/kotlin.version&gt;
&lt;/properties&gt;

&lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;com.salesforce.kafka.test&lt;/groupId&gt;
        &lt;artifactId&gt;kafka-junit5&lt;/artifactId&gt;
        &lt;version&gt;${salesforce-kafka-junit.version}&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;com.salesforce.kafka.test&lt;/groupId&gt;
        &lt;artifactId&gt;kafka-junit-core&lt;/artifactId&gt;
        &lt;version&gt;${salesforce-kafka-junit.version}&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-engine&lt;/artifactId&gt;
        &lt;version&gt;${junit-jupiter.version}&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
        &lt;artifactId&gt;kafka_2.11&lt;/artifactId&gt;
        &lt;version&gt;${salesforce-kafka.version}&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
        &lt;artifactId&gt;kafka-clients&lt;/artifactId&gt;
        &lt;version&gt;${salesforce-kafka.version}&lt;/version&gt;
    &lt;/dependency&gt;
... snip ...
&lt;/dependencies&gt;
</code></pre>
",https://stackoverflow.com/questions/54427877/kotlin-registerextension-not-working-with-salesforce-kafka-junit5,"['apache-kafka', 'junit5']",285,False,0,1
Karmaunit-testing: Cannot read property &#39;eventType&#39; of undefined thrown,"<p>Setting up the basics in unit-testing with Karma (Angular 7) en stumbling upon .</p>

<p><code>&lt;testcase name=""HeaderComponent should create"" time=""0.4"" classname=""HeaderComponent""&gt;
&lt;failure type=""""&gt; Uncaught TypeError: Cannot read property 'eventType' of undefined thrown</code></p>

<p>This particular property exists on <code>queryObject</code> which is used bij my Akita State Manager, however, not in HeaderComponent. There also isnt any reference to Akita Store nor to queryObject or what so ever in HeaderComponent.</p>

<p>How can this be an issue though?</p>

<p>component:</p>

<pre><code>@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  menuHidden = true;

  constructor(
    private router: Router,
    private i18nService: I18nService,
    public authenticationService: AuthenticationService
  ) {}

  ngOnInit() {}

  toggleMenu() {
    this.menuHidden = !this.menuHidden;
  }

  setLanguage(language: string) {
    this.i18nService.language = language;
  }

  logout() {
    this.authenticationService.logout().subscribe(() =&gt; this.router.navigate(['/login']));
  }

  get currentLanguage(): string {
    return this.i18nService.language;
  }

  get languages(): string[] {
    return this.i18nService.supportedLanguages;
  }

  get username(): string | null {
    const credentials = this.authenticationService.credentials;
    return credentials ? credentials.username : null;
  }
}
</code></pre>

<p>spec:</p>

<pre><code>describe('HeaderComponent', () =&gt; {
  let component: HeaderComponent;
  let fixture: ComponentFixture&lt;HeaderComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, NgbModule, TranslateModule.forRoot()],
      declarations: [HeaderComponent],
      providers: [{ provide: AuthenticationService, useClass: MockAuthenticationService }, I18nService]
    }).compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>MockAuthenticationService</p>

<pre><code>export class MockAuthenticationService {
  credentials: Credentials | null = {
    username: 'test',
    token: '123'
  };

  login(context: LoginContext): Observable&lt;Credentials&gt; {
    return of({
      username: context.username,
      token: '123456'
    });
  }

  logout(): Observable&lt;boolean&gt; {
    this.credentials = null;
    return of(true);
  }

  isAuthenticated(): boolean {
    return !!this.credentials;
  }

  isAuthenticatedAdmin(): boolean {
    return true; // this.genericStateModel.isAdmin;
  }
}
</code></pre>

<p>template</p>

<pre><code>  &lt;header&gt;
    &lt;nav class=""navbar navbar-expand-lg navbar-dark bg-dark""&gt;
      &lt;a class=""navbar-brand"" href=""/"" translate&gt;APP_NAME&lt;/a&gt;
      &lt;button class=""navbar-toggler"" type=""button"" aria-controls=""navbar-menu""
              aria-label=""Toggle navigation"" (click)=""toggleMenu()"" [attr.aria-expanded]=""!menuHidden""&gt;
        &lt;span class=""navbar-toggler-icon""&gt;&lt;/span&gt;
      &lt;/button&gt;
      &lt;div id=""navbar-menu"" class=""collapse navbar-collapse float-xs-none"" [ngbCollapse]=""menuHidden""&gt;
        &lt;div class=""navbar-nav""&gt;
          &lt;a class=""nav-item nav-link text-uppercase"" routerLink=""/herd"" routerLinkActive=""active""&gt;
            &lt;i class=""fas fa-home""&gt;&lt;/i&gt;
            &lt;span translate&gt;herd&lt;/span&gt;
          &lt;/a&gt;
          &lt;a *ngIf=""authenticationService.isAuthenticated() &amp;&amp; authenticationService.isAuthenticatedAdmin()"" class=""nav-item nav-link text-uppercase"" routerLink=""/stock"" routerLinkActive=""active""&gt;
            &lt;i class=""fas fa-warehouse""&gt;&lt;/i&gt;
            &lt;span translate&gt;stock&lt;/span&gt;
          &lt;/a&gt;
          &lt;a *ngIf=""authenticationService.isAuthenticated() &amp;&amp; authenticationService.isAuthenticatedAdmin()"" class=""nav-item nav-link text-uppercase"" routerLink=""/orders"" routerLinkActive=""active""&gt;
            &lt;i class=""fas fa-money-check-alt""&gt;&lt;/i&gt;
            &lt;span translate&gt;orders&lt;/span&gt;
          &lt;/a&gt;
        &lt;/div&gt;
        &lt;div class=""navbar-nav ml-auto""&gt;
          &lt;div class=""nav-item"" ngbDropdown placement=""bottom-right""&gt;
            &lt;a id=""user-dropdown"" class=""nav-link"" ngbDropdownToggle&gt;
              &lt;i class=""fas fa-user-circle""&gt;&lt;/i&gt;
            &lt;/a&gt;
            &lt;div ngbDropdownMenu aria-labelledby=""user-dropdown""&gt;
              &lt;h6 class=""dropdown-header""&gt;
                &lt;span translate&gt;logged in as&lt;/span&gt; &lt;b&gt;{{username}}&lt;/b&gt;&lt;/h6&gt;
              &lt;div class=""dropdown-divider""&gt;&lt;/div&gt;
              &lt;button class=""dropdown-item"" (click)=""logout()"" translate&gt;logout&lt;/button&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/nav&gt;
  &lt;/header&gt;
</code></pre>
",https://stackoverflow.com/questions/55086042/karmaunit-testing-cannot-read-property-eventtype-of-undefined-thrown,"['angular', 'unit-testing', 'karma-jasmine']",223,False,0,0
AssertionError: None != &#39;attachment; filename=filename.extension&#39;,"<p>I'm trying to get the filename of a file that is being downloaded while testing. I've took a reference to <a href=""https://stackoverflow.com/questions/8244220/django-unit-test-for-testing-a-file-download"">this</a> but couldnot get the solution. I'm quite a noob in testing. Can anyone help me get the name of the filename that is being downloaded in unit testing? Thanks in advance</p>

<p>test.py</p>

<pre><code>from django.contrib.auth.models import User
from rest_framework.test import APITestCase, force_authenticate
from rest_framework.authtoken.models import Token
from csv_loader.api.views import UserViewSet


class UserTestCase(APITestCase):
    def setUp(self):
        self.username = 'testuser1'
        self.email = 'testuser1@gmail.com'
        self.password = '!superuser'
        self.superuser = User.objects.create_user(username='superuser', email='uid.sawyer@gmail.com',
                                                  password='superuser',
                                                  is_staff=True)
        self.token = Token.objects.get(user=self.superuser)


    def test_superuser_file_download(self):
        user = User.objects.get(username='superuser')
        view = UserViewSet.as_view({'get': 'list'})
        request = self.factory.get('/api/users/user_download/')
        force_authenticate(request, user, token=self.token)
        response = view(request)
        self.assertEquals(
            response.get('Content-Disposition'),
            ""attachment; filename=users.csv""
        )
        )

</code></pre>

<p>Views.py</p>

<pre><code>class UserViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    permission_classes = [IsOwnerOrAdmin, ]

    @action(detail=False, methods=[""get""], permission_classes=[IsAdmin, ])
    def user_download(self, request):
        users = User.objects.all()

        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=""users.csv""'

        writer = csv.writer(response, delimiter=',')
        writer.writerow(['username', 'email'])

        for user in users:
            writer.writerow([user.username, user.email])

        return response
</code></pre>

<p>serializers.py</p>

<pre><code>class FileUploadSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = FileUpload
        fields = ('created', 'datafile')
</code></pre>

<p>Error</p>

<pre><code>======================================================================
FAIL: test_superuser_file_download (csv_loader.tests.tests.UserTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""/home/username/Desktop/CSV/Tasks/Docker/csv-loader/csv_loader/tests/tests.py"", line 245, in test_superuser_file_download
    ""attachment; filename=users.csv""
AssertionError: None != 'attachment; filename=users.csv'

----------------------------------------------------------------------
Ran 1 test in 0.208s

FAILED (failures=1)
Destroying test database for alias 'default'...

</code></pre>
",https://stackoverflow.com/questions/57753988/assertionerror-none-attachment-filename-filename-extension,"['unit-testing', 'csv', 'download', 'django-rest-framework']",55,False,0,1
How to check values in array in object,"<p>I am busy with jasmine unit testing. But I get errors. I have some problems with more values in array. And I don't understand that. </p>

<p>I have this as unit test code:</p>

<pre><code>  component.portfolio = {
            learningPath: [
                {
                    id: '2345',
                    metaLines: ['sbu tekst', '29 maart 2019'],
                    title: 'mock name',
                    titleLink: `${learningPathDetailsLink}/2345`,

                },
                {
                    id: '23567',
                    metaLines: ['sbu tekst', '1 april 2019'],
                    title: 'mock name',
                    titleLink: `${learningPathDetailsLink}/23567`,

                },


            ],
        } as any;

        // Assert
        expect(component.cards).toEqual([
            new CardModel({ id: '2345', metaLines: ['sbu tekst', '29 maart 2019'], title: 'mock name', titleLink: `${learningPathDetailsLink}/2345` }),
            new CardModel({ id: '23567', metaLines: ['sbu tekst', '1 april 2019'], title: 'mock name', titleLink: `${learningPathDetailsLink}/23567` }),
        ]);
        expect(formatPipeSpy.calls.argsFor(0)).toEqual(['30 maart 2019', resources.begindatumTitel]);
        expect(formatPipeSpy.calls.argsFor(1)).toEqual(['30 maart 2019', resources.afrondDatumTitel]);
</code></pre>

<p>But then I get this as errors:</p>

<pre><code>Expected $[0].metaLines[0] = undefined to equal 'sbu tekst'.
Expected $[0].metaLines[1] = undefined to equal '29 maart 2019'.
Expected $[0].title = undefined to equal 'mock name'.
Expected $[0].titleLink = 'undefined/2345' to equal 'test/learningpath-details/2345'.
Expected $[1].metaLines[0] = undefined to equal 'sbu tekst'.
Expected $[1].metaLines[1] = undefined to equal '1 april 2019'.
Expected $[1].title = undefined to equal 'mock name'.
Expected $[1].titleLink = 'undefined/23567' to equal 'test/learningpath-details/23567'.
Error: Expected $[0].metaLines[0] = undefined to equal 'sbu tekst'.
Expected $[0].metaLines[1] = undefined to equal '29 maart 2019'.
Expected $[0].title = undefined to equal 'mock name'.
Expected $[0].titleLink = 'undefined/2345' to equal 'test/learningpath-details/2345'.
Expected $[1].metaLines[0] = undefined to equal 'sbu tekst'.
Expected $[1].metaLines[1] = undefined to equal '1 april 2019'.
Expected $[1].title = undefined to equal 'mock name'.
Expected $[1].titleLink = 'undefined/23567' to equal 'test/learningpath-details/23567'.
    at &lt;Jasmine&gt;
    at UserContext.&lt;anonymous&gt; (http://localhost:9890/_karma_webpack_/webpack:/src/components/src/portfolio/portfolio-details/portfolio-details.component.spec.ts:116:33)
    at UserContext.&lt;anonymous&gt; (http://localhost:9890/_karma_webpack_/webpack:/E:/Projects/VLR/Web/vlrworkspace/node_modules/zone.js/dist/zone-testing.js:1429:1)
    at ZoneDelegate.push.../../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9890/_karma_webpack_/webpack:/E:/Projects/VLR/Web/vlrworkspace/node_modules/zone.js/dist/zone.js:391:1)
Expected $[0] = undefined to equal '30 maart 2019'.
</code></pre>

<p>I realy don't unsestand that. Because what is wrong with:</p>

<pre><code>  metaLines: ['sbu tekst', '29 maart 2019'],

</code></pre>

<p>This are the two values or not?</p>
",https://stackoverflow.com/questions/55457322/how-to-check-values-in-array-in-object,"['javascript', 'angular', 'karma-jasmine']",109,False,0,0
Not able to unit test API controller using moq. Where I&#39;m going wrong?,"<p>Controller class</p>

<pre><code>[Route(""hollywood/[controller]"")]
    [ApiController]
    public class MoviesController : Controller
    {
        List&lt;Film&gt; film = new List&lt;Film&gt;()
        {
            new Film(){id=1,name=""The Dark Knight"",director=""Christopher Nolan"", release=2008},
            new Film(){id=2,name=""300"",director=""Zack Snyder"", release=2007},
            new Film(){id=3,name=""Titanic"",director=""James Cameron"", release=1997},
        };

        // GET film/movies
        [HttpGet]
        public IActionResult Get()
        {
            // some code
            return Json(film);
        }

        // GET film/movies/{id}
        [HttpGet(""{id}"")]
        public IActionResult Get(int id)
        {
            // some code
            return Json(film.FirstOrDefault(x =&gt; x.id == id));
        }

        [HttpPost]
        public IActionResult Post([FromBody]Film value)
        {
            // some code
            film.Add(value);
            return Json(film);
        }
    }
</code></pre>

<p>Model Class </p>

<pre><code>public class Film
    {
        public int id { get; set; }
        public string name { get; set; }
        public string director { get; set; }
        public int release { get; set; }
    }
</code></pre>

<p>Test </p>

<pre><code>[Fact]
        public async Task TestGet()
        {
            List&lt;Film&gt; film = new List&lt;Film&gt;()
            {
                new Film(){id=1,name=""The Dark Knight"",director=""Christopher Nolan"", release=2008},
                new Film(){id=2,name=""300"",director=""Zack Snyder"", release=2007},
                new Film(){id=3,name=""Titanic"",director=""James Cameron"", release=1997},
            };

            // Arrange
            string expectedResult = JsonConvert.SerializeObject(film);
            var requestUri = new Uri(""http://localhost:51867/film/movies"");

            // Act
            var mockHandler = new Mock&lt;MoviesController&gt;();

            mockHandler
                .Setup(x =&gt; x.Get())
                .Returns(expectedResult);

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

            // Assert
            Assert.Equal(expectedResult, result);
        }
</code></pre>

<p>I'm performing unit testing using moq. I need to mock the Get/Post calls in Controllers using Moq HttpClient. I'm unable to mock the object. Please let me know what am I doing wrong? Is IActionResult return type causing it to fail? If yes, what else can I use instead of IActionResult?</p>
",https://stackoverflow.com/questions/54937404/not-able-to-unit-test-api-controller-using-moq-where-im-going-wrong,"['c#', 'unit-testing', 'asp.net-core', 'mocking', 'moq']",131,False,0,0
Error as Cannot read property &#39;subscribe&#39; . for activated route in angular 7 while unit testing,"<p>I am getting error as Cannot read property 'subscribe' of undefined for activated route in angular 7 while unit testing .I have tried it in multiple way kindly help . </p>

<p>Observer.of is not working for me as i have rx.js version 6.3.3</p>

<p>here is my compnent file ChildComponent.ts</p>

<pre><code>import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
    selector: 'app-child',
    template: `
        &lt;h1&gt;Enter your name&lt;/h1&gt;
        &lt;form
              [formGroup]=""nameForm""
              (ngSubmit)=""submitForm(nameForm)""
        &gt;
            &lt;input
                   type=""text""
                   formControlName=""firstName""
                   placeholder=""first""
            &gt;
            &lt;input
                   type=""text""
                   formControlName=""lastName""
                   placeholder=""last""
            &gt;
            &lt;button type=""submit""&gt;launch to space&lt;/button&gt;
        &lt;/form&gt;
    `,
    styleUrls: ['./child.component.css']
})
export class ChildComponent {
    @Input() nameForm: FormGroup;
    private abc: number;
    constructor(
        public route: ActivatedRoute,
       ) {

        this.route.queryParams.subscribe(params =&gt; {
          this.abc = params['abc'];
        });

      }

    submitForm(form: FormGroup) {
        console.log(form);
        // really you would be using an event emitter
    }
}
</code></pre>

<p>here is my unit test file for child component unit test case</p>

<pre><code>
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormBuilder } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router, Data, Params } from '@angular/router';
import { Observable, of } from 'rxjs';
import { BehaviorSubject } from 'rxjs';


export class MockActivatedRoute {
    private paramsSubject = new BehaviorSubject(this.testParams);
    private _testParams: {};

    params  = this.paramsSubject.asObservable();

    get testParams() {
        return this._testParams;
    }
    set testParams(newParams: any) {
        this._testParams = newParams;
        this.paramsSubject.next(newParams);
    }
}


import { ChildComponent } from './child.component';


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

    class MockActivatedRoute1 extends ActivatedRoute {
    constructor() {
        super();
        this.params = of({id: ""5""});
    }
  }

    // create new instance of FormBuilder
    const formBuilder: FormBuilder = new FormBuilder();
    let activeRoute: MockActivatedRoute;  


    beforeEach(() =&gt; {
        activeRoute = new MockActivatedRoute();
    });


    beforeEach(
        async(() =&gt; {
            TestBed.configureTestingModule({
                declarations: [
                    ChildComponent
                ],
                imports: [
                    CommonModule,
                    ReactiveFormsModule,
                    //AppModule
                ],
                providers: [
                    // reference the new instance of formBuilder from above
                    { provide: FormBuilder, useValue: formBuilder },
                    {
                        provide: ActivatedRoute,
                        useValue: {
                            params: {
                                subscribe: (fn: (value: Data) =&gt; void) =&gt; fn({
                                    abc: 1
                                })
                            }
                        }
                    }
                ]
            }).compileComponents();
        })
    );

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(ChildComponent);
        component = fixture.componentInstance;

        // pass in the form dynamically
        component.nameForm = formBuilder.group({
            firstName: null,
            lastName: null
        });
        fixture.detectChanges();
    });

    it('should be created', () =&gt; {
        expect(component).toBeTruthy();
    });
});
</code></pre>
",https://stackoverflow.com/questions/55514167/error-as-cannot-read-property-subscribe-for-activated-route-in-angular-7-whi,"['angular', 'typescript', 'angular-unit-test', 'angular-activatedroute']",3483,True,0,1
How to unit test entities with DatabaseGenerated fields?,"<p>I've inherited an application where every entity has a <code>DateCreated</code> field with the <code>DatabaseGenerated</code> attribute using <code>DateTime.Now</code> on inserts. While beneficial, this introduces problems when unit testing. </p>

<p>I'm a believer in not depending on a volatile resource like a real database during unit testing so my preference would be to use an in-memory solution but neither localdb or Sqlite support the attribute without code changes. <a href=""https://www.manning.com/books/entity-framework-core-in-action?query=efcoreinaction"" rel=""nofollow noreferrer"">EF Core in Action</a> seems to confirm that it's not possible with in-memory databases in general.</p>

<p>But even if I'm willing to look past an in-memory database, the business needs require a diverse set of created dates to be tested and if I want to start fresh every test cycle (and I do) I can only generate data for <code>DateTime.Now</code>.</p>

<p>While I can write some code to operate on real db data that is dumped to application memory where I alter the created date as needed, that's another thing to maintain and support. </p>

<p>Is there another way I'm missing?</p>
",https://stackoverflow.com/questions/59507772/how-to-unit-test-entities-with-databasegenerated-fields,"['unit-testing', 'asp.net-core', 'ef-core-2.2']",109,False,1,1
Code coverage for ElasticClient using Moq,"<p>I am attempting to analyze code coverage via unit testing, I am currently using Moq library to perform unit testing, somehow I am heading into a wrong path, would like to know if the below scenario is applicable using Moq</p>

<p>Below is a snippet of code</p>

<pre><code>public interface ISearchWorker
{
    void DeleteIndex(string indexName);

    T GetClient&lt;T&gt;();
}

public class ElasticSearchWorker : ISearchWorker
{
    public void DeleteIndex(string indexName)
    {
        IElasticClient elasticClient = GetClient&lt;IElasticClient&gt;();

        if (elasticClient.IndexExists(indexName).Exists)
        {
            _ = elasticClient.DeleteIndex(indexName);
        }
    }

    public T GetClient&lt;T&gt;()
    {        
        string nodeList = ""http://localhost:9200/"";

        List&lt;Node&gt; nodes = nodeList.Split(',').Select(uri =&gt; new Node(new Uri(uri))).ToList();

        IConnectionPool sniffingConnectionPool = new SniffingConnectionPool(nodes);

        IConnectionSettingsValues connectionSettings = new ConnectionSettings(sniffingConnectionPool);

        return (T)(IElasticClient)new ElasticClient(connectionSettings);        
    }
}

</code></pre>

<p>Below is the code snippet for the unit test</p>

<pre><code>

    [TestClass]
    public class SearchTestClass
    {
        private ISearchWorker searchWorker;

        private Mock&lt;ISearchWorker&gt; searchWorkerMoq;

        private readonly string indexName = ""testIndex"";

        [TestInitialize]
        public void SetupElasticClient()
        {
            searchWorkerMoq = new Mock&lt;ISearchWorker&gt;();

            var elasticClient = new Mock&lt;IElasticClient&gt;();

            searchWorkerMoq.Setup(c =&gt; c.GetClient&lt;IElasticClient&gt;()).Returns(elasticClient.Object).Verifiable();

            searchWorker = searchWorkerMoq.Object;
        }

        [TestMethod]
        public void DeleteIndexTest()
        {
            try
            {
                searchWorker.DeleteIndex(indexName);

                searchWorkerMoq.Verify(c =&gt; c.GetClient&lt;IElasticClient&gt;(), Times.Once()); 
            }
            catch (System.Exception)
            {
                throw;
            }
        }
    }

</code></pre>

<p>The line </p>

<pre><code>
searchWorkerMoq.Verify(c =&gt; c.GetClient&lt;IElasticClient&gt;(), Times.Once());

</code></pre>

<p>Throws the following exception</p>

<pre><code>(Moq.MockException: '
Expected invocation on the mock once, but was 0 times: c =&gt; c.GetClient&lt;IElasticClient&gt;())

</code></pre>

<p>Reading through most Moq related information it seems this is not the appropriate way to perform a Moq test, the IElasticClient object should be supplied externally to the ElasticSearchWorker class</p>

<p>The reason for not supplying the IElasticClient object from external injection is that we plan to implement ISearchWorker for another search provider (Azure Search) so would like to keep the client entity enclosed within the class implementing the ISearchWorker interface</p>

<p><strong>Would like to know if there is a better way to perform this test, Also how would we achieve code coverage for this scenario.</strong></p>
",https://stackoverflow.com/questions/56489114/code-coverage-for-elasticclient-using-moq,"['c#', 'unit-testing', 'elasticsearch', 'moq', 'code-coverage']",318,True,1,1
"Laravel, phpunit : For loop not saving more than one entry in database","<p>I am developing an application using Laravel, Eloquent as ORM, phpunit for unit testing. I want to save more than one entry in database, i have tried for loop. But for loop is saving only one entry, even the loop is running only one time. The loop is working fine for other code except the save chunk. Below are my codes:</p>

<p><strong>Model Class:</strong></p>

<pre><code>class Post extends Model
{
    protected $table = ""posts"";

    protected $fillable = [
            'id', 
            'user_id', 
            'title',
            'description',
            'total_needed',
            'total_collected', 
            'total_expanse',
            'start_date',
            'end_date',
            'active',
            'updated_at',
            'created_at',
        ];

}
</code></pre>

<p><strong>Unit testing code</strong></p>

<pre><code>class RepoPost extends TestCase
{
public function testMain()
    {
        echo ""\n &gt;----------- Test Name : "" . get_class($this);
        echo ""\n &gt;----------- Test Main : ---------&gt; \n"";
        $this-&gt;postSave();
    } //test:main


public function postSave()
    {
        $postDummy = new Post();
        // $postDummy-&gt;id ='';
        $postDummy-&gt;user_id = 'Tst';
        $postDummy-&gt;title = 'Post Save Repo Test.';
        $postDummy-&gt;description = 'UnitTesting of URLs';
        $postDummy-&gt;total_needed = '2000';
        $postDummy-&gt;total_collected = '1000';
        $postDummy-&gt;total_expanse = '500';
        $postDummy-&gt;start_date = '22-09-2019';
        $postDummy-&gt;end_date = '22-10-2019';
        $postDummy-&gt;active = '1';
        $postDummy-&gt;updated_at = '2019-09-22';
        $postDummy-&gt;created_at = '2019-09-23';

        //loop 1
        for ($x = 0; $x &lt; 10; $x++) {
             echo '\n----PostSave----\n' . $x;
             $postRepoSave = $this-&gt;getRepoPostImpl();
             dd($postRepoSave-&gt;save2($postDummy));
         }

         //loop 2
        for ($x = 0; $x &lt;= 10; $x++) {
            echo ""\n The number is:"" .  $x;
        }
    }


public function getRepoPostImpl()
    {
        return new Post_Repo_Impl;
    }


}
</code></pre>

<p>Loop 1 is saving only one data, the loop also running one time. Loop 2 is working well, printing 10 lines. </p>

<p>If i copy the same method multiple times in ""testMain()"", it is saving more than one entry, as many as times i have copied the method. Below code will save 3 entries in database.</p>

<pre><code>    public function testMain()
        {
            echo ""\n &gt;----------- Test Name : "" . get_class($
            $this-&gt;postSave();
            $this-&gt;postSave();
            $this-&gt;postSave();
        } //test:main
</code></pre>

<p>Using a loop in testMain(), also provide same result, saving one entry.</p>

<pre><code>public function testMain()
    {
        echo ""\n &gt;----------- Test Name : "" . get_class($this);
        for ($x = 0; $x &lt; 10; $x++) {
            $this-&gt;postSave();
        }
    } //test:main
</code></pre>

<p><strong>Repository code:</strong></p>

<pre><code>class Post_Repo_Impl implements Post_Repo_I
{
    public function save2(Post $post)
    {
        $saveStatus = true;
        try {
            $post-&gt;save();
        } catch (Exception $e) {
            $saveStatus = false;
            error_log(""Saveing Post Failed. : "" . $e);
        }
        return $saveStatus;
    }
}
</code></pre>

<p>Why i am not able to save multiple entries by for loop, is there any way to do so?</p>

<p><strong>Update :</strong>
instantiated the ""post object"" inside the loop, doesn't solve the issue.</p>

<pre><code>for ($x = 0; $x &lt; 10; $x++) {
            $postDummy = new Post();
            // $postDummy-&gt;id ='';
            $postDummy-&gt;user_id = 'Tst';
            $postDummy-&gt;title = 'Post Save Repo Test.';
            $postDummy-&gt;description = 'UnitTesting of URLs';
            $postDummy-&gt;total_needed = '2000';
            $postDummy-&gt;total_collected = '1000';
            $postDummy-&gt;total_expanse = '500';
            $postDummy-&gt;start_date = '22-09-2019';
            $postDummy-&gt;end_date = '22-10-2019';
            $postDummy-&gt;active = '1';
            $postDummy-&gt;updated_at = '2019-09-22';
            $postDummy-&gt;created_at = '2019-09-22';

            echo '\n----PostSave----\n' . $x;
            $postRepoSave = $this-&gt;getRepoPostImpl();
            dd($postRepoSave-&gt;save2($postDummy));

        }
</code></pre>
",https://stackoverflow.com/questions/58053680/laravel-phpunit-for-loop-not-saving-more-than-one-entry-in-database,"['php', 'laravel', 'eloquent', 'phpunit']",493,True,1,1
mechanism to take code coverage using cppunit,"<ul>
<li>I need to take the code coverage of my product code. </li>
<li>We use cppunit for unit testing. The complete code is in cpp. </li>
<li>Compilation of code takes place using make files. </li>
<li>Is there any way to take the code coverage using cppunit?</li>
<li>We do not use linux. </li>
<li>We use Keil for debugging and eclipse for code browsing. </li>
</ul>
",https://stackoverflow.com/questions/54708058/mechanism-to-take-code-coverage-using-cppunit,"['c++', 'arm', 'code-coverage', 'keil', 'cppunit']",257,False,0,1
Maven build fails even after unit test is successful,"<p>I am working on a sample to demonstrate unit testing with spring batch. During maven build I could see that the unit test executed successfully but still build fails with below error.</p>

<p>Batch test executed successfully. Below is the output</p>

<pre><code>2019-09-29 16:30:43.276  INFO 8065 --- [           main] o.s.b.a.b.JobLauncherCommandLineRunner   : Running default command line with: []
2019-09-29 16:30:43.402  INFO 8065 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=transactionProcessingJob]] launched with the following parameters: [{}]
2019-09-29 16:30:43.434  INFO 8065 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [transactionImportStep]
Hibernate: call next value for transaction_entry_seq
Hibernate: call next value for transaction_entry_seq
Hibernate: insert into transaction_entry (account_no, amount, transaction_date, transaction_type, id) values (?, ?, ?, ?, ?)
Hibernate: insert into transaction_entry (account_no, amount, transaction_date, transaction_type, id) values (?, ?, ?, ?, ?)
Hibernate: insert into transaction_entry (account_no, amount, transaction_date, transaction_type, id) values (?, ?, ?, ?, ?)
Hibernate: insert into transaction_entry (account_no, amount, transaction_date, transaction_type, id) values (?, ?, ?, ?, ?)
Hibernate: insert into transaction_entry (account_no, amount, transaction_date, transaction_type, id) values (?, ?, ?, ?, ?)
Hibernate: insert into transaction_entry (account_no, amount, transaction_date, transaction_type, id) values (?, ?, ?, ?, ?)
Hibernate: insert into transaction_entry (account_no, amount, transaction_date, transaction_type, id) values (?, ?, ?, ?, ?)
Hibernate: insert into transaction_entry (account_no, amount, transaction_date, transaction_type, id) values (?, ?, ?, ?, ?)
Hibernate: insert into transaction_entry (account_no, amount, transaction_date, transaction_type, id) values (?, ?, ?, ?, ?)
2019-09-29 16:30:43.696  INFO 8065 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=transactionProcessingJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
</code></pre>

<p>After unit text execution, build fails with below error</p>

<pre><code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.batch.test.JobLauncherTestUtils' 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:1658) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1217) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]         ... 31 common frames omitted
</code></pre>

<p>Full source code of the sample is available <a href=""https://github.com/st-spring-batch-samples/unit-testing"" rel=""nofollow noreferrer"">here</a></p>
",https://stackoverflow.com/questions/58153666/maven-build-fails-even-after-unit-test-is-successful,"['spring-boot', 'spring-batch']",120,True,0,2
How to pass props to test component?,"<p>I am learning about unit-testing in Vue and try to test component according to this article <a href=""https://alligator.io/vuejs/testing-vue-with-jest/"" rel=""nofollow noreferrer"">https://alligator.io/vuejs/testing-vue-with-jest/</a></p>

<p>I have a component</p>

<pre><code>&lt;template&gt;
    &lt;div&gt;
        &lt;h1 :style=""headingStyles""&gt;{{title}}&lt;/h1&gt;
    &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
    export default {
        data() {
            return {
                headingStyles: {
                    color: this.color
                }
            };
        },
        props: [""title"", ""color""]
    };
&lt;/script&gt;
</code></pre>

<p>and file with test cases</p>

<pre><code>import Vue from 'vue';
import FancyHeading from '../../src/components/FancyHeading';

function mountComponentWithProps (Component, propsData) {
    console.log('props Data', propsData)
    const Constructor = Vue.extend(Component);
    const vm = new Constructor({
        propsData
    }).$mount();

    return vm.$el;
}

describe('FancyHeading.vue', () =&gt; {
    it('should be the correct color', () =&gt; {
        const headingData = mountComponentWithProps(FancyHeading, { color: 'blue' });
        const styleData = headingData.style.getPropertyValue('color');
        console.log(styleData)
        expect(styleData).toEqual('blue');
    });

    it('should have the correct title', () =&gt; {
        const headingData = mountComponentWithProps(FancyHeading, { title: 'Hello, Vue!' });
        const titleData = headingData.textContent;

        expect(titleData).toEqual('Hello, Vue!');
    });
});
</code></pre>

<p>When I run <code>yarn test:unit</code> I receive error</p>

<pre><code>FancyHeading.vue › should be the correct color

    expect(received).toEqual(expected) // deep equality

    Expected: ""blue""
    Received: """"
</code></pre>

<p>Looks like color is empty xtring, but I don't understand why. Can someone explain me and help to pass test?</p>
",https://stackoverflow.com/questions/58571234/how-to-pass-props-to-test-component,"['unit-testing', 'vue.js', 'jestjs']",90,False,0,0
ClassCastException on attempt to mock Querydsl SQLQueryFactory,"<p>Trying to mock SQLQueryFactory of Querydsl for DAO unit testing. Using Mockito's deep stub for the very first time.
Below is the minimal code which fails</p>

<pre><code>@Test
void tryMockQueryDsl() {
    SQLQueryFactory sql = Mockito.mock(SQLQueryFactory.class, Mockito.RETURNS_DEEP_STUBS);
    Mockito.when(sql.select(ArgumentMatchers.&lt;Expression&lt;?&gt;&gt;any())
            .from(ArgumentMatchers.&lt;Expression&lt;?&gt;&gt;any())
            .fetchFirst()
    ).thenReturn(null);
}
</code></pre>

<p>with the following exception:</p>

<blockquote>
  <p>java.lang.ClassCastException: class com.querydsl.sql.ProjectableSQLQuery$MockitoMock$1584151766 cannot be cast to class com.querydsl.sql.SQLQuery (com.querydsl.sql.ProjectableSQLQuery$MockitoMock$1584151766 and com.querydsl.sql.SQLQuery are in unnamed module of loader 'app')</p>
</blockquote>

<p>What can be the problem?</p>
",https://stackoverflow.com/questions/59135725/classcastexception-on-attempt-to-mock-querydsl-sqlqueryfactory,"['mockito', 'classcastexception', 'querydsl']",451,False,0,1
Mocking GetItemLinqQueryable and Extension method ToFeedIterator(),"<p>We are using Azure cosmos client V3.
For fetching data we are using GetItemLinqQueryable and ToFeedIterator for making it Async. It works well however while mocking/unit testing we are getting error related to ToFeedIterator</p>

<p>Code:</p>

<pre><code>IOrderedQueryable&lt;T&gt; linqQueryable = _container.GetItemLinqQueryable&lt;T&gt;(requestOptions: requestOptions);
var feedIterator = linqQueryable.Where(predicate).ToFeedIterator();
</code></pre>

<p>For mocking 
UnitTestCode Code:</p>

<pre><code>var _mockResponse = new Mock&lt;ItemResponse&lt;Test&gt;&gt;();
mockContainer.Setup(x =&gt; x.GetItemLinqQueryable&lt;Test&gt;(It.IsAny&lt;bool&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;QueryRequestOptions&gt;())).Returns(queryable);
</code></pre>

<p>It does return 1 records from GetItemLinqQueryable however ToFeedIterator() fails saying <strong>System.ArgumentOutOfRangeException: 'ToFeedIterator is only supported on cosmos LINQ query operations
Parameter name: linqQuery'</strong></p>
",https://stackoverflow.com/questions/58212697/mocking-getitemlinqqueryable-and-extension-method-tofeediterator,"['c#', 'moq', 'azure-cosmosdb']",4066,True,6,1
TypeError: module.Name.replace is not a function,"<p>I am new to unit testing and i am not able to identify/ set up the right props for the following:
      js file    REACT / JS  jest/enzyme</p>

<pre class=""lang-js prettyprint-override""><code>populateModuleDropdown = (moduleList) =&gt; {
  let modules = moduleList.map(module =&gt; {
    return (
      &lt;DropdownItem key={module.ModuleId} onClick={() =&gt; {
      this.props.setTarget(null);
      }}&gt;
      &lt;Link className='full-link'
      onClick={e =&gt; {if(this.props.module.moduleId === module.ModuleId){e.preventDefault()}}}
      to={'/'+module.Name.replace(/ /g,'')}&gt;
      {module.Name}
      &lt;/Link&gt;
      &lt;/DropdownItem&gt;
    )
  })
}
</code></pre>

<p>I have done some similar files and they all look fine and passing properly, but  unable to identify and fix the following error. Please take a look at 
 let mockmodules </p>

<p>Test.js</p>

<pre class=""lang-js prettyprint-override""><code>configure({adapter: new Adapter()});

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

  let tree;
  let baseProps;
  let mockdefaultData;
  let mockmodule = {
    Name:""test"",
    moduleId:{},

    beforeEach(() =&gt; {
      module : mockmodule,

      it (' Should render without a Module props',() =&gt; {
        baseProps = {
          ...baseProps,
          module: {},
        };
        // code
      });

      it(' Should render with ALL of the props', () =&gt; {
        //code

      });
    })
  }
})
</code></pre>
",https://stackoverflow.com/questions/54409915/typeerror-module-name-replace-is-not-a-function,"['javascript', 'reactjs', 'unit-testing']",1946,False,0,1
python unittest : Assert the sequence of method calls in unit test,"<p>I have a method which I am unit testing</p>

<pre><code>def some_functionality():
    must_call_first()
    must_call_second()
</code></pre>

<p>My current approach</p>

<pre><code>@patch('module.must_call_first', autospec=True)
@patch('module.must_call_second', autospec=True)
def test_some_functionality(patch_second,patch_first):
     # execute    
     some_functionality()

     # assert
     patch_first.assert_called_once()
     patch_second.assert_called_once()

</code></pre>

<p>Issue:</p>

<ul>
<li>The sequence of method-call for <code>must_call_first</code> and <code>must_call_second</code> will not be tested with my test case.</li>
<li>If I change the actual method and change the order, my test case would still pass. But ideally, it should not!</li>
</ul>

<p>Is there a way I can make sure that the <code>must_call_first</code> method was called before <code>must_call_second</code>.?</p>
",https://stackoverflow.com/questions/57248417/python-unittest-assert-the-sequence-of-method-calls-in-unit-test,"['python', 'unit-testing', 'mocking', 'pytest']",34,False,3,0
Option of using spock lang specification test a Controller,"<p>just searching if spock lang specification can be used to test controllers that uses JDBC interface.   I am not doing RESTful API and not using Grails.  If Spock only supports grails then I guess Junit is another option.  I like how spock mocks classes behaviors and how its code simplicity for unit testing.  Any thoughts or suggestions?</p>
",https://stackoverflow.com/questions/54795713/option-of-using-spock-lang-specification-test-a-controller,"['java', 'unit-testing', 'groovy', 'spock']",56,True,-1,1
Insert values in class without explicit writing them,"<p>I have some huge classes and don't want to write them all out for testing, because it's a huge effort and I could forget some values what makes the test invalid.</p>

<pre><code>Messages = new List&lt;Request.Notif.NotifRuleMessages&gt;
{
    new Request.Notif.NotifRuleMessages
    {
        Code = 1234,
        Message = new List&lt;Request.Notif.NotifRuleMessagesMessage&gt;
        {
            new Request.Notif.NotifMessagesMessage
            {
                Status = new Request.Notif.NotifMessagesMessageStatus
                {
                    Code = 1,
                    Bool = true,
                    Test1 = ""Test"",
                    Test2 = ""Test""
                },
                Rules = new List&lt;Request.Notif.NotifMessagesMessageRule&gt;
                {
                    new Request.Notif.NotifMessagesMessageRule
                    {
                        Lengths = new Request.Notif.NotifMessagesMessageRuleLength
                        {
                            Lenght = 1,
                            Lengths = new List&lt;Request.Notif.NotifMessagesMessageRuleLengthLength&gt;
                            {
                                new Request.Notif.NotifMessagesMessageRuleLengthLength
                                {
                                    Type = ""Test"",
                                    Value = 1
                                }
                            }
                        },
                        Status = new List&lt;Request.Notif.NotifMessagesMessageRuleStatus&gt;
                        {
                            new Request.Notif.NotifMessagesMessageRuleStatus
                            {
                                Test1 = ""Test"",
                                Test2 = ""Test""
</code></pre>

<hr>

<p>Is there a way to automaticly fill all <code>int</code> values with <code>1</code> or <code>0</code> and all <code>string</code> values with <code>Test</code> and especially all <code>objects</code> with the right class <strong>without unit testing and external libs</strong>?</p>
",https://stackoverflow.com/questions/54705054/insert-values-in-class-without-explicit-writing-them,"['c#', 'class', 'testing', 'automation']",190,True,0,1
Jest mock pdfmake and fs.createWriteStream,"<p>I am very new to Jest and unit testing in general. I am trying to generate a test for a piece of code that essentially uses pdfmake and fs.createWriteStream in order to create and write to a pdf file</p>

<p>As I am reading tutorials - and getting confused a bit as it's info I am not used to - I have tried to put together a couple of things. An fs.js module to try and get the writestream mocked. About the pdfmake I am not very sure - could i perhaps skip that and assume I have a target file and therefore mock just the stream creation?</p>

<pre><code>describe('createWriteStream', () =&gt; {
  const MOCK_FILE_INFO = {
    '/path/to/file1.pdf': 'console.log(""file1 pdf contents"");'
  };
})
</code></pre>

<p>Something like the above?</p>

<p>And then just have a result as success for the fs.createWriteStream?</p>

<p>The original code looks something like:</p>

<pre><code>let pdfDoc = new pdfPrinter({
  Roboto: {
    normal: new Buffer(require('pdfmake/build/vfs_fonts.js').pdfMake.vfs['Roboto-Regular.ttf'], 'base64')
  }
}).createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream(path));
pdfDoc.end();
</code></pre>

<p>I understand is not a lot of info but I guess if someone is very aware of unit testing might know how to best shape this. Thanks</p>
",https://stackoverflow.com/questions/57713668/jest-mock-pdfmake-and-fs-createwritestream,"['javascript', 'node.js', 'unit-testing', 'testing', 'jestjs']",1041,False,1,0
How to test that stream emits anything during time interval in unit tests (Flutter)?,"<p>In my code, the function emits value to the stream after one minute. Let's say it is a timer. I want to do unit testing (not widget testing because the function lives in bloc file). I tried to use fakeAsync as described in doc <a href=""https://api.flutter.dev/flutter/quiver.testing.async/FakeAsync-class.html"" rel=""noreferrer"">https://api.flutter.dev/flutter/quiver.testing.async/FakeAsync-class.html</a> but had no luck. Test fails on timeout.
The tested code:</p>

<pre><code>class BarcodeBloc {
  Timer _timer;
  StreamController&lt;bool&gt; _timerFinished;

  BarcodeBloc() {
    _timerFinished = new StreamController();
  }

  Stream&lt;bool&gt; get cameraTimeout =&gt; _timerFinished.stream;

  void _tick() {
    _timerFinished.add(true);
  }

  void startTimer() {
    stopTimer();
    print(""starting timer"");
    _timer = Timer(interval, _tick);
  }

  void stopTimer() {
    if (_timer != null) {
      _timer.cancel();
    }
  }
}
</code></pre>

<p>My code for the test:</p>

<pre><code>void main() {

  test(""After one minute emits true"", () {
    new FakeAsync().run((async) {
       BarcodeBloc barcodeBloc = new BarcodeBloc(preferenceProvider);
       barcodeBloc.startTimer();

       async.elapse(duration);
       expect(barcodeBloc.cameraTimeout, emits(true));
  });
}
</code></pre>
",https://stackoverflow.com/questions/56372855/how-to-test-that-stream-emits-anything-during-time-interval-in-unit-tests-flutt,"['unit-testing', 'flutter']",1933,False,6,1
How to get full test coverage for the react code,"<p>Im new to unit testing , there is a functional component for which I have written some test cases , but unable to get full test coverage with jest and enzyme . Other than function coverage all are covered which I tested with 
<code>npm test -- --coverage</code> . I have added the test coverage command and the test coverage html in the code snippet</p>

<pre><code>const TargetAudience = ({ searchResults }) =&gt; (
    &lt;React.Fragment&gt;
        &lt;div className=""target-audience-header""&gt;Target Audience&lt;/div&gt;
    {searchResults.length &gt; 0 ?
      &lt;Table columns={columns} dataSource={data} /&gt;
      :
      null
    }

    &lt;/React.Fragment&gt;
);
</code></pre>

<pre><code>describe('search results props test', () =&gt; {
    it('expect to render targetAudience component with search results props length &gt; 0 ', ()=&gt; {
        const searchRes = ['a', 'b']; 
        expect(shallow(&lt;TargetAudience searchResults={searchRes} /&gt;)).toMatchSnapshot();
    })

    it('expect to render targetAudience component with search results props length = 0', () =&gt; {
        const searchRes = [];
        expect(shallow(&lt;TargetAudience searchResults={searchRes} /&gt;)).toMatchSnapshot();
    })
})
</code></pre>

<pre><code>describe('test the table component', () =&gt; {
    it('expect to render table component when searchResults props has some 
        values ', ()=&gt; {
        const searchRes = ['a', 'b'];

        const wrapper = shallow(&lt;TargetAudience searchResults={searchRes} /&gt;)

        expect(wrapper.find('Table').length).toBe(1);
        expect(wrapper.find('.target-audience-header').length).toBe(1)
    }) 
    it('render date input correctly with null value', () =&gt; {
        const searchRes = [1, 2];
        const columns = {};
        const wrapper = shallow(&lt;TargetAudience searchResults={searchRes} /&gt;);
        expect(wrapper.find('Table').props().columns).toBe({});
    });
})
</code></pre>

<p>The test Coverage is:</p>

<pre><code>File                                    |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
 src/containers/audience/targetAudience |       80 |      100 |       50 |       80 |                   |
  index.js                              |       80 |      100 |       50 |       80 |                 9 |
</code></pre>

<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;!doctype html&gt;
&lt;html lang=""en""&gt;
&lt;head&gt;
    &lt;title&gt;Code coverage report for src/containers/audience/targetAudience&lt;/title&gt;
    &lt;meta charset=""utf-8"" /&gt;
    &lt;link rel=""stylesheet"" href=""..\..\..\..\prettify.css"" /&gt;
    &lt;link rel=""stylesheet"" href=""..\..\..\..\base.css"" /&gt;
    &lt;meta name=""viewport"" content=""width=device-width, initial-scale=1""&gt;
    &lt;style type='text/css'&gt;
        .coverage-summary .sorter {
            background-image: url(..\..\..\..\sort-arrow-sprite.png);
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class='wrapper'&gt;
  &lt;div class='pad1'&gt;
    &lt;h1&gt;
      &lt;a href=""..\..\..\..\index.html""&gt;All files&lt;/a&gt; src/containers/audience/targetAudience
    &lt;/h1&gt;
    &lt;div class='clearfix'&gt;
      &lt;div class='fl pad1y space-right2'&gt;
        &lt;span class=""strong""&gt;80% &lt;/span&gt;
        &lt;span class=""quiet""&gt;Statements&lt;/span&gt;
        &lt;span class='fraction'&gt;4/5&lt;/span&gt;
      &lt;/div&gt;
      &lt;div class='fl pad1y space-right2'&gt;
        &lt;span class=""strong""&gt;100% &lt;/span&gt;
        &lt;span class=""quiet""&gt;Branches&lt;/span&gt;
        &lt;span class='fraction'&gt;2/2&lt;/span&gt;
      &lt;/div&gt;
      &lt;div class='fl pad1y space-right2'&gt;
        &lt;span class=""strong""&gt;50% &lt;/span&gt;
        &lt;span class=""quiet""&gt;Functions&lt;/span&gt;
        &lt;span class='fraction'&gt;1/2&lt;/span&gt;
      &lt;/div&gt;
      &lt;div class='fl pad1y space-right2'&gt;
        &lt;span class=""strong""&gt;80% &lt;/span&gt;
        &lt;span class=""quiet""&gt;Lines&lt;/span&gt;
        &lt;span class='fraction'&gt;4/5&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;div class='status-line high'&gt;&lt;/div&gt;
&lt;div class=""pad1""&gt;
&lt;table class=""coverage-summary""&gt;
&lt;thead&gt;
&lt;tr&gt;
   &lt;th data-col=""file"" data-fmt=""html"" data-html=""true"" class=""file""&gt;File&lt;/th&gt;
   &lt;th data-col=""pic"" data-type=""number"" data-fmt=""html"" data-html=""true"" class=""pic""&gt;&lt;/th&gt;
   &lt;th data-col=""statements"" data-type=""number"" data-fmt=""pct"" class=""pct""&gt;Statements&lt;/th&gt;
   &lt;th data-col=""statements_raw"" data-type=""number"" data-fmt=""html"" class=""abs""&gt;&lt;/th&gt;
   &lt;th data-col=""branches"" data-type=""number"" data-fmt=""pct"" class=""pct""&gt;Branches&lt;/th&gt;
   &lt;th data-col=""branches_raw"" data-type=""number"" data-fmt=""html"" class=""abs""&gt;&lt;/th&gt;
   &lt;th data-col=""functions"" data-type=""number"" data-fmt=""pct"" class=""pct""&gt;Functions&lt;/th&gt;
   &lt;th data-col=""functions_raw"" data-type=""number"" data-fmt=""html"" class=""abs""&gt;&lt;/th&gt;
   &lt;th data-col=""lines"" data-type=""number"" data-fmt=""pct"" class=""pct""&gt;Lines&lt;/th&gt;
   &lt;th data-col=""lines_raw"" data-type=""number"" data-fmt=""html"" class=""abs""&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
	&lt;td class=""file high"" data-value=""index.js""&gt;&lt;a href=""index.js.html""&gt;index.js&lt;/a&gt;&lt;/td&gt;
	&lt;td data-value=""80"" class=""pic high""&gt;&lt;div class=""chart""&gt;&lt;div class=""cover-fill"" style=""width: 80%;""&gt;&lt;/div&gt;&lt;div class=""cover-empty"" style=""width:20%;""&gt;&lt;/div&gt;&lt;/div&gt;&lt;/td&gt;
	&lt;td data-value=""80"" class=""pct high""&gt;80%&lt;/td&gt;
	&lt;td data-value=""5"" class=""abs high""&gt;4/5&lt;/td&gt;
	&lt;td data-value=""100"" class=""pct high""&gt;100%&lt;/td&gt;
	&lt;td data-value=""2"" class=""abs high""&gt;2/2&lt;/td&gt;
	&lt;td data-value=""50"" class=""pct medium""&gt;50%&lt;/td&gt;
	&lt;td data-value=""2"" class=""abs medium""&gt;1/2&lt;/td&gt;
	&lt;td data-value=""80"" class=""pct high""&gt;80%&lt;/td&gt;
	&lt;td data-value=""5"" class=""abs high""&gt;4/5&lt;/td&gt;
	&lt;/tr&gt;

&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;&lt;div class='push'&gt;&lt;/div&gt;&lt;!-- for sticky footer --&gt;
&lt;/div&gt;&lt;!-- /wrapper --&gt;
&lt;div class='footer quiet pad2 space-top1 center small'&gt;
  Code coverage
  generated by &lt;a href=""https://istanbul.js.org/"" target=""_blank""&gt;istanbul&lt;/a&gt; at Sat Aug 24 2019 09:12:32 GMT+0530 (India Standard Time)
&lt;/div&gt;
&lt;/div&gt;
&lt;script src=""..\..\..\..\prettify.js""&gt;&lt;/script&gt;
&lt;script&gt;
window.onload = function () {
        if (typeof prettyPrint === 'function') {
            prettyPrint();
        }
};
&lt;/script&gt;
&lt;script src=""..\..\..\..\sorter.js""&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/57634808/how-to-get-full-test-coverage-for-the-react-code,"['reactjs', 'testing', 'jestjs', 'enzyme']",5358,False,3,1
Dataflow: string to pubsub message,"<p>I'm trying to make unit testing in Dataflow.</p>

<p>For that test, at the begging, I will start with a simple hardcoded string.</p>

<p>The problem is that I would need to transform that string to a pubsub message. I got the following code to do that:</p>

<pre><code>    // Create a PCollection from string a transform to pubsub message format
    PCollection&lt;PubsubMessage&gt; input = p.apply(""input string"", Create.of(""test"" + 
            """"))
            .apply(""convert to Pub/Sub message"", ParDo.of(new DoFn&lt;String, PubsubMessage&gt;() {
                @ProcessElement
                public void processElement(ProcessContext c) {
                    c.output(new PubsubMessage(c.element().getBytes(), null));
                }
            }));
</code></pre>

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

<pre><code> java.lang.IllegalArgumentException: unable to serialize DoFnWithExecutionInformation{doFn=com.xxx.pipeline.TesterPipeline$1@7b64240d, mainOutputTag=Tag&lt;output&gt;, sideInputMapping={}, schemaInformation=DoFnSchemaInformation{elementConverters=[]}}
    at org.apache.beam.sdk.util.SerializableUtils.serializeToByteArray(SerializableUtils.java:55)
    &lt;...&gt;
Caused by: java.io.NotSerializableException: com.xxx.pipeline.TesterPipeline
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    at org.apache.beam.sdk.util.SerializableUtils.serializeToByteArray(SerializableUtils.java:51)
    ... 50 more
</code></pre>

<p>How I should create the pubsub message from the string?</p>
",https://stackoverflow.com/questions/59375772/dataflow-string-to-pubsub-message,"['java', 'google-cloud-dataflow', 'apache-beam']",1009,True,2,2
TypeError: Cannot read property &#39;getters&#39; of undefined @vue/test-utils,"<p>I am using @vue-test-utils for vuejs unit testing.</p>

<p>My store looks like :</p>

<pre><code>export default {
 root: true,
 state: {
    batches: []
 },
 getters: {
 getBatches: state =&gt; {
    return state.batches
  }
 }
}
</code></pre>

<p>Component Looks like this:</p>

<pre><code>&lt;template&gt;
  &lt;div&gt;
   &lt;p&gt;Batches Work!&lt;/p&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
  import { mapGetters } from ""vuex"";

  export default {
    computed: {
      ...mapGetters({
         getBatches: ""getBatches""
      })
   }
  }; 
 &lt;/script&gt;
</code></pre>

<p>Tests file looks like this:</p>

<pre><code> import { shallowMount, createLocalVue } from '@vue/test-utils'
 import Vuex from 'vuex'
 import Vuetify from 'vuetify'
 import Vue from 'vue'
 import Batches from '../../../src/pages/Batches'

 const $route = {
    path: '/batches'
 }

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

  describe('Batches', () =&gt; {
   let getters, store

   beforeEach(() =&gt; {
    getters = {
     getBatches: () =&gt; jest.fn()
    },
    store = new Vuex.Store({
        getters
    })
 })

 const wrapper = shallowMount(Batches, {
 localVue,
 mocks: {
    $route
   },
   store
 })

 it('Batches is a vue component', () =&gt; {
    expect(wrapper.isVueInstance()).toBeTruthy()
 })

})
</code></pre>

<p>When i run the test, it throws the following:</p>

<pre><code> FAIL  test/unit/pages/batches-test.spec.js
 Batches
   ✕ encountered a declaration exception (2ms)

 ● Batches › encountered a declaration exception

 TypeError: Cannot read property 'getters' of undefined

 at VueComponent.mappedGetter (node_modules/vuex/dist/vuex.common.js:898:73)
 at Watcher.get (node_modules/vue/dist/vue.runtime.common.dev.js:4459:25)
 at Watcher.evaluate (node_modules/vue/dist/vue.runtime.common.dev.js:4564:21)
 at Proxy.computedGetter (node_modules/vue/dist/vue.runtime.common.dev.js:4813:17)
 at Proxy.render (src/pages/Batches.vue:772:20)
 at VueComponent.Vue._render (node_modules/vue/dist/vue.runtime.common.dev.js:3532:22)
 at VueComponent.updateComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4048:21)
 at Watcher.get (node_modules/vue/dist/vue.runtime.common.dev.js:4459:25)
 at new Watcher (node_modules/vue/dist/vue.runtime.common.dev.js:4448:12)
 at mountComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4055:3)
 at VueComponent.Object.&lt;anonymous&gt;.Vue.$mount 
 (node_modules/vue/dist/vue.runtime.common.dev.js:8386:10)
  at init (node_modules/vue/dist/vue.runtime.common.dev.js:3112:13)
  at createComponent (node_modules/vue/dist/vue.runtime.common.dev.js:5952:9)
  at createElm (node_modules/vue/dist/vue.runtime.common.dev.js:5899:9)
  at VueComponent.patch [as __patch__] 
 (node_modules/vue/dist/vue.runtime.common.dev.js:6449:7)
 at VueComponent.Vue._update (node_modules/vue/dist/vue.runtime.common.dev.js:3927:19)
 at VueComponent.updateComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4048:10)
 at Watcher.get (node_modules/vue/dist/vue.runtime.common.dev.js:4459:25)
 at new Watcher (node_modules/vue/dist/vue.runtime.common.dev.js:4448:12)
 at mountComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4055:3)
 at VueComponent.Object.&lt;anonymous&gt;.Vue.$mount 
 (node_modules/vue/dist/vue.runtime.common.dev.js:8386:10)
 at mount (node_modules/@vue/test-utils/dist/vue-test-utils.js:8649:21)
 at shallowMount (node_modules/@vue/test-utils/dist/vue-test-utils.js:8677:10)
 at Suite.Object.&lt;anonymous&gt;.describe (test/unit/pages/batches-test.spec.js:49:21)
 at Object.describe (test/unit/pages/batches-test.spec.js:18:1)

 console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
 [Vue warn]: Error in render: ""TypeError: Cannot read property 'getters' of undefined""
</code></pre>

<p>I have tried all the ways to get my test to work with vuex resources, but I am stuck. I can’t understand Where I am going wrong. Please help me!</p>
",https://stackoverflow.com/questions/58086096/typeerror-cannot-read-property-getters-of-undefined-vue-test-utils,"['javascript', 'vue.js', 'jestjs', 'vuex', 'vue-test-utils']",5434,True,2,2
Unable to find svg element for unit-testing of d3 component in React using enzyme and cheerio,"<p>I have a React component that renders a div element, d3 in another class is used to append a svg element to the above div element.</p>

<p>While unit-testing with enzyme, the find() method is unable to detect the svg element inside the div. This svg element doesn't have any <code>id</code> as it was created through d3. I referred this <a href=""https://github.com/airbnb/enzyme/issues/1510"" rel=""nofollow noreferrer"">https://github.com/airbnb/enzyme/issues/1510</a> but it didn't help.</p>

<p>I referred to another example which uses cheerio to detect html elements but that didn't work either. <a href=""https://medium.com/successivetech/unit-testing-react-d3-with-enzyme-and-jest-108735046535"" rel=""nofollow noreferrer"">https://medium.com/successivetech/unit-testing-react-d3-with-enzyme-and-jest-108735046535</a></p>

<p>Below is the code from the test file. The first test passes i.e the div element is rendered but the second test fails.</p>

<pre><code>import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import { configure, mount } from 'enzyme';
import { expect } from 'chai';
import MostConvProds from './MostConvProds'; 
import { MockedProvider } from ""@apollo/react-testing"";
import { getDataAndConfig, getHtml, checkSvg } from './Helper';

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

const setUp = (props={}) =&gt; {
const component = mount(&lt;MockedProvider&gt;&lt;MostConvProds {...props}/&gt; 
&lt;/MockedProvider&gt;);

return component;
};

describe('The component should render according to props', () =&gt; {
    let component;
    beforeEach(() =&gt; {
        const props = {

        count:1,
        loading: false,
        products: [{productName: 'a', productId: '1', count:10},
                   {productName: 'b', productId: '2', count:9},
                   {productName: 'c', productId: '3', count:8},
                   {productName: 'd', productId: '4', count:7},
                   {productName: 'e', productId: '5', count:6}
                  ],
    }
    component = setUp(props);
 });


 it('Should render the div without any errors', () =&gt; {
    const wrapper = component.find('#mostConvProds');
    expect(wrapper).to.have.length(1);
    // const svg = Icons.IconWrapper(props, children);
    // const wrapper1 = wrapper.find('svg').html();
    //expect(wrapper1.find(&lt;rect&gt; &lt;/rect&gt;)).to.have.length(1);
})

it('Should render svg element without any errors', () =&gt; {
   const wrapper = component.find('#mostConvProds');
   expect(getHtml(wrapper, ""svg"")).to.have.length(1); 
   //expect(component.find(`svg[viewBox=""0 0 440 
   //150""]`)).to.have.length(1);  //didn't work
})
})
</code></pre>

<p>The Helper.js file is as follows</p>

<pre><code>const cheerio = require('cheerio');

export const checkSvg = (component) =&gt; {
const $ = getHtml(component, 'svg');
const svgHeight = $('svg').attr('height');
const svgWidth = $('svg').attr('width');
return svgHeight == '150' &amp;&amp; svgWidth == '440';
}

export const getHtml = (component, tag) =&gt; {
const cheerioData = cheerio.load(component.find(tag).html());
return cheerioData;
}
</code></pre>

<p>The error message </p>

<pre><code>Method “html” is meant to be run on 1 node. 0 found instead.

   9 | 
  10 | export const getHtml = (component, tag) =&gt; {
&gt; 11 | const cheerioData = cheerio.load(component.find(tag).html());
     |                                                      ^
  12 | return cheerioData;
  13 | }
</code></pre>

<p>Below is the component that renders the div </p>

<pre><code>class d3Component extends Component {

componentDidMount(){
    new d3class(this.refs.mostConChart, this.props.products)
}

render() {
    return (
        &lt;div id={'mostConvProds'} className={style.container} 
             ref='mostConChart'&gt; &lt;/div&gt;
     )
   }
}
</code></pre>

<p>the <code>d3Class</code> is where all the d3 code is present. </p>

<pre><code>import * as d3 from 'd3'

const HEIGHT = 150;
const WIDTH = 350;

export default class d3Class {
constructor(element, product) {
    const svg = d3.select(element)
        .append(""svg"")
        .attr(""width"", WIDTH + 90)
        .attr(""height"", HEIGHT)
        .attr(""x"",0)
        .attr(""y"",0)


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

<p>Any help will be appreciated.</p>
",https://stackoverflow.com/questions/58057684/unable-to-find-svg-element-for-unit-testing-of-d3-component-in-react-using-enzym,"['reactjs', 'd3.js', 'svg', 'jestjs', 'enzyme']",3974,True,0,2
Karma+Jasmine function that reads a json file always fails,"<h2>I'm having a hard time understanding how unit testing with Karma+Jasmine works exactly</h2>
<p>I'm trying to setup some Unit Tests for my AngularJS app but I'm running into a problem where the Tests don't seem to run a function properly.</p>
<p>I have a function that reads a json file through a $http.get request and populates an array, but when I set up in my unit test to expect the length of the array  <code>expect(array.length).toBe(10)</code>, it always fails, yet that is the length of the array when I run the App normally. Actually if I print the length in the <code>console.log</code> on the unit test it seems to always be stuck at 1.</p>
<p>But for example if I check some of the variables I declare manually then the expect function works properly.</p>
<p>Can anyone tell me what exactly am I missing here? It's seems i'm missing some of the fundamentals on how unit testing with Karma/Jasmine works.</p>
<p>Any help would be greatly appreciated. Thanks!</p>
",https://stackoverflow.com/questions/58801541/karmajasmine-function-that-reads-a-json-file-always-fails,"['angularjs', 'unit-testing', 'jasmine', 'karma-runner']",344,True,0,2
How to fix ClassCastException: in javax.ws.rs-api RuntimeDelegate.class,"<p>My service works during unit testing but getting runtime errors. There is a main connector and then there are plugins within the framework.</p>

<pre><code>
    ClassCastException: attempting to cast jar: file:/dir/
    /connector-g935ea6c/service/lib/javax.ws.rs-api-2.1.jar!
    /javax/ws/rs/ext/RuntimeDelegate.class

    to 

    jar:file:/dir/services/var/data/plugins/install/new-connector-6/asset-plugin.jar!/javax/ws/rs/ext/RuntimeDelegate.class

</code></pre>

<p>Is there a way I could make sure the cast is fine? Can I make sure they are both the same version?</p>

<p>I unzipped the asset-plugin.jar and looked at the following: 
META-INF/maven/javax.ws.rs/javax.ws.rs-api/pom.properties</p>

<pre><code>version=2.1
groupId=javax.ws.rs
artifactId=javax.ws.rs-api
</code></pre>
",https://stackoverflow.com/questions/55545798/how-to-fix-classcastexception-in-javax-ws-rs-api-runtimedelegate-class,"['java', 'casting', 'runtime-error']",691,False,2,0
Angular Karma/Jasmine unit test case: Scope of test,"<p>I have read several guides on unit testing and I understand that in unit testing, I am only supposed to test the logic in that component. Any children component should be tested separately. However, I am still confused about what to test.</p>

<p>E.g. scenario
I have an overview component which has 2 children components, <code>&lt;app-refresh-button&gt;</code> and <code>&lt;canvas baseChart ...&gt;</code>, which is using a wrapper lib, ng2-charts (chartjs).</p>

<pre><code>&lt;h1&gt;Overview&lt;/h1&gt;

&lt;app-refresh-button 
  [isLoading]=""isLoading""
  (onIntervalChange)=""onSelectNewInterval($event)"" 
  (onRefresh)=""onRefreshManualClick($event)""&gt;
&lt;/app-refresh-button&gt;

&lt;canvas baseChart 
    [datasets]=""lineChartData""
    ... ...
    (chartclick)=""onChartClicked($event)""
&lt;/canvas&gt;
</code></pre>

<p>Upon clicking on the refresh button, data points will be inserted into the lineChartData array and be plotted on the graph.</p>

<p>Now, here's where I am confused:</p>

<ul>
<li>Since <code>&lt;app-refresh-button&gt;</code> is a child component, I do not test it in <strong>unit test</strong>, is that correct?</li>
<li>If so, the logic in refresh button and the plotting of the graph is linked together, if I do not test them together, how do I know they are working together???</li>
<li>What about functions such as ""pushingNewDataPoints()"", which pushes new data into the lineChartData array, that are also in this overview component, do I test them?</li>
</ul>
",https://stackoverflow.com/questions/56558682/angular-karma-jasmine-unit-test-case-scope-of-test,"['angular', 'unit-testing', 'karma-jasmine']",841,True,0,2
How to find &quot;hits&quot; source in test coverage Android Studio,"<p>I am currently unit testing an Android application (using Android Studio), with interest for the code coverage.</p>

<p>I found out it is possible for every line of code to know its number of ""hits"" (i.e. the number of time the line was executed in launched tests). </p>

<p>But is there a way to find out which test resulted in this hit ? </p>

<p>Thanks. </p>
",https://stackoverflow.com/questions/58625520/how-to-find-hits-source-in-test-coverage-android-studio,"['android', 'unit-testing', 'android-studio', 'code-coverage']",79,False,2,0
What are the functional differences in these 3 pytest fixtures?,"<p>I'm relatively new to pytest-style unit testing, and I'm trying to learn more about pytest fixtures.  I'm not passing a scope argument to the fixture, so I know that the scope is ""function"".  Are there any functional differences in these 3 styles of simple fixtures?  Why would one approach be favored over the others?</p>

<pre><code>@pytest.fixture()
@patch('a.b.c.structlog.get_logger')
def fixture_classQ(mock_log):
    handler = MagicMock(spec=WidgetHandler)
    return ClassQ(handler)
</code></pre>

<pre><code>@pytest.fixture()
def fixture_classQ():
    with patch('a.b.c.structlog.get_logger'):
        handler = MagicMock(spec=WidgetHandler)
        return ClassQ(handler)
</code></pre>

<pre><code>@pytest.yield_fixture()
def fixture_classQ():
    with patch('a.b.c.structlog.get_logger'):
        handler = MagicMock(spec=WidgetHandler)
        yield ClassQ(handler)
</code></pre>

<p>Simple example usage of the fixture:</p>

<pre><code>def test_classQ_str(fixture_classQ):
    assert str(fixture_classQ) == ""This is ClassQ""
</code></pre>

<p>Thanks.</p>
",https://stackoverflow.com/questions/54257472/what-are-the-functional-differences-in-these-3-pytest-fixtures,"['python', 'unit-testing', 'pytest']",397,True,2,1
Testing express application with mongodb,"<p>I have a question regarding the different tests for a node and specifically an express application. 
I am new to node/express coming from a PHP background, so have a few questions.</p>

<p>I know about unit testing, using things like PHPUnit, so I have read about about Jest. My specific questions regarding jest and unit testing in an application like express. Is should I be breaking my code apart more? It currently is quite together my routes are basically where all my business logic is found. Which means it's difficult to unit test?</p>

<p>Then with something else like end to end testing, I am looking at testcafe. For this I am really unsure how to get past my authentication and furthermore how to test on my local machine, before pushing code to production.</p>

<p>Full disclosure, I have a CI setup to my main branch, so I am looking to implement these tests to stop me merging breaking code to my master branch and breaking the production site.</p>
",https://stackoverflow.com/questions/59220683/testing-express-application-with-mongodb,"['node.js', 'unit-testing', 'express', 'jestjs', 'end-to-end']",212,True,0,2
How to configure xUnit Mock for Prism Application?,"<p>I am new to xUnit and with the help of <code>Prism Template Studio</code> I created new Prism <code>xUnit</code> test project, which by default created one <code>PrismAppMock.cs</code> file as below:</p>

<pre><code> // This should implement your application class -- What does it means?
    public class PrismAppMock : PrismApplicationBase
    {
        public PrismAppMock(IPlatformInitializer initializer)
            : base(initializer)
        {
        }

        protected override IContainerExtension CreateContainerExtension()
        {
            return null;
        }

        protected override void OnInitialized()
        {

        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {

        }
    }
</code></pre>

<p>On running the test it is throwing null exception as container is not resolved.</p>

<p>I tried to use <code>UnityContainerExtension</code> but as it is abstract class I can't use it directly. </p>

<pre><code> protected override IContainerExtension CreateContainerExtension()
        {
            return new UnityContainerExtension();
        }
</code></pre>

<p>Can anybody suggest on how to initialise <code>PrismAppMock</code> for unit testing.</p>
",https://stackoverflow.com/questions/54859723/how-to-configure-xunit-mock-for-prism-application,"['xamarin.forms', 'unity-container', 'prism', 'xunit']",264,False,2,0
How test an Add method in service layer?,"<p>I read that generally private methods has no need to unit testing because they are tested by public methods. So what should I do in service layer?</p>

<p>I have a service layer and a method to add an article to database. This method checks some logics about article and its files then save it via repository:</p>

<pre><code>public void AddArticle(ArticleDto article)
{
    CheckArticleFiles(article);

    CheckArticleTitle(article.Title);
    CheckArticleSummary(article.Summary);
    CheckArticleBody(article.Body);

    _articleRepository.AddArticle(article.MapToDbModel());
    _articleRepository.SaveChanges();
}
</code></pre>

<p>All of the checking codes are public now to enable them for testing which I think it's not the correct way(because of OOP principles). And on the other hand if I change them to private they should be tested by <strong>AddArticle</strong> method. In this case I think that it's not a unit testing. because it is not a unit and this method act as an orchestrator.</p>

<p>This situation is happen if I use domain model which has its private logics. And <strong>the logics are the most important part need to test which no need to be public and even protected</strong> </p>

<p>So what are my mistakes here?</p>
",https://stackoverflow.com/questions/55490520/how-test-an-add-method-in-service-layer,"['java', 'unit-testing']",157,True,0,2
ForEach in SwiftUI Warning Issue,"<p>I have been using SwiftUI for a few months now an I am having difficulty with using ForEach.
I am aware that the <code>ForEach</code> protocol demands a unique identifier, but I have used <code>/.self</code> to overcome that aspect of the protocol.
Now unit testing a ForEach statement but I am getting a warning which is preventing build.</p>

<blockquote>
  <p>Warning is <strong>Result of 'ForEach' initializer is
  unused</strong></p>
</blockquote>

<pre><code>import SwiftUI

struct GetdOrderView: View {

@State private var myFamily = [""Ufuoma"",""Efe"",""David"",""Vicky"",""Beth""]


    //The use of ForEach
    func myForachOne() {

        ForEach((0 ... myFamily.count), id: \.self) {member in

            VStack {
            Text(""\(member)"")
        }

        }
    }


    var body: some View {

    Text(""Hello world"")


    }        

}
</code></pre>
",https://stackoverflow.com/questions/59318512/foreach-in-swiftui-warning-issue,['swiftui'],228,True,2,2
Why no more mocks in Arquillian?,"<p>If you go to <a href=""http://arquillian.org/"" rel=""nofollow noreferrer"">Arquillian's home page</a> it says: <code>No more mocks.</code>, but if I have EJB 1 that injects EJB 2 and I want to test EJB 1, how do I simulate EJB 2 if I don't mock it? Is Arquillian used for integration and not unit testing? Why is it a bad practice to mock in Arquillian and what's the alternative?</p>
",https://stackoverflow.com/questions/55346056/why-no-more-mocks-in-arquillian,"['java', 'jakarta-ee', 'mockito', 'ejb', 'jboss-arquillian']",1065,True,1,1
How to assert the validate error in sequelizejs unit test with jest?,"<p>I am unit testing a User model. The user name shouldn't be empty. The unit test is the following:</p>

<pre><code>it('should reject no name', async () =&gt; {
   name = '';
   expect(await User.create(payload())).toThrow();
});
</code></pre>

<p>when <code>payload</code> has all the data except with empty name, the unit test throw the following error:</p>

<pre><code> SequelizeValidationError: Validation error: Invalid validator function: unique,
    Validation error: Invalid validator function: msg,
    Validation error: column ""cell"" does not exist
</code></pre>

<p>However the assertion here <code>.toThrow</code> is not right and the test case still fails.  Tried toBeUndefined with no avail. What is the correct assertion for this type of error?</p>
",https://stackoverflow.com/questions/54730677/how-to-assert-the-validate-error-in-sequelizejs-unit-test-with-jest,"['node.js', 'sequelize.js', 'jestjs']",1673,True,1,2
Is MSVC 2010 a C++11-standard-compliant compiler,"<p>I was about to use <a href=""https://github.com/google/googletest"" rel=""nofollow noreferrer"">google test</a> for unit testing our <code>MSVC 2010</code> based project, but the <code>README.md</code> file of the <strong>gtest v1.10.x</strong> branch (the current latest) mentions <em>a C++11-standard-compliant compiler</em> in the <em>Build Requirements</em> section.</p>

<p>So is <code>MSVC 2010</code> a C++11-standard-compliant compiler, or should I rather use <strong>gtest v1.7.0</strong> which mentions <em>Microsoft Visual C++ 7.1 or newer</em> in the <em>Windows Requirements</em> section?</p>
",https://stackoverflow.com/questions/59025634/is-msvc-2010-a-c11-standard-compliant-compiler,"['c++', 'c++11', 'visual-studio-2010', 'visual-c++', 'googletest']",356,True,1,2
How to write PHP Unit Test for Static Methods,"<p>I am very new to PHP Unit Testing. I am trying to create Unit Test for the following function:</p>

<pre><code>    $context = $args[0];

    if (Subscriber::instance()-&gt;isSubscriber()) {
        $context['body_class'] .= ' ' . $this-&gt;bodyClass;
    }

    return $context;
</code></pre>

<p>Which is very simple which adds classname in array if User is subscriber. Subscriber is class which has has a static instance method which returns true or false.</p>

<p>so far I have written this but I don't think this is correct:</p>

<pre><code>$subscriber = $this-&gt;getMockBuilder(Subscriber::class)
    -&gt;disableOriginalConstructor()
    -&gt;setMethods(['isSubscriber'])
    -&gt;getMock();

$subscriber-&gt;expects($this-&gt;once())
    -&gt;method('isSubscriber')
    -&gt;will($this-&gt;returnValue(true));

$this-&gt;assertInternalType('bool',$subscriber-&gt;isSubscriber());
</code></pre>

<p>Any help would be appreciated.</p>
",https://stackoverflow.com/questions/54256172/how-to-write-php-unit-test-for-static-methods,['phpunit'],6385,True,4,2
CLion: run tests before build,"<p>I made a project in CLion (C++ + CMake) where I have a <em>shared library</em> project with 2 configurations <strong>Debug | Release</strong>. I have also implemented google tests for unit testing. </p>

<p>When the configuration is <strong>Release</strong> I would like to run some tests (or all) before the build. When the tests fail the library should <strong>not</strong> be build.</p>

<p>Is this possible? If so how?</p>
",https://stackoverflow.com/questions/58634504/clion-run-tests-before-build,"['cmake', 'automated-tests', 'googletest', 'clion', 'jetbrains-ide']",353,True,1,1
"In the unit test of TestNG, nullPointerException is always reported when using the mokito stub function, I did not find a solution","<p>This is a springmvc project based on gradle, I'm unit testing it using TestNG. When I mock a service layer class and stub its methods, ""<code>when (). ThenReturn ()</code>"" keeps reporting NullPointerException, I tried Many solutions on this site are not suitable for my situation.</p>

<p>controller:</p>

<pre><code>package app.dnatask.controller;

import ...

@Slf4j
@RestController
@RequestMapping(value = ""/API/scanresultconfigure"")

public class ScanResultConfigureController extends BaseController {
    @Autowired
    private ScanResultConfigureService scanResultConfigureService;

    @RequestMapping(value = ""/queryScanResultList/{taskId}/{externalname}"", method = RequestMethod.POST)
    public IBaseResult queryscanResultList(final HttpServletRequest request, @PathVariable final String taskId, @PathVariable final String externalname, @RequestBody Map map) throws Exception {
        return runController(new IControllRunner() {
            public void run(IOutResult or, CheckResult cr) throws Exception {
                List&lt;ScanResultTitleConfigurePO&gt; list = scanResultConfigureService.findtitleConfigure(taskId, externalname, map);
                ......
            }
        }
    }
}
</code></pre>

<p>service:</p>

<pre><code>package app.dnatask.service;

import ...

@Slf4j
@Service
public class ScanResultConfigureService {
    @Autowired
    private Demo1 demo1;
    @Autowired
    private Demo2 demo2;
    @Autowired
    private Demo3 demo3;

    public List&lt;ScanResultTitleConfigurePO&gt; findtitleConfigure(String taskId, String externalname, Map m) {
        //Query database
        List&lt;ScanResultTitleConfigurePO&gt; list = scanResultTitleConfigureRepository.findByTaskId(taskId, externalname);
        ......
        retuen list;
    }
}
</code></pre>

<p>unit test:</p>

<pre><code>package app.dnatask.controller;

import ...

@WebAppConfiguration
@ContextConfiguration(classes = {ScanResultConfigureController.class})
@ComponentScan(
        excludeFilters = {
                @ComponentScan.Filter(type = FilterType.ANNOTATION, value = {
                        ComponentScan.class, Configuration.class, ImportResource.class
                })
        },
        useDefaultFilters = false,
        lazyInit = true
)
@EnableWebMvc
public class ScanResultConfigureControllerTest extends AbstractTestNGSpringContextTests {
    @MockBean(answer = Answers.RETURNS_DEEP_STUBS)
    private ScanResultConfigureService scanResultConfigureService;

    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;

    @BeforeMethod
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).dispatchOptions(true).build();
        Demo1 demo1 = mock(Demo1.class,Answers.RETURNS_DEEP_STUBS);
        Demo2 demo2 = mock(Demo2.class,Answers.RETURNS_DEEP_STUBS);
        Demo3 demo3 = mock(Demo3.class,Answers.RETURNS_DEEP_STUBS);
    }

     @Test
    public void testQueryscanResultList() throws Exception {
        Map&lt;String, String&gt; testMap = new HashMap&lt;&gt;();
        testMap.put(""key1"", ""value1"");
        testMap.put(""key2"", ""value2"");
        String requestJson = JSONObject.toJSONString(testMap);
        List testList = new ArrayList();
        testList.add(""test1"");
        testList.add(""test2"");

        when(scanResultConfigureService.findtitleConfigure(anyString(), anyString(), anyMap())).thenReturn(testList);

        MvcResult mvcResult = mockMvc.perform(
                post(""/API/scanresultconfigure/queryScanResultList/{taskId}/{externalname}"", ""123"", ""abc"")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(requestJson)
        )
                .andExpect(status().isOk())
                .andDo(print())
                .andReturn();
    }
}
</code></pre>

<p>Exception message:</p>

<pre><code>java.lang.NullPointerException
    at app.dnatask.controller.ScanResultConfigureControllerTest.testQueryscanResultList(ScanResultConfigureControllerTest.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
    at org.testng.internal.MethodInvocationHelper$1.runTestMethod(MethodInvocationHelper.java:239)
    at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.run(AbstractTestNGSpringContextTests.java:180)
    at org.testng.internal.MethodInvocationHelper.invokeHookable(MethodInvocationHelper.java:251)
    at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:580)
    at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:172)
    at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
    at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:804)
    at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:145)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.testng.TestRunner.privateRun(TestRunner.java:770)
    at org.testng.TestRunner.run(TestRunner.java:591)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:402)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:396)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:355)
    at org.testng.SuiteRunner.run(SuiteRunner.java:304)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
    at org.testng.TestNG.runSuites(TestNG.java:1032)
    at org.testng.TestNG.run(TestNG.java:1000)
    at org.gradle.api.internal.tasks.testing.testng.TestNGTestClassProcessor.runTests(TestNGTestClassProcessor.java:139)
    at org.gradle.api.internal.tasks.testing.testng.TestNGTestClassProcessor.stop(TestNGTestClassProcessor.java:89)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy1.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:123)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:155)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:137)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
</code></pre>

<p>This problem has bothered me for many days ... I really need your help ..</p>
",https://stackoverflow.com/questions/59449399/in-the-unit-test-of-testng-nullpointerexception-is-always-reported-when-using-t,"['java', 'mockito', 'testng']",385,True,1,2
How to unit test gRPC service in go,"<p>I'm having difficulties in unit testing the gRPC service in go.</p>

<p>I looked at <a href=""https://stackoverflow.com/questions/42102496/testing-a-grpc-service/42103776#42103776"">Testing a gRPC service</a> but it isn't working for me, not sure what I'm doing wrong.</p>

<p><strong>gRPC service implementation for the Add method:</strong></p>

<pre><code>type server struct{}

func main() {
    listener, err := net.Listen(""tcp"", "":4040"")
    if err != nil {
      panic(err)
    }

    srv := grpc.NewServer()
    service.RegisterMathOpServiceServer(srv, &amp;server{})
    reflection.Register(srv)

    if e := srv.Serve(listener); e != nil {
          panic(e)
    }

    fmt.Println(""Service is running on localhost:4040"")
}

func (s *server) Add(ctx context.Context, request *service.AddRequest) 
(*service.AddResponse, error) {
    a, b := request.GetX(), request.GetY()
    result := a + b

    return &amp;service.AddResponse{Answer: result}, nil
}
</code></pre>

<p><strong>Unit Test for the Add method:</strong></p>

<pre class=""lang-golang prettyprint-override""><code>package test

import (
    ""context""
    pb ""mathOp_service/src/service""
    ""testing""
)
func TestAddition(t *testing.T) {
    s := server{}   &lt;-- error occurs here
    req := pb.AddRequest{X: int64(1), Y: int64(2)}
    res, err := s.Add(context.Background(), req)

    if res.Answer != 3 {
        t.Error(""Expected 1 + 2 to equal 3"")
    }
}
</code></pre>

<p><a href=""https://i.stack.imgur.com/Mk0mO.png"" rel=""nofollow noreferrer"">Project Directory structure</a></p>

<p><code>s := server{}</code> throws an error saying <code>undefined: server</code>. </p>

<p>I'm very new to <code>Go</code> and can't find a solution to fix this.</p>
",https://stackoverflow.com/questions/56316982/how-to-unit-test-grpc-service-in-go,"['go', 'grpc', 'grpc-go']",5375,True,1,1
How to write a unit test in Typescript?,"<p>I am new to software testing, and I was wondering how to write a unit test in Typescript.</p>

<p>I know someting about testing, that you have methods like <code>Asser</code> or <code>assertEquals</code> but how to do this in Typescript and do I need to pay attention the staticly typed classes?</p>

<p>I would like to unit test this funtion</p>

<pre><code>function calculateAverage(...numbers: number[]): number {
     let sum = 0
     for (var n in numbers) {
         sum += n
     }
     return sum/numbers.length
}
</code></pre>

<p>So what framework should I use to produce some test that look like this: </p>

<p><code>assertEquals(calculateAverage(1,2,3), 2)</code> // Actual and expected result</p>

<p>Anyone has an advice for what unit testing framework to use?</p>
",https://stackoverflow.com/questions/56241203/how-to-write-a-unit-test-in-typescript,"['typescript', 'unit-testing', 'frameworks']",26500,True,19,1
"In unit testing, how to compare two objects without using operator== which may miss new members?","<p>In unit testing code, which is the best way to test the <code>operator==</code> comparison operator in the hypothesis that new members may have been added to the class? </p>

<p>E.g.:</p>

<pre><code>struct A {
   int a, b;
   bool operator==( const A&amp; other ) const { return( a == other.a &amp;&amp; b == other.b ); }
};

int Test() {
   A a1, a2;
   EXPECT_TRUE( a1 == a2 );
}
</code></pre>

<p>then we change A, adding a new member variable <code>c</code>.
With the current test/comparison operator, we will get false negatives when <code>c</code> differs.</p>

<p>Is there an alternative/low level way to compare two objects?</p>
",https://stackoverflow.com/questions/59093114/in-unit-testing-how-to-compare-two-objects-without-using-operator-which-may-m,"['c++', 'unit-testing', 'comparison-operators']",775,True,1,1
How to run Vue unit testing?,"<p>I'm following this tutorial to implement Vue unit test: <a href=""https://v2.vuejs.org/v2/cookbook/unit-testing-vue-components.html"" rel=""nofollow noreferrer"">https://v2.vuejs.org/v2/cookbook/unit-testing-vue-components.html</a></p>
<p>However, after creating a component and a test component, I have no idea how to actually run the test. My test file is located in test/unit/myfirsttest.spec.js. Do I need to run a command or configure something?</p>
<p>Thanks so much in advance,</p>
",https://stackoverflow.com/questions/56729231/how-to-run-vue-unit-testing,"['unit-testing', 'vue.js']",91,False,0,0
How to enter transaction callback in typeorm?,"<p>I'm kind of new in unit testing and trying to make some test with typeorm.</p>

<p>The code I've is this:</p>

<pre><code>    public executeTransaction(querys: IQueryTransaction[]) {
        return getManager().transaction(async transactionalManager =&gt; {
            for (const query of querys) {
                await transactionalManager.query(query[0], query[1]);
            }
        });
    }
</code></pre>

<p>I need to enter the <code>transaction</code> callBack but can't figured out how to do it. I tried to mock <code>getManager</code> and <code>transaction</code> playing with it, but with no results.</p>

<p>I'm using jest, typeorm and nest.</p>

<p>Someone knows how to do this?.</p>

<p>EDIT: Connecting to the database is not an option</p>
",https://stackoverflow.com/questions/56650804/how-to-enter-transaction-callback-in-typeorm,"['unit-testing', 'jasmine', 'jestjs', 'typeorm']",971,False,3,2
How to properly unit test inequality,"<p>So one of the goals of unit testing is to make sure that future changes/refactors won't break existing functionality. Suppose we have the following method: </p>

<pre><code>public bool LessThanFive(double a) {
  return a &lt; 5;
}
</code></pre>

<p>One way to uni test this is as follow:</p>

<pre><code>public bool LessThanFiveTests_True() {
  const double a = 4;
  Assert.IsTrue(LessThanFive(a))
}
</code></pre>

<p>The problem with this unit test is that if, later on, someone changes the <code>&lt;</code> into <code>&lt;=</code> in <code>LessThanFive</code> method, the test will pass.</p>

<p>What about if we have <code>DateTime</code> instead of <code>double</code>?</p>
",https://stackoverflow.com/questions/54680429/how-to-properly-unit-test-inequality,"['c#', 'unit-testing']",161,True,0,1
"mainwindow.cpp:(.text+0x9): undefined reference to, QT project fails during unit tests","<p>I'm in the middle of submitting a QT project, but the automated unit testing on my course is giving me the following error. I've been trying to figure out what the issue and I can't figure out why. The full error is as follows.</p>

<pre><code>/usr/local/bin/moc -DQT_DEPRECATED_WARNINGS -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_TESTLIB_LIB -DQT_CORE_LIB -DQT_TESTCASE_BUILDDIR='""/submission-repo/student/12/timer""' --include ./moc_predefs.h -I/usr/local/mkspecs/linux-g++ -I/submission-repo/student/12/timer -I/usr/local/include/QtWidgets -I/usr/local/include/QtGui -I/usr/local/include/QtTest -I/usr/local/include/QtCore -I/usr/include/c++/5 -I/usr/include/x86_64-linux-gnu/c++/5 -I/usr/include/c++/5/backward -I/usr/lib/gcc/x86_64-linux-gnu/5/include -I/usr/local/include -I/usr/lib/gcc/x86_64-linux-gnu/5/include-fixed -I/usr/include/x86_64-linux-gnu -I/usr/include tst_timer.cpp -o tst_timer.moc
g++ -c -pipe -O2 -std=gnu++11 -Wall -W -D_REENTRANT -fPIC -DQT_DEPRECATED_WARNINGS -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_TESTLIB_LIB -DQT_CORE_LIB -DQT_TESTCASE_BUILDDIR='""/submission-repo/student/12/timer""' -I. -isystem /usr/local/include/QtWidgets -isystem /usr/local/include/QtGui -isystem /usr/local/include/QtTest -isystem /usr/local/include/QtCore -I. -isystem /usr/include/libdrm -I. -I/usr/local/mkspecs/linux-g++ -o tst_timer.o tst_timer.cpp
g++ -c -pipe -O2 -std=gnu++11 -Wall -W -D_REENTRANT -fPIC -DQT_DEPRECATED_WARNINGS -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_TESTLIB_LIB -DQT_CORE_LIB -DQT_TESTCASE_BUILDDIR='""/submission-repo/student/12/timer""' -I. -isystem /usr/local/include/QtWidgets -isystem /usr/local/include/QtGui -isystem /usr/local/include/QtTest -isystem /usr/local/include/QtCore -I. -isystem /usr/include/libdrm -I. -I/usr/local/mkspecs/linux-g++ -o mainwindow.o mainwindow.cpp
g++ -c -pipe -O2 -std=gnu++11 -Wall -W -D_REENTRANT -fPIC -DQT_DEPRECATED_WARNINGS -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_TESTLIB_LIB -DQT_CORE_LIB -DQT_TESTCASE_BUILDDIR='""/submission-repo/student/12/timer""' -I. -isystem /usr/local/include/QtWidgets -isystem /usr/local/include/QtGui -isystem /usr/local/include/QtTest -isystem /usr/local/include/QtCore -I. -isystem /usr/include/libdrm -I. -I/usr/local/mkspecs/linux-g++ -o moc_mainwindow.o moc_mainwindow.cpp
g++ -Wl,-O1 -Wl,-rpath,/usr/local/lib -o tst_timer tst_timer.o mainwindow.o moc_mainwindow.o   -L/usr/local/lib -lQt5Widgets -lQt5Gui -lQt5Test -lQt5Core -lGL -lpthread 
mainwindow.o: In function `MainWindow::on_startButton_clicked()':
mainwindow.cpp:(.text+0x9): undefined reference to `Stopwatch::isRunning()'
mainwindow.o: In function `MainWindow::on_stopButton_clicked()':
mainwindow.cpp:(.text+0x39): undefined reference to `Stopwatch::isRunning()'
mainwindow.o: In function `MainWindow::MainWindow(QWidget*)':
mainwindow.cpp:(.text+0xf7): undefined reference to `Stopwatch::Stopwatch()'
mainwindow.o: In function `MainWindow::update()':
mainwindow.cpp:(.text+0x592): undefined reference to `Stopwatch::isRunning()'
mainwindow.cpp:(.text+0x5c5): undefined reference to `Stopwatch::getTime()'
mainwindow.o: In function `MainWindow::on_startButton_clicked()':
mainwindow.cpp:(.text+0x1e): undefined reference to `Stopwatch::start()'
mainwindow.o: In function `MainWindow::on_stopButton_clicked()':
mainwindow.cpp:(.text+0x4e): undefined reference to `Stopwatch::stop()'
mainwindow.o: In function `MainWindow::on_resetButton_clicked()':
mainwindow.cpp:(.text+0x88): undefined reference to `Stopwatch::reset()'
collect2: error: ld returned 1 exit status
Makefile:245: recipe for target 'tst_timer' failed
make: *** [tst_timer] Error 1
</code></pre>

<p>Here are my files. </p>

<p><code>mainwindow.hh</code></p>

<pre><code>#ifndef MAINWINDOW_HH
#define MAINWINDOW_HH

#include &lt;QMainWindow&gt;
#include &lt;QTimer&gt;
#include ""stopwatch.hh""

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

    // Normally this member should be in private part of the
    // class, but due to the automated tests it must be more
    // accessible.
    QTimer* timer;

private slots:
    // Add your slots here
    void on_startButton_clicked();
    void on_stopButton_clicked();
    void on_resetButton_clicked();
    void update();

signals:

private:
    Ui::MainWindow *ui;
    Stopwatch* watch;
    // Add other necessary members here
};

#endif // MAINWINDOW_HH
</code></pre>

<p><code>stopwatch.hh</code></p>

<pre><code>#ifndef STOPWATCH_HH
#define STOPWATCH_HH

#include &lt;QAbstractItemModel&gt;
#include &lt;QTime&gt;

class Stopwatch
{
public:
    explicit Stopwatch();
    void start();
    void stop();
    void reset();
    qint64 getTime();
    bool isRunning();
    void setRunning(bool running);


private:
    bool mRunning;
    qint64 mTotalTime;
    qint64 mTempTime;
    QDateTime mStartTime;
    QTime *time;
signals:

public slots:
};

#endif // STOPWATCH_HH
</code></pre>

<p><code>mainwindow.cpp</code></p>

<pre><code>#include ""mainwindow.hh""
#include ""ui_mainwindow.h""
#include &lt;QTimer&gt;
#include &lt;QTime&gt;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    watch(new Stopwatch())
{
    ui-&gt;setupUi(this);

    auto lcdpalette = new QPalette;
    lcdpalette-&gt;setColor(QPalette::Background, QColor(0, 0, 0));
    lcdpalette-&gt;setColor(QPalette::Base, QColor(255, 160, 122));
    lcdpalette-&gt;setColor(QPalette::AlternateBase, QColor(255, 160, 122));


    ui-&gt;lcdNumberMin-&gt;setPalette(*lcdpalette);
    ui-&gt;lcdNumberMin-&gt;setAutoFillBackground(true);
    ui-&gt;lcdNumberSec-&gt;setPalette(*lcdpalette);
    ui-&gt;lcdNumberSec-&gt;setAutoFillBackground(true);

    QObject::connect(ui-&gt;startButton, &amp;QPushButton::clicked,
                     this, &amp;MainWindow::on_startButton_clicked);
    QObject::connect(ui-&gt;stopButton, &amp;QPushButton::clicked,
                     this, &amp;MainWindow::on_stopButton_clicked);
    QObject::connect(ui-&gt;resetButton, &amp;QPushButton::clicked,
                     this, &amp;MainWindow::on_resetButton_clicked);

     timer = new QTimer(this);
     connect(timer, SIGNAL(timeout()), this, SLOT(update()));
     timer-&gt;start(1);

}

MainWindow::~MainWindow()
{
    delete ui;
    delete watch;
}

void MainWindow::on_startButton_clicked()
{
    if(not (watch-&gt;isRunning()))
    {
        watch-&gt;start();
    }
}

void MainWindow::on_stopButton_clicked()
{
    if(watch-&gt;isRunning())
    {
        watch-&gt;stop();
    }
}

void MainWindow::on_resetButton_clicked()
{
    ui-&gt;lcdNumberMin-&gt;display(00);
    ui-&gt;lcdNumberSec-&gt;display(00);
    watch-&gt;reset();
}


// Triggers every 10 milliseconds (every hundredth of a second)
// Updates the time displayed on the stopwatch.
void MainWindow::update()
{
    if(watch-&gt;isRunning())
    {
        qint64 time = watch-&gt;getTime();
        int hour = time / 1000 / 60 / 60;
        int minutes = (time / 1000 / 60) - (hour * 60);
        int seconds = (time / 1000) - (minutes * 60);

        if(seconds &lt; 10) {
            ui-&gt;lcdNumberSec-&gt;display(QStringLiteral(""0%1"").arg(seconds));
        }
        else {
            ui-&gt;lcdNumberSec-&gt;display(QStringLiteral(""%1"").arg(seconds));
        }
        if(minutes &lt; 10) {
            ui-&gt;lcdNumberMin-&gt;display(QStringLiteral(""0%1"").arg(minutes));
        }
        else {
            ui-&gt;lcdNumberMin-&gt;display(QStringLiteral(""%1"").arg(minutes));
        }
    }
}
</code></pre>

<p><code>stopwatch.cpp</code></p>

<pre><code>#include ""stopwatch.hh""

// Default constructor
Stopwatch::Stopwatch() :
    mRunning(false),
    mTotalTime(0),
    mTempTime(0)
{
}

// Starts the stopwatch.
// Instantiates the start time and declares the watch to be running.
void Stopwatch::start()
{
    mStartTime = QDateTime::currentDateTime();
    mRunning = true;
}

// Pauses the stopwatch.
// Saves the current time and declares the watch to not be running.
void Stopwatch::stop()
{
    mTotalTime += mTempTime;
    mRunning = false;
}

// Resets the stopwatch.
// Resets the saved time and declares the watch to not be running.
void Stopwatch::reset()
{
    mTotalTime = 0;
    mRunning = false;
}

// Returns whether the stopwatch is running.
bool Stopwatch::isRunning()
{
    return mRunning;
}

// Sets the state of the stopwatch (running/not running)
void Stopwatch::setRunning(bool running)
{
    mRunning = running;
}

// Returns the current time of the running stopwatch
qint64 Stopwatch::getTime()
{
    mTempTime = mStartTime.msecsTo(QDateTime::currentDateTime());
    qint64 time = mTotalTime + mTempTime;
    return time;
}
</code></pre>

<p><code>timer.pro</code></p>

<pre><code>QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = timer
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += \
        main.cpp \
        mainwindow.cpp \
        stopwatch.cpp

HEADERS += \
        mainwindow.hh \
        stopwatch.hh

FORMS += \
        mainwindow.ui
</code></pre>

<p>I've cleaned and rebuilt project multiple times and it hasn't solved anything. </p>
",https://stackoverflow.com/questions/59130846/mainwindow-cpp-text0x9-undefined-reference-to-qt-project-fails-during-unit,"['c++', 'qt', 'qt-creator']",204,False,0,0
Unit testing a textfield using Formik with Jest / Enzyme,"<p>I am totally lost with unit testing a change in a textfield. I'm using jest + enzyme to change the textfield but policyEffectiveField.props().value is always null.</p>

<p>I've tried to simulate but using 'change' and 'click' from the <a href=""https://github.com/jaredpalmer/formik/blob/f5d76609b222ce583663add279ac76e807e2d0ba/README.md#testing-formik"" rel=""nofollow noreferrer"">formik doc</a>.</p>

<pre><code>policyEffectiveField.simulate('change', {
    // you must add this next line as (Formik calls e.persist() internally)
    persist: () =&gt; {},
    // simulate changing e.target.name and e.target.value
    target: {
      name: 'policyEffectiveDate',
      value: ""07/30/2019"",
    },
  });
  expect(policyEffectiveField.props().value).toEqual(now);
</code></pre>

<p>But policyEffectiveField.props().value is null</p>

<pre><code>it('change policyEffectiveDate textfield ', () =&gt; {
  let now = moment().format('L');
  var mountRTI = mount(&lt;TestRTI forms={[policyEffectiveDate]} /&gt;);
  var policyEffectiveField = mountRTI.find(TextField).find('input').find({ name: 'policyEffectiveDate' });
  policyEffectiveField.simulate('change', {
    // you must add this next line as (Formik calls e.persist() internally)
    persist: () =&gt; {},
    // simulate changing e.target.name and e.target.value
    target: {
      name: 'policyEffectiveDate',
      value: ""07/29/2019"",
    },
  });
  expect(policyEffectiveField.props().value).toEqual(now);
});
</code></pre>

<p>I expected expect(policyEffectiveField.props().value).toEqual(now); to be true, but I am getting the below error</p>

<pre><code>change policyEffectiveDate textfield

expect(received).toEqual(expected) // deep equality

Expected: ""07/30/2019""
Received: undefined

  48 |     },
  49 |   });
&gt; 50 |   expect(policyEffectiveField.props().value).toEqual(now);
</code></pre>
",https://stackoverflow.com/questions/57278710/unit-testing-a-textfield-using-formik-with-jest-enzyme,"['javascript', 'reactjs', 'jestjs', 'enzyme', 'formik']",1674,False,0,1
DebugElement.Nativelement not defined,"<p>I am new to unit testing angular app. I have initialized component.ts variable record.products,record is of type Records. I want to unit test if clicking on delete button is delete function called or not. And this delete will appear in DOM only if this record variable is initialized. I have given code snippet corresponding to these variables. </p>

<p><strong>Template.html</strong></p>

<pre><code>&lt;tr *ngFor=""let product of record.products; let i = index ""&gt;
 &lt;td&gt;
   &lt;button (click)=""delete(i)"" class=""btn1""&gt;Delete&lt;/button&gt;
 &lt;/td&gt;
as you see only if record.product is populated delete button will appear in DOM
</code></pre>

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

<pre><code>record : Record; //Record class is below
 productForm: FormGroup;

products = [
    {
      name:'New Product'
    }]

productTemplate = {
    productid : '1',
    productname:'xyz'

  }


ngOnInit() {

    this.productForm = this.form.group({
      productControl: this.products
    });

    this.record['products'] = [];
    this.addProduct();
  }

  addProduct() {
    let product = JSON.parse(JSON.stringify(this.productTemplate));
    product.id  = 'ent-' + UUID.UUID();
    this.record['products'].push(product);
  }

  deleteProduct(i) {
    this.record['products'].splice(i,1);
  }
</code></pre>

<p><strong>Record.ts</strong></p>

<pre><code>export class Entitlement {
    id: string;
    products:any;
}
</code></pre>

<p><strong>myspec.ts</strong></p>

<pre><code> it('should delete added product by clicking on delete button',()=&gt;{

let mockRecordData:Record;
component.record=mockRecordData; 

// also tried
mockRecordData.products=""some data"";
component.record=mockRecordData; 
let buttons=fixture.debugElement.queryAll(By.css('.btn')).nativeElement;// gives error 

console.log(component.record['products']); 
//expected to print some data but gives only error
})
</code></pre>
",https://stackoverflow.com/questions/55940769/debugelement-nativelement-not-defined,"['angular', 'unit-testing', 'jasmine']",210,False,0,1
Android build system command mm fails with this error &quot;The import org.mockito cannot be resolved&quot;,"<p>I am using <strong>Android</strong> build system command mm to create an <strong>apk</strong> file for unit testing. I use <code>mockito</code> in the test classes and therefore I imported it in my code:</p>

<pre><code>import static org.mockito.Mockito.*;
</code></pre>

<p>mm terminates with this error:</p>

<blockquote>
  <p>ERROR: : The import org.mockito cannot be
  resolved ninja: build stopped: subcommand failed.</p>
</blockquote>

<p>Could anyone know what has caused this issue and how it can be solved?</p>
",https://stackoverflow.com/questions/54913679/android-build-system-command-mm-fails-with-this-error-the-import-org-mockito-ca,['mockito'],61,False,0,0
req.body Undefined When testing,"<p>I am unit testing my express app using Mocha and Chai</p>

<p>When in the test file, I want to use <code>req.body</code> to parse the object to only get undefined in the testing results.</p>

<p>I have body parser already required in the server <code>(app.js)</code></p>

<p>What is I am missing I do get the response. This is calling a route that return a object <code>res.json(response)</code></p>

<pre><code>//Testing File

let chai = require('chai');
let expect  = require('chai').expect;
let request = require('request');
let app = require('../app');
let should = chai.should();


describe('/GET wallet', () =&gt; {
  it('object should have these properties', (done) =&gt; {
    request('http://localhost:3000/theFunction' ,function(error,res,req) {

      expect(res.body).to.have.property('name')


      done();
        });
  });
});
</code></pre>
",https://stackoverflow.com/questions/57918464/req-body-undefined-when-testing,"['javascript', 'node.js', 'express', 'mocha.js', 'chai']",639,False,0,1
How to set up a pipeline for DataFlex open source project in Azure Pipelines?,"<p>I would like to set up a build pipeline for the <a href=""https://github.com/olaeld/DFUnit"" rel=""nofollow noreferrer"">DFUnit</a> (unit testing framework for DataFlex) open source project, using Microsoft's offer of free build pipelines for open source projects.</p>

<p>However, installing the DataFlex build environment may prove hard to script. Can I set up a VM? Are there any other examples of comparable setups in a Windows environment?</p>
",https://stackoverflow.com/questions/55334116/how-to-set-up-a-pipeline-for-dataflex-open-source-project-in-azure-pipelines,"['windows', 'azure-devops', 'open-source', 'azure-pipelines', 'dataflex']",88,True,0,1
Manually fire SpeechRecognizedEvent,"<p>I need to fire the SpeechRecognizedEvent manually for unit testing so I can't  use the EmulateSpeech Method from a SpeechRecognitionEngine</p>

<p>Edit:</p>

<p>I have already encapsulated the SpeechRecognition into a separate Class with its own interface to mock it.</p>

<p>I need to call the Event because I have an AutoResetEvent, which I Set() during the event. The Unit test needs this to proceed.</p>
",https://stackoverflow.com/questions/55262625/manually-fire-speechrecognizedevent,"['c#', 'speech']",82,True,-1,2
Check that number of received calls is within range with NSubstitute,"<p>Is there a way to check with NSubstitute that number of received calls falls within certain range?</p>

<p>I would like to do something like:</p>

<pre><code>myMock.Received(r =&gt; r &gt; 1 &amp;&amp; r &lt;= 5).MyMethod();
</code></pre>

<p>Alternatively, if I could get the exact number of received calls that would do the job as well. I am unit testing retries and timeouts and based on system load and other tests running number of retries can vary during unit test execution.</p>
",https://stackoverflow.com/questions/56013065/check-that-number-of-received-calls-is-within-range-with-nsubstitute,"['c#', 'mocking', 'nsubstitute']",1477,True,3,1
configuring jest and enzyme in existing project is throwing error,"<p>I am working in an existing react project and I want to introduce unit testing in it. For this, I am configuring <code>jest</code> with <code>enzyme</code>. In <code>package.json</code>, I have added below:</p>

<pre><code>""jest"": {
    ""verbose"": true,
    ""setupFilesAfterEnv"": [""&lt;rootDir&gt;src/setupTests.js""],
    ""moduleDirectories"": [
      ""/node_modules""
    ]
  },
</code></pre>

<p>and to <code>yarn test</code>, I have below:</p>

<pre><code>""scripts"": {
    ""start"": ""run-s dev"",
    ""dev"": ""cross-env NODE_ENV=development webpack-dev-server --config webpack.dev.js"",
    ""debug"": ""cross-env NODE_ENV=development webpack-dev-server --config webpack.debug.js"",
    ""build"": ""run-s lint build:no-lint"",
    ""test"": ""jest""
  },
</code></pre>

<p>I have <code>setupTests.js</code> as well in which <code>enzyme</code> is configured:</p>

<pre><code>import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

Enzyme.configure({ adapter: new Adapter() })
</code></pre>

<p><strong>Now, when I run <code>yarn test</code>, I am getting below error:</strong></p>

<pre><code>yarn run v1.12.3
$ jest
 FAIL  src/components/__tests__/TroveV5.test.js
  ● Test suite failed to run

    Cannot find module 'source-map-support' from 'source-map-support.js'

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:230:17)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.352s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code></pre>

<p><strong>Cannot find module 'source-map-support' from 'source-map-support.js'</strong></p>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/57321011/configuring-jest-and-enzyme-in-existing-project-is-throwing-error,"['javascript', 'reactjs', 'jestjs', 'enzyme', 'babel-jest']",226,False,3,0
Injecting DataAccess layer class not allowing to call Controller method,"<p>I am injecting data access layer to write automated unit testing for Datalayer . I am using web api and Dependency injection. We are using Microsoft Enterprise library</p>

<pre><code>    public class DataLayerClass : IDataLayerClass
    {
        Database database;
        public Data Layer Class(Database getdatabase)

        {
            database = getdatabase;
        }
    }
</code></pre>

<p>This is not allowing to call controller method getting below error.</p>

<blockquote>
  <p>""Processing of the HTTP request resulted in an exception. Please see
  the HTTP response returned by the 'Response' property of this
  exception for details.""</p>
</blockquote>
",https://stackoverflow.com/questions/58215193/injecting-dataaccess-layer-class-not-allowing-to-call-controller-method,"['.net', 'api', 'service']",28,False,0,0
Python unittest changing variable seemingly outside of scope,"<p>I have the following Tic-Tac-Toe code:</p>

<pre><code>class TicTacToeBoard:
board = [[0,0,0], [0,0,0], [0,0,0]]

def printBoard(self):
    print(self.board)

def putPiece(self, position1, position2):
    self.board[position1][position2] = 1
</code></pre>

<p>I am unit testing the code, as below:    </p>

<pre><code>def testestablishTicTacToeBoard(self):
    test = TicTacToeBoard()
    self.assertEqual(test.board, [[0,0,0],[0,0,0],[0,0,0]])

def testPutPiece(self):
    test = TicTacToeBoard()
    self.assertEqual(test.board, [[0,0,0],[0,0,0],[0,0,0]])
    test.putPiece(1,1)
    self.assertEqual(test.board, [[0,0,0],[0,1,0],[0,0,0]])
</code></pre>

<p>Before I made the second unit test, the first unit test passed with no problem.  Once I made the second unit test, the first unit test no longer passes with:</p>

<pre><code>self.assertEqual(test.board, [[0,0,0],[0,0,0],[0,0,0]])
AssertionError: Lists differ: [[0, 0, 0], [0, 1, 0], [0, 0, 0]] != [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
</code></pre>

<p>What is happening in the second unit test that is causing the first to no longer pass?</p>
",https://stackoverflow.com/questions/55409445/python-unittest-changing-variable-seemingly-outside-of-scope,"['python', 'python-unittest']",50,True,0,1
Mock behavior of abstract class,"<pre><code>class A extends B
{
    method a(){
        b();
    }
}
abstract class B{
    void method b(){
        //dosomething
    }

}
</code></pre>

<p>I am testing method a of A class and need to mock the behaviour of method b of B class(call to b method should do nothing).
I am using Mockito framework for unit testing and tried spy with class A, but it worked only if another method being called lies in the same class but not in abstract class</p>
",https://stackoverflow.com/questions/57687355/mock-behavior-of-abstract-class,"['unit-testing', 'mockito', 'spy']",26,False,0,0
How to do unit testing for windows form application,"<p>how to do unit testing for windows form application. I have create <strong>Form2</strong> and i want test that form using nUnit , i got this error :</p>

<blockquote>
  <p>Message: 
      System.TypeInitializationException : The type initializer for '...Form2' threw an exception.
        ----> System.Threading.ThreadStateException : ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because
  the current thread is not in a single-threaded apartment.</p>
</blockquote>

<p>Test</p>

<pre><code>[TestFixture,SingleThreaded]
public class FormTest
{

    [SetUp]
    public void Setup()
    {

    }
    [Test]
    public void Form_Test()
    {
        var form = new Form2();

    }
}
</code></pre>

<p>code :
Form2</p>

<pre><code>public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public void SomeThing()
    { 

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

<p>code : Form2.Designer</p>

<pre><code>partial class Form2
{
    /// &lt;summary&gt;
    /// Required designer variable.
    /// &lt;/summary&gt;
    private System.ComponentModel.IContainer components = null;

    /// &lt;summary&gt;
    /// Clean up any resources being used.
    /// &lt;/summary&gt;
    /// &lt;param name=""disposing""&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt;
    protected override void Dispose(bool disposing)
    {
        if (disposing &amp;&amp; (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// &lt;summary&gt;
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// &lt;/summary&gt;
    private void InitializeComponent()
    {
        this.webBrowser1 = new System.Windows.Forms.WebBrowser();
        this.SuspendLayout();
        // 
        // webBrowser1
        // 
        this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.webBrowser1.Location = new System.Drawing.Point(0, 0);
        this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
        this.webBrowser1.Name = ""webBrowser1"";
        this.webBrowser1.Size = new System.Drawing.Size(800, 450);
        this.webBrowser1.TabIndex = 0;
        // 
        // Form2
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(800, 450);
        this.Controls.Add(this.webBrowser1);
        this.Name = ""Form2"";
        this.Text = ""Form2"";
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.WebBrowser webBrowser1;
}
</code></pre>
",https://stackoverflow.com/questions/59171188/how-to-do-unit-testing-for-windows-form-application,"['c#', 'winforms', 'unit-testing']",1280,True,-1,2
InversifyJS uniting testing sinon stub,"<p>I'm trying to write unit testing code on my <code>InversifyJS</code> project. Route testing (using <code>supertest</code>) is working properly. Then try to write <code>sinon</code> <code>stub</code>,<code>spy</code> testing, but couldn't be successful. My sample code is given below:</p>

<p><strong>DemoRoute</strong></p>

<pre><code>@injectable()
class DemoRoute implements IDemoRoute {
 private _demoController:IDemoController;

 constructor( @inject(TYPES.IDemoController) demoController:IDemoController ) {
   this._demoController = demoController;
 }

 create(req: Request, res: Response, next: NextFunction) {
   return this._demoController.create(req.body)
 }
}
</code></pre>

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

<pre><code>import ""reflect-metadata"";
import * as sinon from ""sinon"";
const sandbox = sinon.createSandbox();

describe.only(""Demo Spec 2"", () =&gt; {
   demoController = container.get&lt;IDemoController&gt;(TYPES.IDemoController);

   beforeEach((done) =&gt; {
      insertStub = sandbox.stub(demoController, 'create');
      done();
   });

   afterEach(() =&gt; {
     sandbox.restore();
   });

   it(""Should call demo route url"", async done =&gt; {
     demoRoute  = container.get&lt;IDemoRoute&gt;(TYPES.IDemoRoute);
     const stub =  insertStub.returns(Promise.resolve({ body: { name: ""test xyz"", code: ""test abc""} }));
     const result = await demoRoute.create({body: demoData.validData}, {send: (params) =&gt; params});
     expect(stub).to.have.been.called; // throw error
     done();
   });
}
</code></pre>

<p><strong>Error in unit test</strong></p>

<blockquote>
  <p>UnhandledPromiseRejectionWarning: AssertionError: expected create to have been called at least once, but it was never called</p>
</blockquote>

<p>How can I solve this problem? Thanks in advance.</p>
",https://stackoverflow.com/questions/59103140/inversifyjs-uniting-testing-sinon-stub,"['node.js', 'unit-testing', 'sinon', 'sinon-chai', 'inversifyjs']",1753,True,0,2
Issue with Jest and Enzyme,"<p>I have some issues from Unit testing with Jest and Enzyme.
I'm using React with Typescript, Emotion Framework.
I added a simple unit test on Button Component just to see if the test works.</p>

<pre><code>// button.test.tsx
import React from 'react'
import { shallow } from 'enzyme'
import { Button } from '../button'

describe('First React component test with Enzyme', () =&gt; {
  it('renders without crashing', () =&gt; {
    shallow(&lt;Button/&gt;);
  })
})
</code></pre>

<pre><code>// button.tsx
import React from 'react'
import { FunctionComponent, HTMLAttributes, ButtonHTMLAttributes } from 'react'
import { Icon } from '~/components'
import { styles } from './styles'

interface ButtonProps extends ButtonHTMLAttributes&lt;HTMLButtonElement&gt; {
  onClick?: () =&gt; any

  icon?: string
  color?: 'default' | 'accent' | 'accent-dark' | 'dark'
  size?: 'small' | 'medium' | 'big' | 'large'
  iconSize?: number
  withShadow?: boolean
}

export const Button: FunctionComponent&lt;ButtonProps&gt; = ({
  onClick,
  color = 'default',
  size = 'medium',
  icon,
  withShadow,
  children,
  ...props
}) =&gt; (
  &lt;button
    css={[
      styles.base,
      styles.colors[color],
      styles.sizes[size],
      withShadow &amp;&amp; styles.withShadow,
    ]}
    onClick={onClick}
    {...props}
  &gt;
    {icon &amp;&amp; (
      &lt;span css={styles.icon[color === 'dark' ? 'dark' : 'default']}&gt;
        &lt;Icon icon={icon} size={color === 'dark' ? 16 : 12} /&gt;
      &lt;/span&gt;
    )}
    {children}
  &lt;/button&gt;
)
</code></pre>

<p>And the error is shown as follows:</p>

<pre><code>● Test suite failed to run

    ReferenceError: localStorage is not defined

      12 | 
      13 |   constructor() {
    &gt; 14 |     this.token = localStorage.getItem('token') || null
         |                  ^
      15 | 
      16 |     if (this.token) {
      17 |       this.profile = this.decodeToken(this.token)

      at new UserStore (src/stores/user.ts:14:18)
      at Object.&lt;anonymous&gt; (src/stores/index.ts:4:26)
      at Object.&lt;anonymous&gt; (src/components/header/index.tsx:5:1)
</code></pre>

<p>I'm using ""jsx"":""preserve"" for typescript compile option for build and ""jsx"":""react"" for typescript compile option for jest.</p>

<pre><code>// tsConfig.js
{
  ""compilerOptions"": {
    ""target"": ""esnext"",
    ""module"": ""esnext"",
    ""lib"": [""esnext"", ""dom""],
    ""jsx"": ""preserve"",
    ""types"": [""@emotion/core"", ""@types/node"", ""jest""],

    ""moduleResolution"": ""node"",
    ""allowSyntheticDefaultImports"": true,
    ""esModuleInterop"": true,
    ""experimentalDecorators"": true,

    ""baseUrl"": ""./"",
    ""paths"": {
      ""~/*"": [""src/*""]
    }
  },
  ""presets"": [""@babel/preset-env"", ""@babel/preset-react""],
  ""include"": [""src""]
}
</code></pre>

<p>Here's jest Configuration:</p>

<pre><code>// jestConfig.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['**/src/**/*.test.ts?(x)', '**/?(*.)+(test).ts?(x)'],
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|svg|ttf|woff|woff2)$':
      '&lt;rootDir&gt;/asset-transformer.js',
    '~(.*)$': '&lt;rootDir&gt;/src/$1'
  },
  globals: {
    'ts-jest': {
      tsConfig: {
        jsx: ""react""
      }
    }
  },
  snapshotSerializers: [
      ""enzyme-to-json/serializer""
    ],
    setupFiles: [
      ""./test-shim.js"",
      ""./test-setup.js""
    ],
    moduleFileExtensions: [
      ""ts"",
      ""tsx"",
      ""js"",
      ""jsx""
    ],
    transform: {
      ""^.+\\.js(x)$"": ""babel-jest"",
      ""^.+\\.(ts|tsx)$"": ""./test-preprocessor.js""
    },
    testMatch: [
      ""**/*.test.(ts|tsx|js|jsx)""
    ]
}
</code></pre>

<pre><code>// .babel.rc
{
  ""plugins"": [
    [
      ""transform-inline-environment-variables""
    ],
    [
      ""babel-plugin-jsx-pragmatic"",
      {
        ""export"": ""jsx"",
        ""module"": ""@emotion/core"",
        ""import"": ""___EmotionJSX""
      }
    ],
    [
      ""@babel/plugin-transform-react-jsx"",
      {
        ""pragma"": ""___EmotionJSX"",
        ""pragmaFrag"": ""React.Fragment""
      }
    ],
    [
      ""emotion"",
      {
        ""sourceMap"": true,
        ""autoLabel"": false,
        ""cssPropOptimization"": true
      }
    ],
    [
      ""@babel/plugin-syntax-dynamic-import""
    ]
  ],
  ""presets"": [
    [
      ""@babel/preset-env"",
      {
        ""modules"": false,
        ""targets"": {
          ""node"": ""current""
        }
      }
    ],
    ""@babel/preset-typescript""
  ],
}
</code></pre>
",https://stackoverflow.com/questions/57927385/issue-with-jest-and-enzyme,"['reactjs', 'typescript', 'jestjs', 'enzyme']",1124,True,0,1
Unit Test public method that calls private method and other objects in Java,"<p>I am new to Unit Testing and recently tried my hands on JUnit test and Mockito.</p>

<p>I am trying to unit test a method that calls multiple private methods and also creates private objects of other classes.</p>

<p>How can I unit test the method.</p>

<p>For Example if I have the following code:</p>

<pre><code>class ClassToTest {
    private OuterClass outerClass;
    public Boolean function() {
        outerClass = new OuterClass(20);
        return innerFunction(outerClass.getValue());
    }

    private Boolean innerFunction(int val) {
        if (val % 2 == 0)
            return true;
        return false;
    }
}
</code></pre>

<p>I'm confused how would I test the public function.</p>
",https://stackoverflow.com/questions/54954550/unit-test-public-method-that-calls-private-method-and-other-objects-in-java,"['java', 'unit-testing', 'junit', 'mockito']",2004,True,0,3
How to resolve a &quot;NotSerializableException&quot; thrown when unit testing a plain implementation of &quot;LinearState&quot;,"<p>I have a plain implementation of ""LinearState"" where the only parameter is a UniqueIdentifier. I have a simple Contract to go with it. </p>

<p>When I try to put it through unit testing, however, I keep getting ""NotSerializabeException"".</p>

<p>I'm using the Corda v4 java template. Testing setup with Gradle Runner on IntelliJ. </p>

<p>I've tried annotating the class with @CordaSerializable, and the constructor with @ConstructorForDeserialization</p>

<pre><code>@CordaSerializable
public class InvestorState implements LinearState {

    private final UniqueIdentifier linearId;

    @ConstructorForDeserialization
    public InvestorState(UniqueIdentifier id) {
        this.linearId = id;
    }
...
}
</code></pre>

<blockquote>
<pre><code>Error log:
data(net.corda.core.contracts.ContractState) -&gt; Trying to build an object serializer for com.mycordapp.states.InvestorState, but it is not constructible from its public properties, and so requires a custom serialiser.

java.io.NotSerializableException: data(net.corda.core.contracts.ContractState) -&gt; Trying to build an object serializer for com.mycordapp.states.InvestorState, but it is not constructible from its public properties, and so requires a custom serialiser.

at net.corda.serialization.internal.amqp.ObjectSerializer$Companion.make(ObjectSerializer.kt:18)
at net.corda.serialization.internal.amqp.DefaultLocalSerializerFactory.makeNonCustomSerializer(LocalSerializerFactory.kt:240)
...
</code></pre>
</blockquote>
",https://stackoverflow.com/questions/55501303/how-to-resolve-a-notserializableexception-thrown-when-unit-testing-a-plain-imp,['corda'],819,True,0,2
Google Test Linking Error: File was built for archive which is not the architecture being linked (macOS),"<p>I'm trying to get Google Test (their C++ Unit Testing Framework) working on my Mac, but I'm having an issue when trying to compile the library.</p>

<p>The following commands run fine:</p>

<pre><code>export GTEST_DIR=""path/to/g/test/""

g++ -std=c++11 -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \
    -pthread -c ${GTEST_DIR}/src/gtest-all.cc

ar -rv libgtest.a gtest-all.o
</code></pre>

<p>When trying to actually compile my unit tests, I get a linking error saying <em>""libgtest.a: File was built for archive which is not the architecture being linked (x86/64)""</em>.</p>
",https://stackoverflow.com/questions/55543670/google-test-linking-error-file-was-built-for-archive-which-is-not-the-architect,['googletest'],242,True,0,1
Akka FSM: How to write test case to verify state change?,"<p>I am working with Akka FSM. I have implemented state change with  <code>AbstractFSMWithStash</code>. But I am not sure how to write a unit test case to verify that the actor changes its state. Does Akka provide any methods to access the state of the actor for unit testing? </p>

<p>I could not find much on the documentation page at <a href=""https://doc.akka.io/docs/akka/current/fsm.html"" rel=""nofollow noreferrer"">https://doc.akka.io/docs/akka/current/fsm.html</a>.</p>
",https://stackoverflow.com/questions/58063320/akka-fsm-how-to-write-test-case-to-verify-state-change,"['java', 'akka', 'akka-fsm']",199,False,0,1
FilesDir on mocked context Is null,"<p>I am new to unit testing and currently using Mockito for my Kotlin android application. </p>

<p>I use Koin for dependency injection in my view model class. I have successfully mocked out the dependencies. I pass mockedContext to my viewModel class but when calling mockedContext.filesDir it returns null. </p>

<p>Am I missing something?</p>

<p>HomeViewModelClass</p>

<pre><code>init {
    directoryManager.createDirectory()
}
</code></pre>

<p>DirectoryManager</p>

<pre><code>class DirectoryManager(val context:Context){

    fun createDirectory(){
        val filePath: String = context.filesDir.absolutePath
    }
}
</code></pre>

<p>HomeViewModelTest</p>

<pre><code>@Mock
private lateinit var mockedContext: Context
private lateinit var homeViewModel: HomeViewModel

@Before
fun setup() {
    homeViewModel = HomeViewModel(mockedContext)
}
</code></pre>

<p>Getting null for context.filesDir in DirectoryManager</p>
",https://stackoverflow.com/questions/58997054/filesdir-on-mocked-context-is-null,"['android', 'unit-testing', 'kotlin', 'mockito', 'androidx']",248,True,0,1
CdkDragDrop unit testing events,"<p>So, i've been working on unit testing for my Angular app. I'm using Angular Material and i have a component which uses the drag-drop CDK <a href=""https://material.angular.io/cdk/drag-drop/overview"" rel=""noreferrer"">cdk drag-drop API</a>.</p>

<p>the html code looks like this </p>

<pre><code>&lt;mat-card class=""interventionCard""&gt;
  &lt;div  cdkDropListGroup class=""container""&gt;
    &lt;div cdkDropList
         [cdkDropListData]=""interventionsTodo"" (cdkDropListDropped)=""drop($event)"" class=""dragContainer""&gt;
      &lt;div class=""dragInter"" *ngFor=""let i of interventionsTodo"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;a class=""resetInv"" (click)=""reset()""&gt;&lt;div class=""dragInter""&gt;&lt;img src=""../assets/images/simulation-intervention/noIntervention.svg"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;&lt;/a&gt;&lt;!----&gt;
    &lt;/div&gt;

    &lt;div class=""dropContainer""&gt;
      &lt;div cdkDropList [cdkDropListData]=""interventionsDoneNow"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDoneNow"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;/div&gt;
        &lt;div class=""connectorL""&gt;&lt;/div&gt;
      &lt;div cdkDropList [cdkDropListData]=""interventionsDonePlus5"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDonePlus5"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc""&gt;&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=""connectorL""&gt;&lt;/div&gt;
      &lt;div cdkDropList  [cdkDropListData]=""interventionsDonePlus10"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDonePlus10"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=""connectorL""&gt;&lt;/div&gt;
      &lt;div cdkDropList  [cdkDropListData]=""interventionsDonePlus15"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDonePlus15"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=""connectorL""&gt;&lt;/div&gt;
      &lt;div cdkDropList  [cdkDropListData]=""interventionsDonePlus20"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDonePlus20"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=""connectorL""&gt;&lt;/div&gt;
      &lt;div cdkDropList  [cdkDropListData]=""interventionsDonePlus25"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDonePlus25"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=""connectorL""&gt;&lt;/div&gt;
      &lt;div cdkDropList [cdkDropListData]=""interventionsDonePlus30"" (cdkDropListDropped)=""drop($event)"" class=""dropZone""&gt;
        &lt;div class=""dragInterDropped"" *ngFor=""let i of interventionsDonePlus30"" cdkDrag&gt;&lt;img src=""{{i.imgSrc}}"" class=""interventionIc"" alt=""""&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
</code></pre>

<p>All fine, now i have the cdkDropListDroppet event which calls the function <code>drop()</code></p>

<pre><code>    drop(event: CdkDragDrop&lt;{ imgSrc: string }[], any&gt;) {
     if (event.previousContainer === event.container) {
       moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
     } else {
         if(event.container.data === this.interventionsTodo){
         this.deleteSpecificItemFromTimeline(event.previousContainer.data[0]);
         }else if(event.container.data.length &lt;1){
           copyArrayItem(event.previousContainer.data,
             event.container.data,
             event.previousIndex,
             event.currentIndex);
         }
      }
    }
</code></pre>

<p>this works fine, now im unit testing the angular app (jasmine/karma)
and i am trying to dispatch the CdkDragDrop event so that i can verify the functionality of my <code>drop()</code> function.</p>

<p>So in the angular documentation there is a small chapter on component DOM testing, where its mentioned that you have to get the htmlElement where you want to fire the event which i do like this:<a href=""https://angular.io/guide/testing#component-dom-testing"" rel=""noreferrer"">angular docs</a></p>

<pre><code>    let Dbg = fixture.debugElement;
    let htE = Dbg.nativeElement.querySelector("".dragContainer"");
</code></pre>

<p>now i have the element on which i want to fire the event so full code looks like this</p>

<pre><code>    let Dbg = fixture.debugElement;
      let htE = Dbg.nativeElement.querySelector("".dragContainer"");

      htE.addEventListener('CdkDragDrop', (ev:any) =&gt; {
        component.drop(ev);
      });
      let bla = htE.dispatchEvent(new Event('cdkDropListDropped'));
</code></pre>

<p>So bla returns true, which (if im not wrong) means the event was fired, but nothing seems to happen
<code>fixture.detectchanges()</code> happens automatically..
i tried to debug it to see what is happening but the listenerfunction is never fired and i looked everywhere to find an answer but cant seem to find anything on that kind of eventtesting..</p>
",https://stackoverflow.com/questions/56259451/cdkdragdrop-unit-testing-events,"['angular', 'unit-testing', 'angular-material', 'coded-ui-tests']",9100,True,9,1
best way to specify paths for external text files in the Catch2,"<p>I am writing some unit tests for a function that reads in and parses data from text files, and it got me wondering: what is the best way to specify paths for external text files in the Catch2 unit testing framework? </p>

<p>I couldn't find it in the <a href=""https://github.com/catchorg/Catch2/blob/master/docs/Readme.md#top"" rel=""nofollow noreferrer"">docs</a>, and, even though they are a few questions similar to this one (e.g. <a href=""https://stackoverflow.com/questions/25211110/find-external-test-file-for-unit-test-by-relative-path-c-cmake-guest"">here</a>), none pertain to Catch2 specifically. </p>
",https://stackoverflow.com/questions/58979847/best-way-to-specify-paths-for-external-text-files-in-the-catch2,"['c++', 'unit-testing']",898,True,2,1
Argument of type &#39;By&#39; is not assignable to parameter of type &#39;Predicate&lt;DebugElement&gt;&#39;,"<p>I'm experimenting with Protractor (5.4.2) and trying to test my Angular component.
I created the following test, inspired by the <a href=""https://app.pluralsight.com/library/courses/unit-testing-angular/table-of-contents"" rel=""noreferrer"">Unit testing in Angular course</a> from Joe Eames.</p>

<p><strong>The (working) example from the course</strong>
<a href=""https://i.stack.imgur.com/QKJ6W.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/QKJ6W.png"" alt=""enter image description here""></a></p>

<p><strong>My (faulty) code</strong></p>

<pre class=""lang-js prettyprint-override""><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { DetailsComponent } from './details.component';
import { By } from 'protractor';

describe('DetailsComponent', () =&gt; {
    let fixture: ComponentFixture&lt;DetailsComponent&gt;;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [DetailsComponent]
        })
            .compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(DetailsComponent);

        fixture.detectChanges();
    });

     it('contains 3 titles', () =&gt; {
        expect(fixture.debugElement.queryAll(By.css('.card-title')).length).toBe(3);
    });
});
</code></pre>

<p>However, the following type error occurres in the <em>.query</em> invocation in the test method:</p>

<blockquote>
  <p>Argument of type 'By' is not assignable to parameter of type 'Predicate'.</p>
</blockquote>

<p>I don't understand why this error occurs as my code looks similair to the example.</p>
",https://stackoverflow.com/questions/57058449/argument-of-type-by-is-not-assignable-to-parameter-of-type-predicatedebugele,"['angular', 'typescript', 'jasmine', 'protractor']",3944,True,11,1
How to Unit Test Graphql Resolver functions created using apollo-resolvers,"<p>I have created resolver<strong>s(userresolver.js)</strong> using '<strong>apollo-resolvers</strong>' npm module as below.</p>

<pre><code>import { createResolver } from 'apollo-resolvers';
import {  isInstance } from 'apollo-errors';

const baseResolver = createResolver(
  null,
  (root, args, context, error) =&gt; isInstance(error) ? error : new UnknownError()
);



const users = baseResolver.createResolver(
  (parent, args, { models, me } ) =&gt; {
         return Object.values(models.users);
  }
);

export default {
  Query: {
    users
  }
}
</code></pre>

<p>;</p>

<p>These also work fine when I test the queries after starting the server.</p>

<p>I now want to do unit testing of the resolver functions.</p>

<p>I am not sure how to do that. Can someone help me on how to unit test the resolver functions. I am using <strong>mocha with cha</strong>i for testing my project.</p>
",https://stackoverflow.com/questions/55162083/how-to-unit-test-graphql-resolver-functions-created-using-apollo-resolvers,"['mocha.js', 'graphql', 'chai', 'apollo-server']",3825,True,2,1
jest + enzyme access to instance of a connected component,"<p>I have an issue using jest and enzymes for my unit testing on react. I have a component connected to redux and i want to test a method in my component that update the state. heres's my component :</p>

<pre><code>import React, {Component} from 'react';
import Form from 'react-jsonschema-form';
import pick from 'lodash/pick';
import {bindActionCreators} from 'redux';
import fields from './fields';
import widgets from './widgets';

import {initContainerActions} from '../../utils/actionHelper';
import {actions as modelActions} from './actions';
import {connect} from '../../utils/connect';
import reducerRegistry from '../ReducerRegistry';
import reducer from './reducer';

type StateProperties = {
  roleModelSchema: Object,
  roleUiSchema: Object
};

export type FormContainerProps = {
  model: Object,
  uiSchema: Object,
  userModelLoad: Function,
  isLoading: boolean,
  idContainer: string
};

export class FormContainer extends Component&lt;FormContainerProps, StateProperties&gt; {
  fields = {...fields};

  widgets = {...widgets};

  constructor(props) {
    super(props);
    const {idContainer} = props;
    reducerRegistry.register(idContainer, reducer(idContainer));

    this.state = {
      roleModelSchema: {},
      roleUiSchema: {}
    };
  }

  componentDidMount = async () =&gt; {
    const {userModelLoad} = this.props;
    await userModelLoad();
    this.renderRoleForm();
  };

  renderRoleForm = () =&gt; {
    const {model, uiSchema} = this.props;
    const modelProperties = Object.keys(model.properties);
    const roleUiSchema = pick(uiSchema, modelProperties);

    this.setState({
      roleUiSchema,
      roleModelSchema: model
    });
  };

  render = () =&gt; {
    const {roleModelSchema, roleUiSchema} = this.state;
    const {isLoading} = this.props;

    if (isLoading) {
      return &lt;div&gt;...Loading&lt;/div&gt;;
    }
    return (
      &lt;div className=""container""&gt;
        &lt;div className=""columns""&gt;
          &lt;div className=""column col-12""&gt;
            &lt;Form schema={roleModelSchema} uiSchema={roleUiSchema} liveValidate fields={this.fields} widgets={this.widgets}&gt;
              &lt;div&gt;
                &lt;button type=""submit"" className=""btn btn-primary""&gt;
                  Submit
                &lt;/button&gt;
                &lt;button type=""button""&gt;Cancel&lt;/button&gt;
              &lt;/div&gt;
            &lt;/Form&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
  };
}

const mapDispatchToProps = (dispatch, props) =&gt; {
  const initializedActions = initContainerActions(modelActions, props.idContainer);
  return bindActionCreators(initializedActions, dispatch);
};

export default connect(
  (state, props) =&gt; state[props.idContainer] || {},
  mapDispatchToProps
)(FormContainer);
</code></pre>

<p>And the test :</p>

<pre><code>const mockStore = configureMockStore([]);
const context = React.createContext();

describe('Check if renderRoleForm update state', () =&gt; {
it('renders without crashing', () =&gt; {
// Initialize mockstore with empty state
const initialState = {roleUiSchema: {}};
const store = mockStore(initialState);
const wrapper = shallow(
  &lt;Provider store={store} context={context}&gt;
    &lt;FormContainer model={model} uiSchema={uiSchema} context={context}
/&gt;
  &lt;/Provider&gt;
);

const instance = wrapper.instance();
instance.renderRoleForm();

expect(wrapper.state().roleUiSchema).not.toBeEmpty();
});
});
</code></pre>

<p>The error i have : <strong>TypeError: instance.renderRoleForm is not a function</strong></p>

<p>I tried with mount, dive with shallow and same problem.
If you have any idea :)
Thanks</p>
",https://stackoverflow.com/questions/55102863/jest-enzyme-access-to-instance-of-a-connected-component,"['reactjs', 'jestjs', 'enzyme']",2902,True,2,1
How to fix &#39;cannot read property subscribe&#39; of undefined during angular unit testing?,"<p>Angular6 - Unit testing error “Cannot read property 'subscribe' of undefined”</p>

<p>I was writing a unit test for an angular component which is having several dependencies. One of those dependent service has some properties as observables. I tried to mock this service but is throwing error as in title,</p>

<p>spec.ts</p>

<pre><code>describe('Component', () =&gt; {
let mockService= jasmine.createSpyObj(['property1', 'property2', 'property3']);

beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
declarations: [testComponent],
providers: [
......someOther,
{ provide service, useValue: mockService},
......someOther
]
}).compileComponents();

fixture = TestBed.createComponent(testComponent);
component = fixture.componentInstance;
}));

it('should be created', () =&gt; {
expect(component).toBeTruthy();
  });
});
</code></pre>

<p>ts file has</p>

<pre><code>this.Service.property1.subscribe(() =&gt; {})
this.Service.property2.subscribe(() =&gt; {})
this.Service.property3.subscribe(() =&gt; {})
</code></pre>

<p>Expect test case to pass but fails with error as in title</p>
",https://stackoverflow.com/questions/54017368/how-to-fix-cannot-read-property-subscribe-of-undefined-during-angular-unit-tes,"['angular', 'karma-jasmine']",810,False,2,1
Unit Testing AWS python lambda global variable patch doesnt work,"<p>I am trying to unit test Python based aws lambda code. I tried to use patch to mock environment variables but it throws error.How to handle global variables during unit testing. Any help is appreciated</p>

<p>Tried @mock @patch but nothing seems to be working. When executing the testcase the values seems to be empty</p>

<p>[registration.py]</p>

<pre class=""lang-py prettyprint-override""><code>    import os 

    #Global Variables
    DEBUG = os.environ.get(""EnableLog"")
    rest_endpoint = os.environ.get('restApiEndpoint')
    db_fn_endpoint = rest_endpoint+"":3000/rpc/""

    def lambda_handler(event,context):
    return ""success"" #to see if this works

    if __name__ == ""__main__"":
        lambda_handler('', '')
</code></pre>

<p>Unit Test [test_registration.py]</p>

<pre class=""lang-py prettyprint-override""><code>    import json
    import pytest
    import sys, os
    from mock import patch
    from businesslogic import registration

    @mock.patch.dict(os.environ,{'EnableLog':'True'})
    @mock.patch.dict(os.environ,{'restApiEndpoint':'http://localhost'})

    @patch('registration.restApiEndpoint', 'http://localhost') 


    def test_lambda_handler():
       assert lambda_handler() ==""success""

</code></pre>

<p>When I run pytest test_registration.py</p>

<p>I get below exception </p>

<pre><code>businesslogic\registration.py:6: in &lt;module&gt;
    db_fn_endpoint = rest_endpoint+"":3000/rpc/""
E   TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
</code></pre>
",https://stackoverflow.com/questions/57117736/unit-testing-aws-python-lambda-global-variable-patch-doesnt-work,['python'],1410,False,2,1
Import Kafka MockAdminClient for unit testing my Kafka application using maven,"<p>I would like to use <code>MockAdminClient</code> for unit testing my Kafka application. How can I make <code>MockAdminClient</code> imported using <code>maven</code>?</p>

<p><a href=""https://github.com/apache/kafka/blob/2.3.0/clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java"" rel=""nofollow noreferrer"">https://github.com/apache/kafka/blob/2.3.0/clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java</a></p>

<p><strong>UPDATE:</strong></p>

<p>My kafka-client related pom.xml</p>

<pre><code>&lt;dependency&gt;
   &lt;groupId&gt;org.apache.kafka&lt;/groupId&gt;
   &lt;artifactId&gt;kafka-clients&lt;/artifactId&gt;
    &lt;version&gt;${kafka.version}&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>

<p>By referring test by maven I found sth like this
<a href=""https://stackoverflow.com/questions/29653914/how-can-i-reference-unit-test-classes-of-a-maven-dependency-in-my-java-project"">How can I reference unit test classes of a maven dependency in my java project?</a></p>
",https://stackoverflow.com/questions/57256737/import-kafka-mockadminclient-for-unit-testing-my-kafka-application-using-maven,"['java', 'apache-kafka']",1027,True,2,2
Unit Tests: how to prevent execution of built-in PHP functions,"<p>I'm doing a small library that uses native PHP methods, like <code>json_encode</code> and <code>file_put_contents</code>.</p>

<p>Now, I'm doing unit testing, and <code>json_encode</code> doesn't bother me if it runs, but <code>file_put_contents</code> creates me files when running unit tests.</p>

<p>What ideas do you have about this?</p>

<p>I was thinking of encapsulating these methods in Helpers, eg. JsonHelper, FileHelper, with methods that execute these, and mock them in the original class.</p>

<p>What do you think?</p>
",https://stackoverflow.com/questions/55772332/unit-tests-how-to-prevent-execution-of-built-in-php-functions,"['php', 'unit-testing', 'tdd']",45,False,2,1
How to unit test a Controller method that has a RequestParam of an object?,"<p>I have a controller mapping</p>

<pre><code>@RequestMapping(value = ""/something"", method = RequestMethod.GET)
public String get(@RequestParam(""id"") Person aPerson, Model aModel) {

    aModel.addAttribute(""person"", aPerson);
    return ""index"";
}
</code></pre>

<p>How do I go about testing this through MockMvc?</p>

<p>I can do something like this </p>

<pre><code>mockMvc.perform(get(""/something?id=1"")).andExpect(status().is2xxSuccessful());
</code></pre>

<p>But this will not work since the RequestParam is an object, not a String. The conversion is done by Spring but I'm unit testing the method and do not want to start up the application context. How do I unit test something like this with MockMvc?</p>
",https://stackoverflow.com/questions/55306901/how-to-unit-test-a-controller-method-that-has-a-requestparam-of-an-object,"['java', 'spring', 'mockmvc']",1067,False,2,1
Failing to cover the code and pass the test,"<p>I am a beginner in unit testing. I am trying to write a test script, but I am stuck. I'd like to understand what I am doing wrong.</p>

<pre><code>public ConvertExcelDocumentResponse ConvertExcelDocument(ConvertExcelDocumentRequest request)
        {
            var logger = Bootstrapper.Resolve&lt;ILogger&gt;();

            ConvertExcelDocumentResponse response = new ConvertExcelDocumentResponse();
            if (!string.IsNullOrEmpty(request.FileName) &amp;&amp;
                System.IO.Path.GetExtension(request.FileName).ToLowerInvariant() == "".xls"" &amp;&amp;
                request.FileContent != null &amp;&amp; request.FileContent.Length &gt; 0)
            {
                response.FileContent = _httpClient.ConvertExcelDocument(request.FileContent, request.FileName);
                response.FileName = System.IO.Path.GetFileNameWithoutExtension(request.FileName) + "".xlsx"";
                response.Success = true;
            }
            else
            {
                logger.LogError(""Unable to convert Excel Document '"" + request.FileName + ""' only .xls files are allowed."");
                response.FileContent = new byte[] { };
                response.Success = false;
            }
            return response;
        }
</code></pre>

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

<pre><code>        /// &lt;summary&gt;
        /// Test to Convert XLS to XLSX
        /// &lt;/summary&gt;
        [TestCategory(""DocumentService"")]
        [TestMethod]
        public void Test_ConvertExcelDocumentResponse()
        {
            byte[] filecontent = new byte[] { };
            string filename = ""file"";

            using (ShimsContext.Create())
            {
                ConvertExcelDocumentRequest excelDocumentRequest1 = new ConvertExcelDocumentRequest()
                {
                    FileName = ""filename"",
                    FileContent = new byte[] {},
                };
                ConvertExcelDocumentRequest excelDocumentRequest2 = new ConvertExcelDocumentRequest()
                {
                    FileName = """",
                    FileContent = new byte[] {},    
                };

                ShimDocumentService.AllInstances.ConvertExcelDocumentConvertExcelDocumentRequest = ((@this, Success) =&gt;
                {
                    return new ConvertExcelDocumentResponse()
                    {
                        FileContent=filecontent,
                        Success = true,
                        FileName = filename,
                    };
                });
                ShimHttpClientBase.AllInstances.ConvertWordDocumentByteArrayString = ((@this, fileContent, fileName) =&gt;
                {
                    return fileContent;
                });

                //Act
                ILogger logger = Bootstrapper.Resolve&lt;ILogger&gt;();
                var docService = new DocumentService();

                //IDocumentService DocumentService = Bootstrapper.Resolve&lt;IDocumentService&gt;();
                var excelResponse1 = docService.ConvertExcelDocument(excelDocumentRequest1);
                var excelResponse2 = docService.ConvertExcelDocument(excelDocumentRequest2);

                //Assert
                Assert.AreEqual(excelResponse1.FileContent, filecontent );
                Assert.AreEqual(excelResponse1.FileName, filename);
                Assert.IsTrue(excelResponse1.Success, ""Expects true"");

                Assert.AreEqual(excelResponse2.FileContent, filecontent);
                Assert.AreEqual(excelResponse2.FileName, filename);
                Assert.IsTrue(excelResponse2.Success, ""Expects true"");
            }
        }
</code></pre>

<p>This is passing the test but code coverage is 0%. I don't know where I am going wrong. I tried covering filename = null and few other conditions. not sure why it isn't covering my code</p>
",https://stackoverflow.com/questions/57924820/failing-to-cover-the-code-and-pass-the-test,"['c#', 'unit-testing']",73,False,2,1
How to test leaflet based maps using testcafe?,"<p>We are building a series of tests using TestCafe. How do we test if a point or path in a leaflet control is rendered correctly? To be more specific we are trying to test the lat-lon data of a circle marker in the map. But, we do not have any leaflet map/marker object available in the scope of testcafe scripts. </p>

<p>References:</p>

<p><a href=""https://stackoverflow.com/questions/38099276/how-can-you-unit-test-leaflet-js-maps"">Unit testing leaflet maps</a></p>
",https://stackoverflow.com/questions/56432686/how-to-test-leaflet-based-maps-using-testcafe,"['leaflet', 'automated-tests', 'maps', 'e2e-testing', 'testcafe']",879,True,2,1
Spec has no expectations Angular 7,"<p>I am using Jasmine &amp; Karma for unit testing angular app . I have wrote unit tests like this:</p>

<pre><code>describe('#getAll', async () =&gt; {
    it('#should return user intergration_tester', inject([UsersService], async(service: UsersService) =&gt; {
        await service.getAll('integration_tester', access_token).subscribe(
            user =&gt; {
                expect(user[0].firstName).toContain('Integration');
                done();
            })
      }));

      it('#should return error 404', inject([UsersService], (service: UsersService) =&gt; {
        service.getAll('integration_tester', '').subscribe(
            user =&gt; {expect(user[0].firstName).not.toContain('Integration');},
            err =&gt; { expect(err).toContain('error');}
        )
      }));
})
</code></pre>

<p>When I execute test cases , I see a message SPEC HAS NO EXPECTATIONS for both test cases . I am wondering why it shows spec has no expectations.</p>

<p>Then I followed the suggested solutions in this post: <a href=""https://stackoverflow.com/questions/45578981/spec-has-no-expectations-jasmine-testing-the-callback-function"">Spec has no expectations - Jasmine testing the callback function</a></p>

<p>Using <code>done()</code>:</p>

<pre><code>describe('#getAll', async () =&gt; {
    it('#should return user intergration_tester', inject([UsersService], async(service: UsersService, done) =&gt; {
        await service.getAll('integration_tester', access_token).subscribe(
            user =&gt; {
                expect(user[0].firstName).toContain('Integration');
                done();
            })
      }));

      it('#should return error 404', inject([UsersService], (service: UsersService, done) =&gt; {
        service.getAll('integration_tester', '').subscribe(
            user =&gt; {expect(user[0].firstName).not.toContain('Integration'); done();},
            err =&gt; { expect(err).toContain('error'); done();}
        )
      }));
})
</code></pre>

<p>Again, Jasmine tells me that the <code>spec has no expectations</code></p>
",https://stackoverflow.com/questions/54919897/spec-has-no-expectations-angular-7,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",14554,True,5,1
How to set up a onClick test for the following:,"<p>I am new to unit testing and would like to know how could I set up a test for the following onClick</p>

<p>I have done some onClicks before but how could I call the following event and get it passing on my test:</p>

<p>file.js</p>

<pre><code>return (
 &lt;DropdownItem key={action.RouteId} 
 id={action.RouteName}
 onClick={() =&gt; {
   if(this.props.action &amp;&amp; (this.props.action.routeId !== action.RouteId)){
       this.props.setTarget(null);
       this.props.setAction(action);
    }
   }}&gt;
</code></pre>

<p>Usually, this is how I set up my onClick tests: How could I get the test above to work based on this:</p>

<p>test.file.js</p>

<pre class=""lang-js prettyprint-override""><code>beforeEach(() =&gt; {
  wrapper = mount(
    &lt;BrowserRouter&gt;
      &lt;Component {...baseProps} /&gt;
    &lt;/BrowserRouter&gt;
  );
});

it(' should call button click event', () =&gt; {
  baseProps.onClick.mockClear();
  wrapper.setProps({});
  wrapper.find('COMPONENT').setState({});
  wrapper.update();
  wrapper.find('#id').simulate('click');
  expect(toJson(wrapper)).toMatchSnapshot();
});
</code></pre>
",https://stackoverflow.com/questions/55006440/how-to-set-up-a-onclick-test-for-the-following,"['javascript', 'reactjs', 'jestjs', 'enzyme']",57,False,1,0
How to do unit test for Bitmap in android,"<p>I want to write unit test for my DiskLruCache class which actually check the bitmap is writing properly in cache and we can verify that by getting the bitmap. I am using below code for bitmap creation in test class but its showing error.</p>

<pre><code>var bitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888)
</code></pre>

<p>Its showing <code>IllegalStateException bitmap can not be null</code></p>

<p>Then change the code to:</p>

<pre><code>var bitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888).copy(Bitmap.Config.ARGB_8888, true)
</code></pre>

<p>And it's showing <code>NullPointerException</code></p>

<p>Any idea how to create bitmap in test class for unit testing?</p>
",https://stackoverflow.com/questions/58853136/how-to-do-unit-test-for-bitmap-in-android,"['android', 'unit-testing', 'bitmap']",2440,True,1,1
Unable to run mocha test locally with firebase,"<p>I am working on a react based frontend app that I am unit testing using mocha / enzyme.</p>

<p>The stack includes webpack, react, mocha + enzyme for testing, and firebase for auth / db / etc.</p>

<p>When I try and run <code>npm test</code> I get the following error due to firebase: </p>

<pre><code>WEBPACK  Compiled successfully in 3412ms

 MOCHA  Testing...

 RUNTIME EXCEPTION  Exception occurred while loading your tests

TypeError: Cannot read property 'stringify' of undefined
    at Module.eval (webpack:///./node_modules/@firebase/webchannel-wrapper/dist/index.esm.js?:31:308)
    at eval (webpack:///./node_modules/@firebase/webchannel-wrapper/dist/index.esm.js?:136:30)
    ...

npm ERR! Test failed.  See above for more details.
</code></pre>

<p>What could be causing this error? This didn't happen before I imported firebase. Is there a webpack config I should tweak?</p>
",https://stackoverflow.com/questions/54449308/unable-to-run-mocha-test-locally-with-firebase,"['reactjs', 'firebase', 'webpack', 'mocha.js']",462,True,1,1
"Mocking constructor of a class with jasmine, jest or ts-mockito","<p>I have a group of classes that receive some dependencies outside angular in this way. </p>

<pre><code>import {TypeATest} from '...../TypeA.model'
import { TypeBTest } from '..../TypeB.model'
import { SomeDependency } from './services/SomeDependency'
import { SomeAnother } from './services/SomeAnother'
  // ....

@Injectable({
  providedIn: 'root'
})
export class TestingService {
  this.activeTest: AnyTestType;

  constructor(private readonly injectorService: InjectorService) {}

  loadTest(TypeOfTest) {
    const someDependency = this.injectorService.get(SomeDependency)
    const someAnother = this.injectorService.get(SomeAnother)
      switch(TypeOfTest) {
        case TypeA:
            injector
            this.activeTest = new TypeATest(someDependency, someAnother);
            break;
        case TypeB:
            this.activeTest = new TypeBTest(someAnother);
            break;
      }
  }

  startTest(){
    this.activeTest.start()
  }

// .. more this.activeTest uses...
}
</code></pre>

<p>I am unit testing the service that loads that external classes but I do not want to create <code>TypeATest</code>, <code>TypeBTest</code> or similar but just mock the result (they all have the same API) but I am not able to find how to mock them. Is there a way to do this?</p>
",https://stackoverflow.com/questions/55403112/mocking-constructor-of-a-class-with-jasmine-jest-or-ts-mockito,"['angular', 'jestjs']",1997,True,1,1
OSError [WinError6] raised when running unittestts with sqlite,"<p>I have been tasked with creating a GUI for our unit testing. To achieve this, I've created an <code>sqlite</code> database. Here's a snippet of the SQL manager I'm using</p>

<p><strong>manager.py</strong></p>

<pre><code>    def write_results_true(self):
        connection = sqlite3.connect('../data.db')
        cursor = connection.cursor()
        cursor.execute('''UPDATE Tests 
                          SET Passed = 'True'
                          WHERE Script = ''' + self.test + '''''')
        connection.close()
</code></pre>

<p>And an example test:</p>

<p><strong>test.py</strong></p>

<pre><code>manager = manager.Manager(""'test_login_superuser'"")

class TestTest(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.get(""https://example.com"")

    def first_test(self):
         current_url = self.driver.current_url

        if current_url == 'https://example.com':
            manager.write_results_true()
            self.assertEqual(current_url, assertion_url)
</code></pre>

<p>I believe the issue I am having is being caused by <code>sqlite3</code>. The tests still complete and the terminal reflects this. It also outputs an ignored exception, but nothing is written into the database.</p>

<pre><code>D:\_jb_unittest_runner.py"" --path D:/test.py
Launching unittests with arguments python -m unittest D:/test.py in D:\

Ran 1 test in 6.167s

OK
 Exception ignored in: &lt;function Popen.__del__ at 0x02F91738&gt;
 Traceback (most recent call last):
      File ""C:\Users\[user]\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py"", line 854, in __del__
self._internal_poll(_deadstate=_maxsize)

    File ""C:\Users\[user]\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py"", line 1210, in _internal_poll
    if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
OSError: [WinError 6] The handle is invalid

Process finished with exit code 0
</code></pre>
",https://stackoverflow.com/questions/54596423/oserror-winerror6-raised-when-running-unittestts-with-sqlite,"['python-3.x', 'sqlite', 'unit-testing']",241,True,1,1
Unable to access external library classes in android test,"<p>I am writing a library module (lets call Lib A) which in turn depends on the another library (Lib B) which I am adding as an external library.
While writing the test cases for Library A, I am not able to access the classes of Library B in unit testing.</p>

<p>I have tried following:
testImplementation project(':B') but didn't helped</p>

<p>implementation project (':B')
testImplementation project(':B')</p>
",https://stackoverflow.com/questions/57790749/unable-to-access-external-library-classes-in-android-test,"['android', 'unit-testing', 'android-library']",84,False,1,0
Codeception/Symfony4 Environment variable not found: &quot;DATABASE_URL&quot;,"<p>I have a project in Symfony4 with doctrine DB, everything flies.</p>
<p>I would like to add some functional and unit testing with Codeception. I followed the docs and added this to my <strong>functional.suite.yml</strong>:</p>
<pre><code>actor: FunctionalTester
modules:
    enabled:
        - Symfony:
            app_path: 'src'
            environment: 'test'
        - Doctrine2:
            depends: Symfony
#            cleanup: true
        - \Helper\Functional
#       - Db
    step_decorators: ~        
</code></pre>
<p>However, when running <strong>vendor/bin/codecept</strong> run I get an ugly:</p>
<blockquote>
<p>In EnvVarProcessor.php line 131:</p>
<p>Environment variable not found: &quot;DATABASE_URL&quot;.</p>
</blockquote>
<p>I can't see anything else related in the docs, so not sure what I'm missing.</p>
",https://stackoverflow.com/questions/57712792/codeception-symfony4-environment-variable-not-found-database-url,"['symfony', 'doctrine-orm', 'doctrine', 'symfony4', 'codeception']",3170,True,4,2
How to test Parent passing `this` to Children using enzyme,"<p>I have below code where <code>Parent</code> Component is passing it's <code>this</code> to <code>Child</code> Component. <code>Child</code> Component will do some work and then do <code>setState</code> in <code>Parent</code> Component.</p>

<p>How Should i go about testing only Child Component. Means how can i create dummy <code>Parent</code> and later on check value in it's state using <code>enzyme</code> &amp; <code>jest</code>.</p>

<pre><code>class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            status: '',
        }
    }
    render(){
        return (
            &lt;div&gt;
                &lt;Child 
                    parentThis={this}
                /&gt;
            &lt;/div&gt;
        );
    }
}

class Child extends React.Component {

    doSomeWork = () =&gt; {
        const {parentThis} = this.props;
        parentThis.setState({
            'status': '1'
        })
    }

    render() {
        this.doSomeWork()
        return (&lt;div&gt;&lt;/div&gt;);
    }
}
</code></pre>

<p>I want to do Unit testing of <code>Child</code> Component. I want to make sure that <code>Child</code> is correctly updating <code>state</code> of <code>Parent</code> Component.</p>
",https://stackoverflow.com/questions/56900000/how-to-test-parent-passing-this-to-children-using-enzyme,"['reactjs', 'jestjs', 'enzyme']",36,True,1,1
Lighthouse auto model detection doesn&#39;t work with unit tests,"<p>I seem to be facing the general problem that directive driven mutations won't properly work when unit testing them. Using GraphQL Playground everything works as expected and the User model is auto detected. But if unit testing the same functionality it fails.</p>

<p>All config values are properly set (as I can see from regular requests not failing):</p>

<pre><code>'providers' =&gt; [
        'users' =&gt; [
            'driver' =&gt; 'eloquent',
            'model' =&gt; ClientName\PackageName\Models\User::class,
        ],
   ...
]
</code></pre>

<p>And lighthouse config values also set to the namespace above!</p>

<p>So for example this mutation would trigger the <code>UserPolicy</code> class and after that automatically call the create method of the <code>User</code> class:</p>

<pre><code>type Mutation @protect(guards: [""api""]) {
  ""Create user""
  createUser(data: NewUserInput! @spread): User
  @can(ability: ""create"")
  @create 
}
</code></pre>

<p>But calling the same request via phpunit would result in errors:
for <code>@can</code> it returns a <em>not authorized</em> error and if I remove <code>@can</code> it only updates the email field of the user model as if mass assignment is not properly set.</p>

<p>When I now change the above schema definition to:</p>

<pre><code>type Mutation @protect(guards: [""api""]) {
  ""Create user""
  createUser(data: NewUserInput! @spread): User
  @can(ability: ""create"" model: ""ClientName\\PackageName\\Models\\User"")
  @create(model: ""ClientName\\PackageName\\Models\\User"") 
}
</code></pre>

<p>And it works as expected within phpunit tests!</p>

<p>Now I suspect that within tests there is not User model found or not the appropriate but I cannot understand why this is.</p>

<p>Does anyone have any idea?</p>
",https://stackoverflow.com/questions/58014797/lighthouse-auto-model-detection-doesnt-work-with-unit-tests,"['phpunit', 'graphql', 'laravel-lighthouse']",110,False,2,0
Mocking a method that uses an asynchronous callback with moq,"<p>I'm unit testing some asynchronous code. I have tried to abstract it to make the issue more clear. My issue is that I want to set up the mocked <code>Bar</code> to execute <code>Foo</code>'s private callback method after <code>BeginWork</code> returns. The callback is supposed to call <code>Set()</code> on the <code>ManualResetEvent</code> allowing the calling thread to continue to run. When I run the test my thread blocks indefinitely at the call to <code>WaitOne()</code>.</p>

<p>Code under test:</p>

<pre><code>using System.Threading;
using NUnit.Framework;
using Moq;
using System.Reflection;

public interface IBar
{
    int BeginWork(AsyncCallback callback);
}

public class Bar : IBar
{
    public int BeginWork(AsyncCallback callback)
    {
        // do stuff
    }   // execute callback
}

public class Foo
{
    public static ManualResetEvent workDone = new ManualResetEvent(false);
    private IBar bar;

    public Foo(IBar bar)
    {
        this.bar = bar;
    }

    public bool DoWork()
    {
        bar.BeginWork(new AsyncCallback(DoWorkCallback));
        workDone.WaitOne(); // thread blocks here
        return true;
    }

    private void DoWorkCallback(int valueFromBeginWork)
    {
        workDone.Set();
    }
}
</code></pre>

<p>Test Code:</p>

<pre><code>[Test]
public void Test()
{
    Mock&lt;IBar&gt; mockBar = new Mock&lt;IBar&gt;(MockBehavior.Strict);

    // get private callback
    MethodInfo callback = typeof(Foo).GetMethod(""DoWorkCallback"", 
                  BindingFlags.Instance | BindingFlags.NonPublic);

    mockBar.Setup(() =&gt; BeginWork(It.IsAny&lt;AsyncCallback&gt;())) 
                        .Returns(0).Callback(() =&gt; callback.Invoke(0));

    Foo = new Foo(mockBar.Object);
    Assert.That(Foo.DoWork());
}
</code></pre>
",https://stackoverflow.com/questions/56809159/mocking-a-method-that-uses-an-asynchronous-callback-with-moq,"['c#', 'unit-testing', 'nunit', 'moq', 'iasyncresult']",1993,True,4,1
Build local unit tests (No instrumentation registered! Must run under a registering instrumentation),"<p>Take a look at the official <a href=""https://developer.android.com/training/testing/unit-testing/local-unit-tests#include-framework-dependencies"" rel=""noreferrer"">documentation</a>. The section <strong><em>Include framework dependencies</em></strong> gives an example of how to set up a local unit testing to work with the environment android sdk. But if you do everything as in the example, the test does not start. I get an error instead </p>

<blockquote>
  <p>java.lang.IllegalStateException: No instrumentation registered! Must
  run under a registering instrumentation.</p>
</blockquote>

<p>All attempts were made on a new project. Android Studio 3.3, gradle-4.10.1, build:gradle:3.3.0, Kotlin, and include Androidx artifacts.</p>

<p>Then added the following lines to the project with the specified configuration:</p>

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

<pre><code>android {
    // ...
    testOptions {
        unitTests.includeAndroidResources = true
    }
}

dependencies {
    // ...
    // Already exist
    testImplementation 'junit:junit:4.12'
    // Added this line
    testImplementation 'androidx.test:core:1.0.0'
}
</code></pre>

<p><strong>And the test body itself:</strong></p>

<pre><code>package com.example.myapplication

import android.content.Context
import androidx.test.core.app.ApplicationProvider
import org.junit.Test

class ExampleUnitTest {

    val context = ApplicationProvider.getApplicationContext&lt;Context&gt;()

    @Test
    fun readStringFromContext_LocalizedString() {
        System.out.println(context.applicationInfo.packageName)
    }
}
</code></pre>

<p>What am I doing wrong?</p>

<hr>

<pre><code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId ""com.example.myapplication""
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName ""1.0""
        testInstrumentationRunner ""androidx.test.runner.AndroidJUnitRunner""
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    testOptions {
        unitTests.includeAndroidResources = true
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation ""org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version""
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.core:core-ktx:1.1.0-alpha03'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
    testImplementation 'junit:junit:4.12'
    testImplementation 'androidx.test:core:1.0.0'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}
</code></pre>
",https://stackoverflow.com/questions/54222533/build-local-unit-tests-no-instrumentation-registered-must-run-under-a-register,"['android', 'unit-testing', 'documentation', 'robolectric']",17616,True,24,1
"Unit test doesn&#39;t complete, the method being tested just throws an exception. What am I missing?","<p>I'm currently in the process of working through a Unit Testing in C# course - specifically for NUnit (I'm using NUnit 3.8.1 with NUnit3TestAdapter 3.1.13).</p>

<p>My issue in question, is that when I'm testing for an exception to be thrown, my debugger stops &amp; throws an exception on the method that I'm testing. I'm not sure if I'm mistaken with the behaviour, but I can't see what I've done wrong.</p>

<p>Firstly - I've read up on the <a href=""https://github.com/nunit/docs/wiki/Assert.Throws"" rel=""nofollow noreferrer"">documentation</a> &amp; can't see a problem.</p>

<p>I've also looked through various other posts on stack overflow that just don't seem to quite point at the answer, as none of these solutions have worked for me.</p>

<p><a href=""https://stackoverflow.com/questions/44316606/is-there-some-assert-method-which-can-be-used-for-unit-test-on-whether-a-method"">Is there some Assert method which can be used for unit test on whether a method throws an exception?</a></p>

<p><a href=""https://stackoverflow.com/questions/56958118/c-sharp-unit-testing-test-method-throwing-nullreferenceexception"">C# Unit Testing - Test method throwing NullReferenceException</a></p>

<p><a href=""https://stackoverflow.com/questions/22384572/why-when-i-am-testing-that-a-method-throws-an-exception-and-the-method-throw-an"">Why, when I am testing that a method throws an exception and the method throw an exception, does the test stop?</a></p>

<p>The class I'm testing is as follows (and was provided from the instructor on the course - they have demonstrated that this works).</p>

<pre class=""lang-cs prettyprint-override""><code>
using System;

namespace TestNinja.Fundamentals
{
    public class ErrorLogger
    {
        public string LastError { get; set; }

        public event EventHandler&lt;Guid&gt; ErrorLogged; 

        public void Log(string error)
        {
            if (String.IsNullOrWhiteSpace(error))
                throw new ArgumentNullException();

            LastError = error; 

            // Write the log to a storage
            // ...

            ErrorLogged?.Invoke(this, Guid.NewGuid());
        }
    }
}
</code></pre>

<p>And finally, my test methods -</p>

<pre><code>using NUnit.Framework;
using TestNinja.Fundamentals;

namespace TestNinja.UnitTests
{
    [TestFixture]
    public class ErrorLoggerTests
    {
        //private ErrorLogger _errorLogger;

        [SetUp]
        public void SetUp()
        {
            //_errorLogger = new ErrorLogger();
        }

        [Test]
        public void Log_WhenCalled_SetTheLastErrorProperty()
        {
            var logger = new ErrorLogger();

            logger.Log(""a"");

            Assert.That(logger.LastError, Is.EqualTo(""a""));
        }

        [Test]
        [TestCase(null)]
        [TestCase("""")]
        [TestCase("" "")]
        public void Log_InvalidError_ThrowArgumentNullException(string error)
        {
            var logger = new ErrorLogger();
            Assert.That(() =&gt; logger.Log(error), Throws.ArgumentNullException);
        }
    }
}

</code></pre>

<p>The test I'm talking about is <code>Log_InvalidError_ThrowArgumentNullException</code>. On each test case the code breaks on the line <code>throw new ArgumentNullException();</code> in <code>ErrorLogger</code>. I have to close the box &amp; continue running the code.</p>

<p>When I run this test individually, the test runs to completion, however when I run all, that's where the exception is thrown &amp; my testing is stopped.</p>

<p>Originally, my unit testing had the <code>SetUp</code> method uncommented &amp; I was using that private field, however I swapped over to a fresh instance to make sure there weren't any issues with lingering objects.</p>
",https://stackoverflow.com/questions/57101827/unit-test-doesnt-complete-the-method-being-tested-just-throws-an-exception-wh,"['c#', 'nunit']",115,False,0,0
How to write unit testing for guzzle request in laravel?,"<p>I have a login function which makes a curl call via Guzzle Http request.The api is working fine and now i need to write unit test for the same api for all cases. Please help me how to write unit testing for the below function.</p>

<pre><code>public function login(Request $request)
    {
        $input = $request-&gt;all();

        /*
        *  check whether all the required parameters are received
        */

        $validator = Validator::make($input,[
            'username' =&gt; 'required',
            'password' =&gt; 'required'
        ]);

        if($validator-&gt;fails())
        {
            // if the validation fails send error response

            return $this-&gt;sendError('Validation Error',$validator-&gt;errors(),400);

            //EOF
        }

        /*
        *   get the username and password from Request and url value from .env file 
        *   and make a curl to  server to check the user authentication
        */

        $client = new \GuzzleHttp\Client(['http_errors' =&gt; false]);

        $response = $client-&gt;request('POST', config('link'), [
                'form_params' =&gt; [
                    'action' =&gt; 'login',
                    'username' =&gt; $input['username'],
                    'pwd' =&gt; $input['password']
                ]
            ]);

        $response_body = json_decode($response-&gt;getBody(),true);

        if(array_key_exists('success',$response_body))
        {
            if($response_body['success'] == 'yes')
            {
                $userId = $response_body['data']['profileData']['id'];
                // check if user is already registered or not

                $userObj = new User;
                $isUserExists = $userObj-&gt;checkUserExists($userId);

                // EOF

                if($isUserExists &lt; 1)
                {
                    $createUser['id'] = $userId;
                    $createUser['name'] = $response_body['data']['profileData']['first_name']."" "".$response_body['data']['profileData']['last_name'];
                    $createUser['email'] = $response_body['data']['profileData']['email'];
                    $createUser['password'] = bcrypt($input['password']);
                    $createUser['company_id'] = $response_body['data']['profileData']['company_id'];

                    $user = User::create($createUser);
                }
                else
                {
                    $user = User::find($userId);
                }

                // check if company already exists or not else register new company

                $companyObj = new Company;

                $companyId = $response_body['data']['profileData']['company_id'];
                $isCompanyExists = $companyObj-&gt;checkCompanyExists($companyId);

                if($isCompanyExists &lt; 1)
                {
                    $createCompany['id'] = $companyId;
                    $createCompany['name'] = $response_body['data']['profileData']['comp_name'];

                    $company = Company::create($createCompany);
                }

                // EOF

                // send the response back to the appliaction

                $success['user_id'] = $userId;
                $success['company_id'] = $response_body['data']['profileData']['company_id'];
                $success['token'] =  $user-&gt;createToken('silva-reborn')-&gt; accessToken;


                return $this-&gt;sendResponse($success,'Login successful');

                // EOF
            }
            else
            {
                // Invalid login

                return $this-&gt;sendError($response_body['msg'], array() ,401);

                // EOF
            }
        }
        else
        {
            return $this-&gt;sendError(""Invalid url"", '' ,404);
        }
    }
</code></pre>

<p>This api is working perfectly now i need to write the unit test case for this api .How to do it  ?</p>
",https://stackoverflow.com/questions/55255110/how-to-write-unit-testing-for-guzzle-request-in-laravel,"['laravel', 'guzzle']",1160,False,0,1
Unit test result in null object while testing a web api 2,"<p>I am new to MS Unit Testing and Moq objects. I am trying to test my Web API 2 controller. I have given below my unit test and controller code. While stepping through the code, it doesn't even go to the GetDeliveryCodeStrategy method.</p>

<pre><code>[TestMethod]
public void  CreateDelivery_ShouldReturnDeliveryCode()
{
    Mock&lt;IDeliveryStrategy&gt; deliveryStrategy = new Mock&lt;IDeliveryStrategy&gt; 
 ();
    Mock&lt;IDeliveryCode&gt; deliveryCode = new Mock&lt;IDeliveryCode&gt;();
    var controller = new DeliveryCodeController(deliveryStrategy.Object, 
    deliveryCode.Object);
    var controllerContext = new HttpControllerContext();
    var request = new HttpRequestMessage();
    request.Headers.Add(""appToken"", ""a57ffa87-950e-40f4-b965-17788becac7d"");

    controllerContext.Request = request;
    controller.ControllerContext = controllerContext;

    var result = controller.CreateDelivery(50) as 
    CreatedNegotiatedContentResult&lt;IDeliveryCode&gt;;
    Assert.IsNotNull(result);

}

public class DeliveryCodeController : ApiController
{
    IDeliveryStrategy _deliveryBatch;
    IDeliveryCode _deliveryCode;

    //Constructor dependency injection through Autofac
   public DeliveryCodeController(IDeliveryStrategy DeliveryBatch, 
   IDeliveryCode deliveryCode)
   {
        _deliveryBatch = DeliveryBatch;
        _deliveryCode = deliveryCode;
   }

   [HttpPost]
   [Route(""api/DeliveryCode/{percentage}"")]
   public IHttpActionResult CreateDelivery(int percentage)
   {
      String appToken = String.Empty;

    if (Request.Headers.TryGetValues(""appToken"", out IEnumerable&lt;String&gt; 
    headerValues))
    {
    appToken = headerValues.FirstOrDefault();
    }
    if (!String.IsNullOrEmpty(appToken)))
    {   
    IDeliveryContext deliveryContext = 
       _deliveryBatch.GetDeliveryCodeStrategy(percentage);  
    _deliveryCode.Code = deliveryContext.Create();
    return Created(Request.RequestUri.ToString(), _deliveryCode);    
    }
    else
    {
    return Content(HttpStatusCode.Forbidden, new Error { message = ""The App 
    Token is not valid."" });
    }
  }
</code></pre>

<p>}</p>

<p>When I do the ""Debug Test"" and step through the code, the deliveryContext 
  object comes as null in the code  IDeliveryContext deliveryContext = 
  _deliveryBatch.GetDeliveryCodeStrategy(percentage);</p>
",https://stackoverflow.com/questions/54221985/unit-test-result-in-null-object-while-testing-a-web-api-2,"['c#', 'unit-testing', 'asp.net-web-api2']",442,True,0,2
Testing a Redux login Action with fetch api,"<p>On my React-Native project, i tried to start unit testing, how to test on Redux action that involves a login fetch api call.I've looked at some examples of testing an async Action, but I haven't wrapped my head around how to test the code below.</p>

<p>I've looked at using redux-mock-store, but I have no idea where to start with the test.</p>

<pre class=""lang-js prettyprint-override""><code>import {
  API_URL_AUTH,
  API_URL,
  CLIENT_ID,
  CLIENT_SECRET,
} from ""../config/consts"";

import { FETCHING, FETCHED } from ""../actions/ActionTypes"";

const { dispatch } = this.props;
const { email, password } = this.state;

const authenticationData = {
  client_id: CLIENT_ID,
  client_secret: CLIENT_SECRET,
  grant_type: ""password"",
  username: email,
  password: password,
};

dispatch({ type: FETCHING });

let response = await (await fetch(API_URL_AUTH + ""oauth/token"", {
  headers: {
    Accept: ""application/json"",
    ""Content-Type"": ""application/json"",
  },
  method: ""POST"",
  body: JSON.stringify(authenticationData),
})).json();

if (!response.error) {
  await AsyncStorage.setItem(""accessToken"", ""Bearer "" + response.access_token);
  let user = await (await fetch(API_URL + ""user"", {
    headers: {
      Accept: ""application/json"",
      ""Content-Type"": ""application/json"",
      Authorization: ""Bearer "" + response.access_token,
    },
    method: ""GET"",
  })).json();
} else {
  showMessage({
    message: response.message,
    type: ""danger"",
  });
}

dispatch({ type: FETCHED });
</code></pre>
",https://stackoverflow.com/questions/56628866/testing-a-redux-login-action-with-fetch-api,"['javascript', 'unit-testing', 'react-native', 'testing', 'redux']",593,True,0,1
How to check the api response body using Mockito on android?,"<p>I am new to unit testing. My requirement is to check the response is in correct format or not. I am posting the code that I have done. Is this correct way to implement the Mockito. While compiling the code it throws me the error, saying Actually, there were zero interactions with this mock. Can you give some idea how to mock test for response format?</p>

<pre><code>public class SignUpTest {
    MockWebServer mockWebServer;

    @Mock
    ApiInterface apiInterface;

    @Mock
    Call&lt;ResponseBody&gt; responseBodyCall;


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

    }

    @Test
    public void testWithCorrect() throws Exception {
        String format = ""{"" +
                ""\""Status\"":null,"" +
                ""\""Message\"":null,"" +
                ""\""IssueId\"":null,"" +
                ""\""TransId\"":null,"" +
                ""\""ResponseCode\"":101,"" +
                ""\""ResponseDescription\"":\""APP requires your phone id while registering app."" +
                "" Please provide necessary permission to the app before proceeding.\"""" +
                ""}"";
        JsonObject jsonParam = new JsonObject();
        jsonParam.addProperty(""msisdn"", ""9812345678"");
        when(apiInterface.appLogin(jsonParam)).thenReturn(responseBodyCall);
        verify(responseBodyCall).enqueue(new Callback&lt;ResponseBody&gt;() {
            @Override
            public void onResponse(@NonNull Call&lt;ResponseBody&gt; call, @NonNull Response&lt;ResponseBody&gt; response) {
                assert response.body() != null;
                assertEquals(format, response.body().toString());
            }

            @Override
            public void onFailure(@NonNull Call&lt;ResponseBody&gt; call, @NonNull Throwable t) {

            }
        });

    }
</code></pre>
",https://stackoverflow.com/questions/54320378/how-to-check-the-api-response-body-using-mockito-on-android,"['android', 'mockito']",495,False,0,0
http typed client in net core unit testing,"<p>How would i go about to unit test a service that makes calls to a http typed client?
the examples given at <a href=""https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2#typed-clients"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2#typed-clients</a> do not use interface.</p>

<pre><code>public GitHubService(HttpClient client)
</code></pre>

<p>Would creating interface for the typed client be needed for unit testing using xunit/moq? or wouldn't i need to unit test this service.</p>
",https://stackoverflow.com/questions/56527226/http-typed-client-in-net-core-unit-testing,['asp.net-core'],704,True,0,2
Running test with Spring Boot Test,"<p>Hello I am doing some unit testing with spring boot and Junit and I turn into this error:</p>

<pre><code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ch.hcuge.dpi.dpidata.exporter.clinerion.ExtractDataFromPushTest': Unsatisfied dependency expressed through field 'extractDataFromPush'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ch.hcuge.dpi.dpidata.exporter.clinerion.ExtractDataFromPush' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code></pre>

<p>My Java test class:</p>

<pre><code>package ch.hcuge.dpi.dpidata.exporter.clinerion;

import ch.hcuge.dpi.dpidata.common.util.DateUtil;

import java.util.Date;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(""classpath*:testApplicationContextClinerion.xml"")
public class ExtractDataFromPushTest {

@Autowired
private ExtractDataFromPush extractDataFromPush;

@Test
public void getCaseIdsForDatesTest() {
    Date from = DateUtil.of(2019, 1, 1);
    Date to = DateUtil.of(2019, 1,10);
    List&lt;String&gt; caseIds = extractDataFromPush.getCaseIdsForDates(from, to);
    Assert.assertEquals(74, caseIds.size());
    Assert.assertTrue( caseIds.contains(""45698""));
    }

}
</code></pre>

<p>What's wrong with my code?</p>

<p>This is my application xml context:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;beans xmlns=""http://www.springframework.org/schema/beans""
   xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
   xmlns:context=""http://www.springframework.org/schema/context""
   xmlns:task=""http://www.springframework.org/schema/task""
   xsi:schemaLocation=""http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd


    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task.xsd""&gt;

&lt;bean id=""DejaProperties""
      class=""org.springframework.beans.factory.config.PropertiesFactoryBean""&gt;
    &lt;property name=""locations""&gt;
        &lt;list&gt;
            &lt;value&gt;classpath*:ch/hcuge/deja/ConfigTests.properties&lt;/value&gt;
            &lt;value&gt;classpath*:application.properties&lt;/value&gt;
        &lt;/list&gt;
    &lt;/property&gt;
&lt;/bean&gt;

&lt;!-- Expose the properties so other parts of the spring config can use them --&gt;
&lt;bean id=""propertyConfigurer""
      class=""org.springframework.beans.factory.config.PropertyPlaceholderConfigurer""&gt;
    &lt;property name=""ignoreResourceNotFound"" value=""true""/&gt;
    &lt;property name=""ignoreUnresolvablePlaceholders"" value=""false""/&gt;
    &lt;property name=""properties"" ref=""DejaProperties""/&gt;
&lt;/bean&gt;

&lt;import resource=""classpath*:/META-INF/deja-test-L2-services-application-context.xml""/&gt;

&lt;context:component-scan base-package=""ch.hcuge.dpi""&gt;
    &lt;!--&lt;context:exclude-filter type=""regex""--&gt;
                            &lt;!--expression=""ch.hcuge.dpi.dpidata.exporter.config.ExporterWebConfig""&gt;&lt;/context:exclude-filter&gt;--&gt;
    &lt;!--&lt;context:exclude-filter type=""regex""--&gt;
                            &lt;!--expression=""ch.hcuge.dpi.dpidata.exporter.test.config.TestConfig""&gt;&lt;/context:exclude-filter&gt;--&gt;
    &lt;!--&lt;context:exclude-filter type=""regex""--&gt;
                            &lt;!--expression=""ch.hcuge.dpi.dpidata.exporter.swisssos.core.AneuxPatientStudyService""&gt;&lt;/context:exclude-filter&gt;--&gt;
    &lt;!--&lt;context:exclude-filter type=""regex""--&gt;
                            &lt;!--expression=""ch.hcuge.dpi.dpidata.exporter.swisssos.core.AneuxGeneralConsentService""&gt;&lt;/context:exclude-filter&gt;--&gt;
&lt;/context:component-scan&gt;

&lt;context:annotation-config/&gt;

&lt;task:annotation-driven executor=""taskExecutor"" scheduler=""taskScheduler""/&gt;
&lt;task:executor id=""taskExecutor"" pool-size=""5""/&gt;
&lt;task:scheduler id=""taskScheduler"" pool-size=""10""/&gt;
</code></pre>

<p></p>

<p>I am pretty new to testing especially with java and spring-boot;
Do I have to do some build to reinstall some packages or maybe I have to import some other spring packages?</p>
",https://stackoverflow.com/questions/54196987/running-test-with-spring-boot-test,"['java', 'unit-testing', 'spring-boot', 'junit']",296,False,0,2
Angular unit testing in routing and routerLink using Jasmine,"<p>I am new in Angular and unit testing. I create a new project for testing the routing in Angular.I follow the guide in <a href=""https://angular.io/guide/testing#components-with-routerlink"" rel=""nofollow noreferrer"">Angular official doc</a>.It does work in testing the routerLink.</p>

<p>but here is a problem. I forgot creating a route in the app.routing.module.ts, 
but the test still pass.</p>

<p>here is the code
in routing.module.ts</p>

<p><code>const routes: Routes = [];</code></p>

<p>and in html
<code>
&lt;a routerLink=""/order""&gt;Order&lt;/a&gt;&lt;br/&gt;
&lt;a routerLink=""/creditCard""&gt;Credit Card&lt;/a&gt;
</code></p>

<p>in spec.ts</p>

<pre><code>describe('AppComponent', () =&gt; {
  let fixture: ComponentFixture&lt;AppComponent&gt;;
  let app: any;
  let compiled: any;
  let linkDes:any;
  let routerLinks:any;
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent,
        RouterLinkDirectiveStub
      ]
    }).compileComponents().then(() =&gt; {
      fixture = TestBed.createComponent(AppComponent);
      app = fixture.debugElement.componentInstance;
      fixture.detectChanges();
      compiled = fixture.debugElement.nativeElement;

      // find DebugElements with an attached RouterLinkStubDirective
      linkDes = fixture.debugElement
        .queryAll(By.directive(RouterLinkDirectiveStub));

      // get attached link directive instances
      // using each DebugElement's injector
      routerLinks = linkDes.map(de =&gt; de.injector.get(RouterLinkDirectiveStub));
    })
  }));

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

  it(`should have as title 'unitTesting'`, () =&gt; {
    expect(app.title).toEqual('unitTesting');
  });

  it('should render title in a h1 tag', () =&gt; {
    expect(compiled.querySelector('h1').textContent).toContain('Welcome to unitTesting!');
  });

  it('can get RouterLinks from page', () =&gt; {
    expect(routerLinks.length).toBe(2, 'should have 2 routerLinks');
    expect(routerLinks[0].linkParams).toBe('/order');
    expect(routerLinks[1].linkParams).toBe('/creditCard');
  });

}); 
</code></pre>

<p>I understand the unit testing should be isolated.
but in some case, it should have connection in order to test.</p>

<p>I googled. but lot of answers just compare with static path.</p>

<p>and my question is, how to test in scenario like below:</p>

<ol>
<li><p>in routing.module.ts</p>

<p>const routes: Routes = [</p>

<p>{path:""order"",component:OrderComponent},
  {path:""creditCard"",component:CreditcardComponent}</p>

<p>];</p></li>
</ol>

<p>2.in two or more pages have same anchor tag 
<code>
&lt;a routerLink=""/order""&gt;Order&lt;/a&gt;&lt;br/&gt;
&lt;a routerLink=""/creditCard""&gt;Credit Card&lt;/a&gt;
</code></p>

<p>3.if someone change the path in routing.module.ts,like</p>

<p><code>{path:""orderDetail"",component:OrderComponent},</code></p>

<p>and forgot to change the path of routerLink in all or one of html file, test case will still pass for those component that forgot to change the path of routerLink.</p>

<p>Therefore, what to do to fix it to show failure in test case.</p>
",https://stackoverflow.com/questions/57422418/angular-unit-testing-in-routing-and-routerlink-using-jasmine,"['angular', 'unit-testing', 'routes', 'jasmine']",334,False,1,0
Steemit Jussi Docker Not working Properly,"<p>Jussi docker has 28 steps to build the docker.
I run the docker with steemit developer guide but it was not passed in unit test step 26.
<code>Step 26/28 : RUN pipenv run pytest</code></p>

<p>My environment is as followings
OS: Ubuntu 18.04
Python: 3.6.5
Docker: 18.09.1</p>

<p>Following Error happened.</p>

<pre><code> ---&gt; Running in 248a0ce440aa
============================= test session starts ==============================
platform linux -- Python 3.6.5, pytest-3.10.0, py-1.7.0, pluggy-0.8.1
rootdir: /app, inifile: pytest.ini
plugins: timeout-1.3.3, sanic-0.1.15, pylint-0.14.0, profiling-1.4.0, mock-1.10.0, docker-0.6.1, cov-2.6.0, console-scripts-0.1.7, asyncio-0.9.0
collected 3036 items

tests/test_account_transfer_route.py ......................              [  0%]
tests/test_appbase_compat_translation.py ............................... [  1%]
........................................................................ [  4%]
........................................................................ [  6%]
........................................................................ [  8%]
........................................................................ [ 11%]
........................................................................ [ 13%]
........................................................................ [ 15%]
.........................................                                [ 17%]
tests/test_cache_backends.py ..................                          [ 17%]
tests/test_cache_group.py .............................................. [ 19%]
........................................................................ [ 21%]
........................................................................ [ 24%]
........................................................................ [ 26%]
........................                                                 [ 27%]
tests/test_cache_key.py .........................................        [ 28%]
tests/test_cache_middleware.py sF                                        [ 28%]
tests/test_cache_utils.py .                                              [ 28%]
tests/test_empty.py .........                                            [ 29%]
tests/test_error_handling.py FFFFFFFF                                    [ 29%]
tests/test_healthcheck_routes.py sss                                     [ 29%]
tests/test_jsonrpc_request_and_responses.py FFFFFFFFFFFFFFFFFFFFFFFFFFFF [ 30%]
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF                 [ 32%]
tests/test_jussi_handlers.py FFFFFF                                      [ 32%]
tests/test_jussi_http_request.py ...........................             [ 33%]
tests/test_jussi_jsonrpc_request.py .................................... [ 34%]
........................................................................ [ 36%]
........................................................................ [ 39%]
........................................................................ [ 41%]
........................................................................ [ 43%]
........................................................................ [ 46%]
.........................................................                [ 48%]
tests/test_jussi_request_response_middleware.py FFFF....                 [ 48%]
tests/test_responses.py ssssssssssssssssssssssssssssssssssssssssssssssss [ 50%]
ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss [ 52%]
ssssssssssssssssssssssssssssssssssssssssss                               [ 53%]
tests/test_restricted_routes.py ssssssssssssssssssssssssssssssssssssssss [ 55%]
                                                                         [ 55%]
tests/test_ttls.py ......................                                [ 55%]
tests/test_upstream.py ................................................. [ 57%]
........................................................................ [ 59%]
..                                                                       [ 59%]
tests/test_upstreams.py .................                                [ 60%]
tests/test_urn.py ...................................................... [ 62%]
........................................................................ [ 64%]
........................................................................ [ 66%]
........................................................................ [ 69%]
........................................................................ [ 71%]
...........................                                              [ 72%]
tests/test_utils_namespaces.py ......................................... [ 73%]
.........................................................                [ 75%]
tests/test_validators.py ............................................... [ 77%]
........................................................................ [ 79%]
........................................................................ [ 82%]
........................................................................ [ 84%]
........................................................................ [ 86%]
........................................................................ [ 89%]
........................................................................ [ 91%]
........................................................................ [ 94%]
........................................................................ [ 96%]
........................................................................ [ 98%]
......................................                                   [100%]

=================================== FAILURES ===================================
____________________ test_mocked_cache_response_middleware _____________________

mocked_app_test_cli = (&lt;CoroutineMock name='_get_new_connection()' id='140155905724144'&gt;, &lt;pytest_sanic.utils.TestClient object at 0x7f789735c4e0&gt;)

    async def test_mocked_cache_response_middleware(mocked_app_test_cli):
        mocked_ws_conn, test_cli = mocked_app_test_cli
        mocked_ws_conn.recv.return_value = json.dumps(expected_response)
        response = await test_cli.post('/', json=req, headers={'x-jussi-request-id': '1'})
        assert 'x-jussi-cache-hit' not in response.headers
&gt;       assert await response.json() == expected_response
E       AssertionError: assert {'error': {'c...onrpc': '2.0'} == {'id': 1, 'jso...9615022, ...}}
E         Omitting 1 identical items, use -vv to show
E         Differing items:
E         {'id': None} != {'id': 1}
E         Left contains more items:
E         {'error': {'code': -32603,
E                    'data': {'error_id': '16a3d5dc-efd6-49e7-bd22-30f5223a555f',
E                             'jussi_request_id': '1'},...
E         
E         ...Full output truncated (33 lines hidden), use '-vv' to show

tests/test_cache_middleware.py:96: AssertionError
---------------------------- Captured stdout setup -----------------------------
[2019-01-29 12:17:00 +0000] [6] [INFO] Goin' Fast @ http://127.0.0.1:43365
------------------------------ Captured log setup ------------------------------
app.py                    1120 INFO     Goin' Fast @ http://127.0.0.1:43365
----------------------------- Captured stdout call -----------------------------
[2019-01-29 12:17:00 +0000] - (sanic.access)[INFO][127.0.0.1:50746]: POST http://127.0.0.1:43365/  200 160
------------------------------ Captured log call -------------------------------
errors.py                  217 ERROR    {""exception"":""InvalidUsage('Bad Request',)"",""message"":""Internal Error"",""error_id"":""16a3d5dc-efd6-49e7-bd22-30f5223a555f"",""jrpc_request_id"":null,""jussi_request_id"":""1"",""event"":""Internal Error"",""logger"":""jussi.errors"",""level"":""error""}
server.py                  362 INFO
___________ test_middleware_error_handler[rpc_req0-error0-expected0] ___________

rpc_req = {'id': 1, 'jsonrpc': '2.0', 'method': 'yo.test_method', 'params': [1, 2, 3]}
error = Exception()
expected = {'error': {'code': -32603, 'data': {'error_id': '123', 'jussi_request_id': '123'}, 'message': 'Internal Error'}, 'id': 1, 'jsonrpc': '2.0'}

    @pytest.mark.test_app
    @pytest.mark.parametrize(
        'rpc_req,error,expected',
        [(jrpc_req, Exception(),
          minimal_error0),
         ({'jsonrpc': '2.0', 'method': 'yo.test_method'},
          Exception(),
          minimal_error_with_no_jsonrpc_id),
         (jrpc_req,
          JsonRpcError(http_request=fake_http_request),
          minimal_error2),
         (jrpc_req,
          JsonRpcError(
              http_request=fake_http_request, data=test_data),
          jrpc_error_with_data),
         (jrpc_req,
          JsonRpcError(
              http_request=fake_http_request, data=test_data,
              exception=Exception('test'),
              error_id='123'),
          jrpc_error_with_data),
         (jrpc_req,
          ParseError(http_request=fake_http_request),
          parse_error),
         (jrpc_req,
          InvalidRequest(http_request=fake_http_request),
          invalid_request_error),
         (jrpc_req,
          ServerError(http_request=fake_http_request),
          server_error)])
    def test_middleware_error_handler(rpc_req, error, expected):
        app = sanic.Sanic('testApp', request_class=HTTPRequest)

        # pylint: disable=unused-argument,unused-variable

        @app.post('/')
        def handler(request):
            return sanic.response.text('Hello')

        @app.middleware('request')
        @handle_middleware_exceptions
        async def error_middleware(request):
            raise error

        req, response = app.test_client.post('/', json=rpc_req, headers={'x-jussi-request-id': '123'})
&gt;       assert response.headers['Content-Type'] == 'application/json'
E       AssertionError: assert 'text/plain; charset=utf-8' == 'application/json'
E         - text/plain; charset=utf-8
E         + application/json

tests/test_error_handling.py:179: AssertionError
----------------------------- Captured stdout call -----------------------------
[2019-01-29 12:17:00 +0000] [6] [INFO] Goin' Fast @ http://127.0.0.1:42101
[2019-01-29 12:17:00 +0000] [6] [INFO] http://127.0.0.1:42101/
[2019-01-29 12:17:00 +0000] [6] [ERROR] Exception occurred while handling uri: 'http://127.0.0.1:42101/'
Traceback (most recent call last):
  File ""httptools/parser/parser.pyx"", line 307, in httptools.parser.parser.cb_on_body
  File ""/app/.venv/lib/python3.6/site-packages/sanic/server.py"", line 310, in on_body
    self.request.body_push(body)
AttributeError: 'HTTPRequest' object has no attribute 'body_push'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File ""/app/.venv/lib/python3.6/site-packages/sanic/server.py"", line 251, in data_received
    self.parser.feed_data(data)
  File ""httptools/parser/parser.pyx"", line 193, in httptools.parser.parser.HttpParser.feed_data
httptools.parser.errors.HttpParserCallbackError: the on_body callback failed
[2019-01-29 12:17:00 +0000] - (sanic.access)[INFO][127.0.0.1:49448]: POST http://127.0.0.1:42101/  400 18
[2019-01-29 12:17:00 +0000] [6] [INFO] Starting worker [6]
[2019-01-29 12:17:00 +0000] [6] [INFO] Stopping worker [6]
[2019-01-29 12:17:00 +0000] [6] [INFO] Server Stopped
</code></pre>

<p>My DEV_config.json is as followings.</p>

<pre><code>{
  ""limits"": {
    ""blacklist_accounts"": [
      ""non-steemit""
    ]
  },
  ""upstreams"": [
    {
      ""name"": ""steemd"",
      ""translate_to_appbase"": true,
      ""urls"": [
        [
          ""steemd"",
         ""https://api.steemit.com""
        ]
      ],
      ""ttls"": [
        [
          ""steemd"",
          3
        ],
        [
          ""steemd.login_api"",
          -1
        ],
        [
          ""steemd.network_broadcast_api"",
          -1
        ],
        [
          ""steemd.follow_api"",
          10
        ],
        [
          ""steemd.market_history_api"",
          1
        ],
        [
          ""steemd.database_api"",
          3
        ],
        [
          ""steemd.database_api.get_block"",
          -2
        ],
        [
          ""steemd.database_api.get_block_header"",
          -2
        ],
        [
          ""steemd.database_api.get_content"",
          1
        ],
        [
          ""steemd.database_api.get_state"",
          1
        ],
        [
          ""steemd.database_api.get_state.params=['/trending']"",
          30
        ],
        [
          ""steemd.database_api.get_state.params=['trending']"",
          30
        ],
        [
          ""steemd.database_api.get_state.params=['/hot']"",
          30
        ],
        [
          ""steemd.database_api.get_state.params=['/welcome']"",
          30
        ],
        [
          ""steemd.database_api.get_state.params=['/promoted']"",
          30
        ],
        [
          ""steemd.database_api.get_state.params=['/created']"",
          10
        ],
        [
          ""steemd.database_api.get_dynamic_global_properties"",
          1
        ]
      ],
      ""timeouts"": [
        [
          ""steemd"",
          5
        ],
        [
          ""steemd.network_broadcast_api"",
          0
        ]
      ]
    },
    {
      ""name"": ""appbase"",
      ""urls"": [
        [
          ""appbase"",
          ""https://api.steemit.com""
        ]
      ],
      ""ttls"": [
        [
          ""appbase"",
          -2
        ],
        [
          ""appbase.block_api"",
          -2
        ],
        [
          ""appbase.database_api"",
          1
        ]
      ],
      ""timeouts"": [
        [
          ""appbase"",
          3
        ],
        [
          ""appbase.chain_api.push_block"",
          0
        ],
        [
          ""appbase.chain_api.push_transaction"",
          0
        ],
        [
          ""appbase.network_broadcast_api"",
          0
        ],
        [
          ""appbase.condenser_api.broadcast_block"",
          0
        ],
        [
          ""appbase.condenser_api.broadcast_transaction"",
          0
        ],
        [
          ""appbase.condenser_api.broadcast_transaction_synchronous"",
          0
        ],
        [
          ""appbase.condenser_api.get_ops_in_block.params=[2889020,false]"",
          20
        ]
      ]
    }
  ]
}

</code></pre>

<p>It should be passed 28 steps in docker building but was not success in 26 steps in unit testing</p>
",https://stackoverflow.com/questions/54421067/steemit-jussi-docker-not-working-properly,"['unit-testing', 'docker', 'blockchain', 'cryptocurrency', 'steemit']",83,False,0,0
How do I inject a BufferedReader with InputStreamReader as its parameter using Spring Boot?,"<p>My question is along the same lines as <a href=""https://stackoverflow.com/questions/42171280/how-do-i-inject-a-buffered-reader-into-a-class-with-a-file-reader-as-its-paramet"">this question</a>. However, my BufferedReader takes an InputStreamReader as parameter. My code looks like this:</p>

<pre><code>URL url = new URL(""http://localhost:8080/endpoint"");

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

//Line of importance:
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
</code></pre>

<p>How do I inject this, so that I can mock it for unit testing? Thanks in advance.</p>

<p>EDIT: Added test code (how I think it should work):</p>

<p>Adding a bean(?):</p>

<pre><code>@Bean
public BufferedReader bufferedReader() throws FileNotFoundException {
    return new BufferedReader(new InputStreamReader());
}
</code></pre>

<p>Mocking of all dependencies with mock instances:</p>

<pre><code>@Mock
private HttpURLConnection httpURLConnection;

@Mock
private BufferedReader bufferedReader;

@Mock
private InputStream inputStream;

    when(URLhandlerClass.getPath(any(String.class))).thenReturn(""http://localhost:8080/endpoint);
    when(bufferedReader.readLine()).thenReturn(""firstLine"", ""secondLine"", ""thirdLine"");
    when(httpURLConnection.getInputStream()).thenReturn(inputStream);
</code></pre>

<p>ERROR: FileNotFoundException and Connect: connection refused</p>
",https://stackoverflow.com/questions/57865707/how-do-i-inject-a-bufferedreader-with-inputstreamreader-as-its-parameter-using-s,"['java', 'spring-boot', 'unit-testing', 'dependency-injection', 'mockito']",405,True,0,1
NUnit Check if button was click,"<p>I am learning how to do unit testing. I tried to search for how to do testing for a button click event but couldn't find an answer that I could understand. 
How can I check if <code>TextBlock_MouseDown</code> event was raised and followed by reponse from <code>PostMethod</code>, which must not be <code>null</code>. My issue is, I can't find a way or don't know how to check <code>TextBlock_MouseDown</code> event using <code>NUnit</code>.</p>

<pre><code>public partial class MainWindow : Window
{
    public MainWindow(){
        InitializeComponent();
    }

    public void TextBlock_MouseDown(object sender, MouseButtonEventArgs e){
        //Check return value from PostMethod
        string reponse = PostMethod(""myurlhere"");
    }

    public static String PostMethod(String val){
        //Code
    }
}




[TestFixture]
public class TestClass
{
    [Test]
    public void PostMethod_IsAlive_returnHello()
    {
        //ARRANGE
        String url = ""myurlhere"";

        //ACT
        string response = MainWindow.PostMethod(url);

        //ASSERT
        Assert.AreEqual(""\""Hello\"""", response);

    }
}
</code></pre>
",https://stackoverflow.com/questions/58851763/nunit-check-if-button-was-click,"['c#', 'nunit']",481,False,0,1
Implicitly pass arguments,"<p>I'm working on a custom unit-testing framework that doesn't display the filename/line numbers of failed tests. I know I could require them as arguments for the <code>report_results</code> function but that seems like a lot of text. </p>

<p>Is there a way to make it so that <code>__FILE__</code> and <code>__LINE__</code> are always passed with the function, even if I don't pass them when I call it? </p>

<p>You can do something like this in C++:</p>

<pre><code>void func(char *file=__FILE__, int line=__LINE__)(int more_args) {}
</code></pre>
",https://stackoverflow.com/questions/56858585/implicitly-pass-arguments,['c'],74,True,3,1
How to fix &#39;$timeout is not a function&#39; error in Jasmine?,"<p>I get an TypeError: this.$timeout is not a function on unit testing with Jasmine for angular.js app. </p>

<p>I run a timeout service on my onInit, which gives the error.</p>

<p>Can't find a solution to fix this problem.</p>

<p>The onInit look like: </p>

<pre><code>constructor($document, $window, $element, $timeout) {
    this.$document = $document;
    this.$window = $window;
    this.$element = $element;
    this.$timeout = $timeout;
}

$onInit() {
    const elementsList = this.element.children;
    const currentPage = elementsList.findIndex(pageController.findElement) + 1;
    const totalPages = elementsList.length;

    if (totalPages &gt; 1) {
        this.elementsList = elementsList;
        this.currentPage = currentPage;
        this.totalPages = totalPages;
    }

    this.$timeout(() =&gt; {
        this.getCurrentPage().style.width = 'auto';
        this.currentStepWidth = this.getCurrentPage().clientWidth;
    });
}
</code></pre>

<p>and the spec file:</p>

<pre><code>describe('$onInit', () =&gt; {
    fit('should set currentPage and totalPages', () =&gt; {
        let pageCounter = new pageController();
        pageCounter.element = {
            children: [
                { styles: ['pageCurrent'] },
                { styles: ['pageVisited'] }
            ]
        };

        // When
        pageCounter.$onInit();

        // Then
        expect(pageCounter.currentPage).toEqual(1);
        expect(pageCounter.totalSteps).toEqual(2);
    });
});
</code></pre>

<p>When I run the test, I get the TypeError: this.$timeout is not a function</p>

<p>How can I fix this?</p>
",https://stackoverflow.com/questions/57660400/how-to-fix-timeout-is-not-a-function-error-in-jasmine,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",124,False,0,0
Chai Cannot read property &#39;should&#39; of null,"<p>I'm getting the following error when unit testing for a single item using <a href=""https://github.com/tgriesser/knex"" rel=""nofollow noreferrer"">knex</a>. I'm also referencing this <a href=""https://mherman.org/blog/test-driven-development-with-node/"" rel=""nofollow noreferrer"">https://mherman.org/blog/test-driven-development-with-node/</a></p>

<p>It renders api/users/1 successfully. So not sure why it says null. </p>

<blockquote>
  <p>GET /api/users/:id
         Should return a single show :
       Uncaught TypeError: Cannot read property 'should' of null
        at should (tests/users.spec.js:59:26)</p>
</blockquote>

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

<pre><code>import chai from 'chai';
import { expect } from 'chai';
import chaiHttp from 'chai-http';
import { assert } from 'assert'
import users from '../routes/users';
import request from 'supertest';


describe('GET /api/users/:id ', () =&gt;{
    it('Should return a single show ', (done)=&gt; {
       chai.request(users)
            .get('/users/1')
            .set('Accept', 'application/json')
            .end((response) =&gt; {
                // error begins here
                response.should.have.status(200);
                response.should.be.json; 
                response.body.should.be.a('object');
                response.body.should.have.property('id');
                response.body.name.should.equal(1);
                done()
            })          

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

<p><strong>routes/users.js</strong></p>

<pre><code>users.get('/users/:id', (req, res) =&gt; {
    return knex('users').where({id: req.params.id})
        .then( (user) =&gt; {
            res.json({
                user: user
            })
        });
})
</code></pre>
",https://stackoverflow.com/questions/55600750/chai-cannot-read-property-should-of-null,"['javascript', 'mocha.js', 'chai', 'knex.js']",1911,True,0,1
Updating state with timer does not return updated values,"<p>I'm new to unit testing with Jest. The project has a progress indicator component that uses setInterval as a timer. I need to unit test that the ""completed"" state variable is updating correctly on 20ms ticks in the ""progress"" function.</p>

<pre><code>""react-dom"": ""^16.8.6"",
""react-redux"": ""^6.0.1"",
""react-scripts"": ""^2.1.3""
</code></pre>

<p>progress.js</p>

<pre><code>import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import CircularProgress from '@material-ui/core/CircularProgress';

const styles = theme =&gt; ({
  progress: {
    margin: theme.spacing.unit * 2
  }
});

class CircularDeterminate extends React.Component {
  state = {
    completed: 0
  };

  componentDidMount() {
    this.timer = setInterval(this.progress, 20);
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  progress = () =&gt; {
    let be = this.state.completed;
    console.log('&gt;&gt;&gt;&gt;&gt;&gt; ', this.state.completed);
    const { completed } = this.state;
    this.setState({ completed: completed &gt;= 100 ? 0 : completed + 1 });
    console.log('+++++ ', be, '  ', this.state.completed);
  };

  render() {
    const { classes } = this.props;
    if (!this.props.statusCode) {
      return (
        &lt;div&gt;
          &lt;CircularProgress
            className={classes.progress}
            variant=""determinate""
            value={this.state.completed}
          /&gt;
        &lt;/div&gt;
      );
    } else {
      return null;
    }
  }
}

CircularDeterminate.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(CircularDeterminate);

</code></pre>

<p>progressTest.js</p>

<pre><code>import React from 'react';
import { shallow, mount } from 'enzyme';
import Progress from '../progress';

describe('Input Component', () =&gt; {
  it('update timer', () =&gt; {
    jest.useFakeTimers();
    const wrapper = mount(&lt;Progress /&gt;);
    wrapper.instance().setState({ completed: 8 });

    jest.advanceTimersByTime(41);
    wrapper.update();

    expect(wrapper.instance().state.completed).toBe(10);
  });
});

</code></pre>

<p>The above test fails with: Expected: 10, Received: 8. I would expect ""completed"" to be of value 10 after 2 ticks (~41 ms).</p>
",https://stackoverflow.com/questions/56380297/updating-state-with-timer-does-not-return-updated-values,"['javascript', 'reactjs', 'jestjs', 'enzyme', 'create-react-app']",89,False,0,1
Mocking out global variables prior to importing a module?,"<p>I'm trying to do unit testing for an aws lambda function that uses environment variables to create some global objects. When I try to import my local copy of the lambda into my unit test file, I will get a key error for 'LOG_LEVEL'.</p>

<pre><code>import boto3
import logging
import os

log_level = os.environ['LOG_LEVEL']
logger = logging.getLogger()
logger.setLevel(eval(log_level))


def handler(event, context):
    ...some code...
</code></pre>

<p>and inside my testing file:</p>

<pre><code>import unittest
from myModule import *
from moto import mock_dynamodb2, mock_s3
from botocore.exceptions import ClientError
</code></pre>

<p>Is there anyway I can mock out the os.environ value before I import into my testing file?</p>
",https://stackoverflow.com/questions/59459727/mocking-out-global-variables-prior-to-importing-a-module,"['python-3.x', 'amazon-web-services', 'mocking', 'python-unittest']",633,True,0,1
Global node-config variable undefined when testing with Jest,"<p>I am implementing Option 2 from the <a href=""https://github.com/lorenwest/node-config/wiki/Webpack-Usage"" rel=""nofollow noreferrer"">node-config docs</a>.</p>

<p>This runs fine, and my global config variable is defined when running outside of a test environment.</p>

<p>However, when I run this with <code>vue-cli</code> and Jest unit testing (e.g. <code>vue-cli-service test:unit</code>), I get this error:</p>

<pre><code>  ● Test suite failed to run

    ReferenceError: APP_CONFIG is not defined
</code></pre>

<pre><code>// vue.config.js
...
 configureWebpack: {
    plugins: [
      new ConfigWebpackPlugin('APP_CONFIG')
    ]
  },
...
</code></pre>

<p>What is a good way around this? Is it because Jest starts executing the JS files before the <code>node-config</code> can finish switching out all global variables with their values?</p>
",https://stackoverflow.com/questions/57084920/global-node-config-variable-undefined-when-testing-with-jest,"['vue.js', 'webpack', 'vuejs2', 'jestjs', 'node-config']",2446,True,3,1
Compile time error occur bit it did not affect anything xamarin forms,"<p>I am getting this error:</p>

<blockquote>
  <p>Error Unable to remove directory ""obj\Debug\81\android\bin\classes"". The directory is not empty.  DipsDemoXaml.Android            </p>
</blockquote>

<p>But It does not affect my code for building. But it causes when I try to test my code with unit testing and try to run all test once. Run them selecting one by one is not a problem. </p>

<p>What's the reason for this error?</p>
",https://stackoverflow.com/questions/55275966/compile-time-error-occur-bit-it-did-not-affect-anything-xamarin-forms,"['c#', 'android', 'xamarin.forms']",61,False,0,0
How do I unittest a Windows Forms method which has a message box displayed in between,"<p>I am writing a unit test script for a Windows Forms application and one of my methods pops up a message box, but I don't want to click <kbd>OK</kbd> in between my unit tests. If I do so, it will break the automated unit testing concept.</p>

<p>I searched several posts, but unfortunately I couldn't find a solution for this issue. How can I fix it?</p>
",https://stackoverflow.com/questions/55064834/how-do-i-unittest-a-windows-forms-method-which-has-a-message-box-displayed-in-be,"['c#', 'nunit']",73,False,0,0
Spring MVC - Error 404 with @EnableGlobalMethodSecurity when testing Controller using @WebMvcTest,"<p>We are trying to add unit testing to our Spring project <code>Controllers</code> (BTW, the Integration tests work fine), but we are suffering a very odd behavior, When we add the Configuration with <code>@EnableGlobalMethodSecurity</code> (with JSR-250 annotations) if the Controller implements an interface (whatever interface) the <code>Controller</code> is not included by Spring application context as ""request handler"" (I checked it on method: <code>org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.processCandidateBean(String beanName)</code>), that is, the requests mappings defined in the Controler (<code>@PostMapping</code>, ...) are not registered as potential locations, but if the interface is removed, then the Controller and the path is found without problem.</p>

<p>This is my Controller (simplified) with a simple interface <code>MyInterface</code>:</p>

<pre><code>@RestController
@RequestMapping(path = ""/api/customer"")
@RolesAllowed({Role.Const.ADMIN})
public class CustomerController implements MyInterface {    
    @Override // The only method in MyInterface 
    public void myMethod(Object param) throws QOException {
        System.out.println(""Hello"");
    }    
    @PostMapping(path = {""/"", """"})
    public Customer create(@RequestBody Customer data) throws QOException {
        return customerService.create(data);
    }
}
</code></pre>

<p>And this is the Test class (if I remove the <code>@EnableGlobalMethodSecurity</code> config class all works fine):</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(controllers = CustomerController.class)
@Import({ CustomerController.class, TestAuthConfiguration.class, TestAuthConfiguration2.class})  //, TestAuthConfiguration.class })
@ActiveProfiles({""test"", ""unittest""})
@WithMockUser(username = ""test"", authorities = { Role.Const.ADMIN })
class CustomerControllerTest {
    private static final Logger LOG = LogManager.getLogger(CustomerControllerTest.class);
    @EnableWebSecurity
    protected static class TestAuthConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            LOG.info(""configure(HttpSecurity http) "");
            http.csrf().disable().authorizeRequests().filterSecurityInterceptorOncePerRequest(true)
                    .antMatchers(""/api/session/**"").permitAll() //
                    .antMatchers(""/api/**"").authenticated() //
                    .anyRequest().permitAll().and() //
                    .addFilterBefore(new OncePerRequestFilter() {
                        @Override
                        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                FilterChain filterChain) throws ServletException, IOException {
                            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                            if (auth != null) {
                                LOG.info(""User authenticated: {}, roles: {}"", auth.getName(), auth.getAuthorities());
                            }
                            filterChain.doFilter(request, response);
                        }
                    }, BasicAuthenticationFilter.class).sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }

    }

    @EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = false)
    protected static class TestAuthConfiguration2 extends GlobalMethodSecurityConfiguration {
        @Bean
        public GrantedAuthorityDefaults grantedAuthorityDefaults() {
            return new GrantedAuthorityDefaults(""""); // Remove the ROLE_ prefix
        }
    }

    @Autowired
    MockMvc mockMvc;

    @Test
    void testCreate() throws Exception {
        Customer bean = new Customer();
        bean.setName(""Test company"");           
        when(customerServiceMock.create(bean)).thenReturn(bean);
        mockMvc.perform(post(""/api/customer"") 
        .content(JsonUtils.toJSON(bean)).contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.jsonPath(""$.name"").value(""Test company""));
    }
}
</code></pre>

<p>I don't understand what is happeing, I've tried to find an example of unit testing in controllers with security based on anotations JSR-250 (@RollesAllowed), but I didn't find anything useful, anyway this problem sounds (to me) to a bug, but I'm not sure, so any help is welcome.</p>

<p>The libraries versions:</p>

<ul>
<li>Spring Boot version: 2.2.2</li>
<li>Spring Core: 5.2.1</li>
<li>Mockito Core: 3.1.0</li>
</ul>
",https://stackoverflow.com/questions/59348034/spring-mvc-error-404-with-enableglobalmethodsecurity-when-testing-controller,"['java', 'unit-testing', 'spring-mvc-test', 'springmockito', 'jsr250']",743,True,1,1
How to address nested functions using Sinon?,"<p>Using Sequelize in the code, I can't stub crucial inner functions of it, such as .save(), .scope(), etc.. Nesting doesn't seem to work.</p>

<p>As part of unit testing, the tests fail without proper handling of those functions, saying: <code>TypeError: Cannot read property 'returns' of undefined</code></p>

<p>The error is being thrown during the execution of this line:</p>

<pre><code>  subscription.save()
</code></pre>

<p>Implementation of the stub:</p>

<pre><code>const deleteSubscription = async (subscriptionId) =&gt; {
  const ts = Math.floor(Date.now() / 1000)
  const subscription = await sql.Subscriptions.findByPk(subscriptionId);
  if (subscription == null) {
    throw new Error('Subscription not found', 'subscription_not_found')
  }
  subscription.deletedAt = ts
  subscription.save()
  return subscription
}
</code></pre>

<p>The unit-test:</p>

<pre><code>
    it('deleteSubscription succeeds', async () =&gt; {
        subscriptionsSqlStub.save.returns({})
        subscriptionsSqlStub.findByPk.returns({
            id: 1
        })
        const subscription = await subscriptions.deleteSubscription(subscriptionsSqlStub)
        expect(subscription).to.have.deep.property('id', 1)
        sinon.assert.calledOnce(subscriptionsSqlStub.findByPk)
        subscriptionsSqlStub.findByPk.resetHistory()
    })
</code></pre>

<p>How can I address the inner/nested functions?</p>
",https://stackoverflow.com/questions/56887616/how-to-address-nested-functions-using-sinon,"['node.js', 'unit-testing', 'sinon']",366,True,0,1
How to fix &#39;$timeout is not a function&#39; error in Jasmine?,"<p>I get an TypeError: this.$timeout is not a function on unit testing with Jasmine for angular.js app. </p>

<p>I run a timeout service on my onInit, which gives the error.</p>

<p>Can't find a solution to fix this problem.</p>

<p>The onInit look like: </p>

<pre><code>constructor($document, $window, $element, $timeout) {
    this.$document = $document;
    this.$window = $window;
    this.$element = $element;
    this.$timeout = $timeout;
}

$onInit() {
    const elementsList = this.element.children;
    const currentPage = elementsList.findIndex(pageController.findElement) + 1;
    const totalPages = elementsList.length;

    if (totalPages &gt; 1) {
        this.elementsList = elementsList;
        this.currentPage = currentPage;
        this.totalPages = totalPages;
    }

    this.$timeout(() =&gt; {
        this.getCurrentPage().style.width = 'auto';
        this.currentStepWidth = this.getCurrentPage().clientWidth;
    });
}
</code></pre>

<p>and the spec file:</p>

<pre><code>describe('$onInit', () =&gt; {
    fit('should set currentPage and totalPages', () =&gt; {
        let pageCounter = new pageController();
        pageCounter.element = {
            children: [
                { styles: ['pageCurrent'] },
                { styles: ['pageVisited'] }
            ]
        };

        // When
        pageCounter.$onInit();

        // Then
        expect(pageCounter.currentPage).toEqual(1);
        expect(pageCounter.totalSteps).toEqual(2);
    });
});
</code></pre>

<p>When I run the test, I get the TypeError: this.$timeout is not a function</p>

<p>How can I fix this?</p>
",https://stackoverflow.com/questions/57660400/how-to-fix-timeout-is-not-a-function-error-in-jasmine,"['javascript', 'angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",124,False,0,0
Chai Cannot read property &#39;should&#39; of null,"<p>I'm getting the following error when unit testing for a single item using <a href=""https://github.com/tgriesser/knex"" rel=""nofollow noreferrer"">knex</a>. I'm also referencing this <a href=""https://mherman.org/blog/test-driven-development-with-node/"" rel=""nofollow noreferrer"">https://mherman.org/blog/test-driven-development-with-node/</a></p>

<p>It renders api/users/1 successfully. So not sure why it says null. </p>

<blockquote>
  <p>GET /api/users/:id
         Should return a single show :
       Uncaught TypeError: Cannot read property 'should' of null
        at should (tests/users.spec.js:59:26)</p>
</blockquote>

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

<pre><code>import chai from 'chai';
import { expect } from 'chai';
import chaiHttp from 'chai-http';
import { assert } from 'assert'
import users from '../routes/users';
import request from 'supertest';


describe('GET /api/users/:id ', () =&gt;{
    it('Should return a single show ', (done)=&gt; {
       chai.request(users)
            .get('/users/1')
            .set('Accept', 'application/json')
            .end((response) =&gt; {
                // error begins here
                response.should.have.status(200);
                response.should.be.json; 
                response.body.should.be.a('object');
                response.body.should.have.property('id');
                response.body.name.should.equal(1);
                done()
            })          

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

<p><strong>routes/users.js</strong></p>

<pre><code>users.get('/users/:id', (req, res) =&gt; {
    return knex('users').where({id: req.params.id})
        .then( (user) =&gt; {
            res.json({
                user: user
            })
        });
})
</code></pre>
",https://stackoverflow.com/questions/55600750/chai-cannot-read-property-should-of-null,"['javascript', 'mocha.js', 'chai', 'knex.js']",1911,True,0,1
Lumen phpunit get request fails and gives 500 when I access the uri parameter via $request-&gt;route(&#39;whatever&#39;),"<p>I'm sending a <code>GET</code> request via Lumen unit testing using</p>

<p><code>$this-&gt;get('api/cars/volvo/')</code></p>

<p>where <em>volvo</em> is a route parameter.</p>

<p>When this request reaches my controller, it returns a <code>500</code> response because I'm accessing the URI parameter through</p>

<p><code>$request-&gt;route('company')</code></p>

<p>Note that this only occurs when I send request through unit test, not the normal request if I send for example from Postman.</p>

<p>Example:</p>

<pre class=""lang-php prettyprint-override""><code>$response = $this-&gt;get('/api/v1/cars/volvo', $header);
$response-&gt;assertResponseStatus(200);
</code></pre>

<p>I get the following when I run this test:</p>

<pre><code>1) Tests\ApiTest::test_get_cars
Expected status code 200, got 500.
Failed asserting that 500 matches expected 200.
</code></pre>
",https://stackoverflow.com/questions/55019259/lumen-phpunit-get-request-fails-and-gives-500-when-i-access-the-uri-parameter-vi,"['unit-testing', 'testing', 'laravel-5', 'lumen']",203,False,0,0
SpringBoot JavaMailSender is null even if autowired,"<p>I am trying to implement mail sending capability to my web App. The problem is with JavaMailSender which is not getting auto wired neither when running the app nor when unit-testing. I really don't get it why it does not want to instantiate the JavaMailSender object. I have properly set both application.properties as well as application-test.properties. </p>

<p>application.properties &amp; application-test.properties</p>

<pre><code>spring.mail.host=mail.xxx.com
spring.mail.username=noreply@xxx.com
spring.mail.password=xxx
spring.mail.properties.mail.smtp.port=587
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
</code></pre>

<p>My EmailSender.class</p>

<pre><code>@Component
public class EmailSender {

    private static final Logger log = LoggerFactory.getLogger(EmailSender.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private Configuration freeMarkerConfig = null;
    @Autowired
    private JujuServerProperties serverProperties = null;

    private List&lt;RuntimeTypeAdapterFactory&gt; adapterFactoryList;

    private AbstractSamplePostSynchroActions abstractSamplePostSynchroActions;

    //FIXME CE CODE EST A 2 ENDROITS (SendEmailProcessor)
    public void send(int projectId,int questionnaireId, int terminalId) {
        try {

            // TODO: Revoir certaind crite pour l&lt;envoi de courrier test. Ceci devrait inclure la presence des entree postSynchro dans la BD. valider la correspondance avec une question email dans le questionnaire
            adapterFactoryList = new ArrayList&lt;&gt;();
            adapterFactoryList.add(prepareMediaQuestionAdapters());
            adapterFactoryList.add(prepareSocialMediaAdapters());
            adapterFactoryList.add(prepareConditionAdapters());

            ObjectMapper mapper = new ObjectMapper();
            File fic = new File(IOUtils.getTerminalDir(projectId, questionnaireId,terminalId)+ File.separator+""Email""+File.separator+""email.json"");

            Email emailConfig = EmailUtil.generateEmailConfigurationFromJsonFile(fic,adapterFactoryList);

            ConditionsEvaluator conditionsEvaluator = emailConfig.getConditionsEvaluator();

            Map&lt;String, Object&gt; model = new HashMap&lt;&gt;();
            PostSynchroUtil.generateEmail(projectId,questionnaireId,terminalId,adapterFactoryList);
            File file = new File(IOUtils.getTerminalDir(projectId, questionnaireId,terminalId)+""Email""+File.separator+""email.xml"");
            //initEmailModel(model, respondent);
            SampleEmailData sample = (SampleEmailData)abstractSamplePostSynchroActions;
            MimeMessagePreparator preparator = mimeMessage -&gt; {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                for(QuestionCondition questionCondition : conditionsEvaluator.getConditions())
                {
                    if(questionCondition.getQuestion_type().contains(""email""))
                    {

                        String emailAddr = sample.getEmailAddrs();
                        message.setTo(emailAddr);
                    }
                }

                message.setFrom(""noreply@nomadlogicapp.com"",""noreply@nomadlogicapp.com"");
                message.setSubject(""Test Email From Juju Console"");
                StringWriter out = new StringWriter();




                message.setText(sample.getMsg(),true);
            };

            this.mailSender.send(preparator);


        } catch (Exception ex) {
            log.error(""{}"", ex);
        }
    }

    private void initEmailModel(Map&lt;String, Object&gt; model, IRespondent respondent, Email email) {
        model.put(""email"", email);
        model.put(""respondent"", respondent);
        model.put(""server"", serverProperties.getServerAdress());

    }

    public AbstractSamplePostSynchroActions getAbstractSamplePostSynchroActions() {
        return abstractSamplePostSynchroActions;
    }

    public void setAbstractSamplePostSynchroActions(AbstractSamplePostSynchroActions abstractSamplePostSynchroActions) {
        this.abstractSamplePostSynchroActions = abstractSamplePostSynchroActions;
    }
}
</code></pre>

<p>Spring Configuration class</p>

<pre><code>package com.nomadlogic.juju;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


@ConfigurationProperties(prefix = ""juju-server"")
@Component
public class JujuServerProperties {
    private String address;
    private String port;
    private String dns;

    public String getServerAdress() {
        return this.address + "":"" + this.port;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getDns() {
        return dns;
    }

    public void setDns(String dns) {
        this.dns = dns;
    }
}
</code></pre>
",https://stackoverflow.com/questions/56138692/springboot-javamailsender-is-null-even-if-autowired,"['java', 'spring', 'spring-boot', 'http', 'smtp']",40,False,0,0
Configuring Jest and Enzyme for React app using create-react-app,"<p>I have built a sample React application using create-react-app (CRA), I am trying to write the unit testing for the application.</p>
<p>Using Jest and Enzyme, I have installed the required packages as the dev dependencies</p>
<pre><code>    &quot;enzyme&quot;: &quot;^3.10.0&quot;,
    &quot;enzyme-adapter-react-16&quot;: &quot;^1.15.1&quot;,
    &quot;jest&quot;: &quot;^24.9.0&quot;
</code></pre>
<p><strong>jest.config.js</strong> - located <strong>outside</strong> of <strong>src</strong> folder</p>
<pre><code>module.exports = {
    verbose: true,
    setupFilesAfterEnv: [&quot;./src/setupTest.js&quot;],
};
</code></pre>
<p><strong>setupTest.js</strong> - located <strong>inside</strong> of <strong>src</strong> folder root</p>
<pre><code>import { configure } from &quot;enzyme&quot;;
import Adapter from &quot;enzyme-adapter-react-16&quot;;

configure({ adapter: new Adapter() });
</code></pre>
<p><strong>App.test.js</strong></p>
<pre><code>import React from &quot;react&quot;;
import { shallow } from &quot;enzyme&quot;;

import App from &quot;./App&quot;;

describe(&quot;&lt;App /&gt;&quot;, () =&gt; {
    it(&quot;Renders the app component&quot;, () =&gt; {
        const wrapper = shallow(&lt;App /&gt;);
        expect(wrapper).toMatchSnapshot();
    });
});
</code></pre>
<p>When I try to do <strong>npm run test</strong>, it's giving the below error:</p>
<pre><code>Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none.
      To configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })`
      before using any of Enzyme's top level APIs, where `Adapter` is the adapter
      corresponding to the library currently being tested. For example:

      import Adapter from 'enzyme-adapter-react-15';

      To find out more about this, see http://airbnb.io/enzyme/docs/installation/index.html

   6 | describe(&quot;&lt;App /&gt;&quot;, () =&gt; {
   7 |     it(&quot;Renders the app component&quot;, () =&gt; {
&gt;  8 |         const wrapper = shallow(&lt;App /&gt;);
     |                         ^
   9 |         expect(wrapper).toMatchSnapshot();
  10 |     });
  11 | });
</code></pre>
",https://stackoverflow.com/questions/59083772/configuring-jest-and-enzyme-for-react-app-using-create-react-app,"['reactjs', 'jestjs', 'create-react-app', 'enzyme']",2544,True,0,2
Unit testing Android Tab Layout,"<p>I am new to Android Unit testing and trying to write some test cases for Android tab layout with <code>Robolectric</code>. I am able to verify the tab count and tab titles. But I am not able to verify some content in tabs. Can anyone help me in getting the fragment content and verify some elements in that?</p>

<p>Here is my code</p>

<pre><code>public void verifyTabsDefaultText() throws Exception{
    ViewPager viewPager = searchActivity.findViewById(R.id.container);
    FragmentPagerAdapter tabAdapter = (FragmentPagerAdapter) viewPager.getAdapter();

    viewPager.setCurrentItem(0);

    TextView hintTextView = tabAdapter.getItem(0).getActivity().findViewById(R.id.search_hint_text_view);

    assertTrue(hintTextView.getVisibility() == View.VISIBLE);

}
</code></pre>

<p><code>tabAdapter.getItem(0)</code> is giving <code>null</code> value.</p>

<p>Thanks in advance. </p>
",https://stackoverflow.com/questions/57057785/unit-testing-android-tab-layout,"['android', 'robolectric']",2078,False,0,3
Rest API Unit Testing Using Moq,"<p>How to test Rest API..?</p>

<p>In my project we have mocked data access layer. In unit test via end point will hit business layer and it returns the same value which has been mocked.</p>

<p>Since, our unit test will always pass as we have mocked then what is the use of unit testing..?</p>

<p>Let me know if there are any better ways of testing rest end points.</p>
",https://stackoverflow.com/questions/55063626/rest-api-unit-testing-using-moq,"['rest', 'unit-testing', 'moq']",111,False,0,1
Python Mock Patch From Another File/Module,"<p>I have a mock that works fine as expected. </p>

<pre><code>from mock import patch

def second(arg):
    return 3


def first():
    return second('arg')


@patch('test.second')
def test_test(second_mock):
    second_mock.return_value = 47  # We decide this

    call_it = first()

    second_mock.assert_called_once()
    second_mock.assert_called_with('arg')

    assert call_it == 47
</code></pre>

<p>But not if i move me second() method to another file...</p>

<pre><code>from mock import patch
from test_help import second


def first():
    return second('arg')


@patch('test_help.second')
def test_test(second_mock):
    second_mock.return_value = 47  # We decide this

    call_it = first()

    second_mock.assert_called_once()
    second_mock.assert_called_with('arg')

    assert call_it == 47
</code></pre>

<p>I get the same error: AssertionError: Expected 'second' to have been called once. Called 0 times.</p>

<p>What am I missing here?</p>

<p>I have tried a few different ways of formatting, but none seem to work. Is this even the best practice/package in this case for unit testing?</p>
",https://stackoverflow.com/questions/56939533/python-mock-patch-from-another-file-module,"['python', 'mocking', 'pytest', 'pytest-mock']",1895,True,2,1
Jest testing Vue Single File Components with Ionic Capacitor plugin imports,"<p><a href=""https://github.com/calebbergman/capacitortest.git"" rel=""nofollow noreferrer"">GitHub repo</a> of the issue.</p>

<p>I'm building an Ionic app using Vue and Capacitor. I'm setting up unit tests using vue-test-utils + Jest. Jest unit tests are failing trying to import Capacitor plugins into Vue Single File Components.</p>

<p>The Vue app was created using Vue CLI 3 (v3.4.0). CLI options included unit testing using Jest. I'm new to unit testing altogether. I've naively tried <a href=""https://jestjs.io/docs/en/mock-functions#mocking-modules"" rel=""nofollow noreferrer"">mocking</a> the @capacitor/core module prior to importing the Vue component; this didn't help.</p>

<p><strong><em>jest.config.js</em></strong> (Vue CLI default)</p>

<pre><code>module.exports = {
  moduleFileExtensions: [""js"", ""jsx"", ""json"", ""vue""],
  transform: {
    ""^.+\\.vue$"": ""vue-jest"",
    "".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$"":
      ""jest-transform-stub"",
    ""^.+\\.jsx?$"": ""babel-jest""
  },
  transformIgnorePatterns: [""/node_modules/""],
  moduleNameMapper: {
    ""^@/(.*)$"": ""&lt;rootDir&gt;/src/$1""
  },
  snapshotSerializers: [""jest-serializer-vue""],
  testMatch: [
    ""**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)""
  ],
  testURL: ""http://localhost/"",
  watchPlugins: [
    ""jest-watch-typeahead/filename"",
    ""jest-watch-typeahead/testname""
  ]
};

</code></pre>

<p><strong><em>MyComponent.vue</em></strong></p>

<pre><code>&lt;template&gt;...&lt;/template&gt;
&lt;script&gt;
import { Plugins } from '@capacitor/core'
const { Filesystem } = Plugins
...
&lt;/script&gt;
</code></pre>

<p><strong><em>MyComponent.spec.js</em></strong></p>

<pre><code>import { shallowMount } from ""@vue/test-utils"";
import Component from ""@/components/MyComponent.vue"";
...
</code></pre>

<p>I expect the test to run without issue. Instead, I get the following error message when Jest tries to import the component on line 2 of the spec file:</p>

<pre><code>TypeError: Cannot destructure property `Filesystem` of 'undefined' or 'null'.

      35 | &lt;script&gt;
      36 | import { Plugins } from '@capacitor/core'
    &gt; 37 | const { Filesystem } = Plugins
</code></pre>

<p><code>Plugins</code> is undefined on line 36, thusly line 37 complains when it attempts to destructure <code>Filesystem</code> from it.</p>

<p>In a browser, however, the <code>Filesystem</code> object is as follows:</p>

<pre><code>{
  ""config"": {
     ""name"": ""Filesystem"",
     ""platforms"": [""web""]
  },
  ""loaded"": false,
  ""listeners"": {}, 
  ""windowListeners"":{},
  ""DEFAULT_DIRECTORY"": ""DATA"",
  ""DB_VERSION"": 1,
  ""DB_NAME"": ""Disc"",
  ""_writeCmds"": [""add"",""put"",""delete""]
}
</code></pre>

<hr>

<p>I don't know where the issue lies. I don't know if I should be doing something different with Jest, I don't know if I shouldn't be importing Capacitor plugins directly in Vue SFCs like I've seen in some <a href=""https://www.smashingmagazine.com/2018/07/mobile-apps-capacitor-vue-js#example-adding-a-capacitor-plugin"" rel=""nofollow noreferrer"">examples</a>, or...🤷‍♂️.</p>
",https://stackoverflow.com/questions/56707580/jest-testing-vue-single-file-components-with-ionic-capacitor-plugin-imports,"['vue.js', 'ionic-framework', 'jestjs', 'vue-test-utils', 'capacitor']",850,True,0,2
Django test client does not provide the right authentication headers,"<p>When sending a request to the development server, I can include a header as follows:</p>

<pre><code>Authorization: Token efc7fa291f4e320ff4a31cf9a11d6de3a366937cd1ec24e0a7ab68dafa38430f\r\n
</code></pre>

<p>Internally Django sees an <code>HTTP_AUTHORIZATION</code> header, which I am not sure where is generated.</p>

<p>But when using the Django test client for unit testing:</p>

<pre><code>from django.test import Client

c = Client()
response = c.get('/api/auth/user/', **{'Authorization': 'Token ' + token})
</code></pre>

<p>Django can not authorize the request.</p>

<p>If instead I do the following:</p>

<pre><code>response = c.get('/api/auth/user/', **{'HTTP_AUTHORIZATION': 'Token ' + token})
</code></pre>

<p>It works.</p>

<p>I would like to understand what is going on.</p>

<p>Who is responsible of performing the mapping <code>Authorization</code> -> <code>HTTP_AUTHORIZATION</code>?</p>

<p>Relevant for this question: I am using <code>Django 2.1.5</code>, <code>djangorestframework = ""==3.9.0""</code> and <code>djangorestframework = ""==3.9.0""</code></p>
",https://stackoverflow.com/questions/54674844/django-test-client-does-not-provide-the-right-authentication-headers,"['django', 'authentication']",782,True,8,1
How to test using assertEquals an element of a Set in Java?,"<p>I need to make unit testing for a Java method, and I have a Set like this:</p>

<pre><code>Set&lt;CreditCard&gt; creditCard = ...
</code></pre>

<p>And I need to test if an element of this Set is equal with a specific value. It is very easy to do that if creditCard is an ArrayList, I can do something like this:</p>

<pre><code>assertEquals(creditCard.get(0).getCreditCardBalance(), CREDIT_CARD_BALANCE);
</code></pre>

<p>But unfortunately this is a Set and not an ArrayList. How can I test this? Thank you!</p>
",https://stackoverflow.com/questions/58437468/how-to-test-using-assertequals-an-element-of-a-set-in-java,"['java', 'set', 'mockito']",399,False,2,1
Injectmocks unable to instantiate because No thread-bound request found,"<p>I am trying to create a logging utility in REST API and I would require some details from HttpServletRequest for the same. </p>

<p>Below is code for logging utility:</p>

<pre><code>import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import lombok.Getter;
import lombok.Setter;

@Component
@Scope(scopeName = ""session"",proxyMode = ScopedProxyMode.TARGET_CLASS)
@Getter
@Setter
public class LoggingUtil {

    private String uri;
    private String callerIp;
    private String authorization;

    public LoggingUtil() {
        HttpServletRequest httpServletRequest = 
                ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
        this.uri = httpServletRequest.getRequestURI();
        this.callerIp = httpServletRequest.getRemoteAddr();
        this.authorization = httpServletRequest.getHeader(""Authorization"");
    }

    public void log() {
        System.out.println(""URI is ""+this.uri+"" Caller IP is ""+this.callerIp+""authorization id is ""+this.authorization);
    }
}
</code></pre>

<p>I am trying for unit testing the class using JUnit-Mockito framework, but the test coverage always has the issue with InjectMocks not working properly. </p>

<p>Below is unit test case code :</p>

<pre><code>import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;

import javax.servlet.http.HttpServletRequest;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.omg.CORBA.portable.ResponseHandler;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.context.request.RequestContextHolder;

@RunWith(SpringJUnit4ClassRunner.class)
public class LoggingUtilTest {

    @InjectMocks
    LoggingUtil loggingUtil;

    @Mock
    static HttpServletRequest httpServletRequest;

    @Mock
    static MockHttpServletRequest request = new MockHttpServletRequest();

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        httpServletRequest = mock(HttpServletRequest.class);
        request.setServerName(""www.example.com"");
        request.setRequestURI(""/foo"");
        request.setQueryString(""param1=value1&amp;param"");
    }

    @Test
    public final void testLoggingUtil() {
        assertEquals(request.getRequestURI(),""/foo"");
    }

}
</code></pre>

<p>Below is the error that is displayed in console :</p>

<pre><code>org.mockito.exceptions.misusing.InjectMocksException: 
Cannot instantiate @InjectMocks field named 'loggingUtil' of type 'class in.name.util.LoggingUtil'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.initMocks(MockitoTestExecutionListener.java:68)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:53)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    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$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    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: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)
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
    at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
    at in.name.util.LoggingUtil.&lt;init&gt;(LoggingUtil.java:27)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.mockito.internal.util.reflection.FieldInitializer$NoArgConstructorInstantiator.instantiate(FieldInitializer.java:195)
    at org.mockito.internal.util.reflection.FieldInitializer.acquireFieldInstance(FieldInitializer.java:137)
    at org.mockito.internal.util.reflection.FieldInitializer.initialize(FieldInitializer.java:91)
    at org.mockito.internal.configuration.injection.PropertyAndSetterInjection.initializeInjectMocksField(PropertyAndSetterInjection.java:94)
    at org.mockito.internal.configuration.injection.PropertyAndSetterInjection.processInjection(PropertyAndSetterInjection.java:79)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.process(MockInjectionStrategy.java:68)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.relayProcessToNextStrategy(MockInjectionStrategy.java:89)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.process(MockInjectionStrategy.java:71)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.relayProcessToNextStrategy(MockInjectionStrategy.java:89)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.process(MockInjectionStrategy.java:71)
    at org.mockito.internal.configuration.injection.MockInjection$OngoingMockInjection.apply(MockInjection.java:92)
    at org.mockito.internal.configuration.DefaultInjectionEngine.injectMocksOnFields(DefaultInjectionEngine.java:25)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.injectMocks(InjectingAnnotationEngine.java:87)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.processInjectMocks(InjectingAnnotationEngine.java:48)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:42)
    at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)
    ... 25 more
</code></pre>
",https://stackoverflow.com/questions/57773963/injectmocks-unable-to-instantiate-because-no-thread-bound-request-found,"['java', 'spring', 'spring-boot', 'unit-testing', 'junit']",2151,True,2,2
How can I extract the properties of an interface using TypeScript (preferably with no 3rd party libs),"<p>I need to get the properties of an interface to make sure that they match an object that implements it. For unit testing purposes.</p>

<p>So if changes are made to the interface the unit test should break if it isn't updated with the new members.</p>

<p>I've tried using the ts-transformer-keys package but it throws an error about not being a function.</p>

<pre class=""lang-js prettyprint-override""><code>   interface Test {
      mem1: boolean,
      mem2: string
   }
</code></pre>

<p>I would like to do something like this:</p>

<pre><code>   console.log(Object.keys(Test))
</code></pre>

<p>and expect</p>

<pre><code>   ['mem1', 'mem2'];
</code></pre>
",https://stackoverflow.com/questions/57768494/how-can-i-extract-the-properties-of-an-interface-using-typescript-preferably-wi,"['angular', 'typescript']",7892,False,4,3
When to prefix a BUILD file (*.BUILD) in Bazel,"<p>In its C++ unit testing tutorial, Bazel suggests adding a root level <code>gtest.BUILD</code> file to the workspace root in order to properly integrate Google Test into the test project.</p>

<p><a href=""https://docs.bazel.build/versions/master/cpp-use-cases.html"" rel=""nofollow noreferrer"">https://docs.bazel.build/versions/master/cpp-use-cases.html</a></p>

<p>Why would one create a new BUILD file and add <code>gtest</code> prefix to it rather than adding a new build rule to an existing BUILD file in the workspace? Is it just a minor style preference?</p>
",https://stackoverflow.com/questions/58593443/when-to-prefix-a-build-file-build-in-bazel,['bazel'],408,True,1,1
"Typescript, Babel 7, Karma, Jasmine, Code Coverage Configuration","<p>I'm developing a standalone library in Typescript and am trying to setup unit testing and code coverage with Karma, Jasmine, and Babel 7.  I wrote a couple of simple tests and am attempting to have Karma run them, but zero tests are running.  The message <code>03 08 2019 07:36:35.252:WARN [middleware:karma]: Invalid file type (ts), defaulting to js.</code> is emitted the console, followed by <code>Executed 0 of 0 ERROR (0.005 secs / 0 secs)</code>.  This is telling me I'm missing something from the Karma config file, but I'm not certain of what the missing piece is.</p>

<p>karma.config.js</p>

<pre><code>module.exports = function (config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',


        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],


        // list of files / patterns to load in the browser
        files: [
            'src/**/*.ts'
        ],


        // list of files / patterns to exclude
        exclude: [],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'spec/**/*.spec.ts': ['babel'],
            'src/**/*.ts': ['babel']
        },


        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress'],

        coverageReporter: {
            reporters: [
                {
                    type: 'html',
                    dir: 'coverage/'
                }
            ]
        },

        // web server port
        port: 9876,


        // enable / disable colors in the output (reporters and logs)
        colors: true,


        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,


        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,


        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],


        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity,
    });
};
</code></pre>

<p>.babelrc</p>

<pre><code>{
    ""sourceMaps"": ""inline"",
    ""presets"": [
        ""@babel/env"",
        ""@babel/typescript""
    ],
    ""plugins"": [
        ""@babel/proposal-class-properties"",
        ""@babel/proposal-object-rest-spread""
    ]
}
</code></pre>
",https://stackoverflow.com/questions/57338028/typescript-babel-7-karma-jasmine-code-coverage-configuration,"['typescript', 'jasmine', 'karma-jasmine', 'babeljs', 'karma-coverage']",644,False,4,0
Unit Testing Jest in Reactjs Component state,"<p>Hello :) I'm starting to learn <strong>Unit Testing</strong> using <strong>JEST &amp; Enzyme</strong></p>

<p>on my version (already done) of ""Color Guessing Game"" using with <strong>Reactjs</strong>, 
but when I started to test my Square Component I can't even test my color state value and my color state when clicked (clickSquare function)...</p>

<p>and I can't find much resources about it, can you see what's wrong, and how can I test my Square Component?</p>

<p><strong>Square.js Component:</strong></p>

<pre><code>import React, { Component } from 'react';



class Square extends Component {




constructor(props) {
    super(props);
    this.state = {
      color: undefined
    }
    this.clickSquare = this.clickSquare.bind(this);
  }

  componentDidMount() {
    if (this.props.color) {
      this.setState({
        color: this.props.color
      })
    }
  };

  componentWillReceiveProps(props) {
    //results in the parent component to send updated props,, 
    //whenever the propositions are updated in the parent, runs this
    //to update the son as well
    this.setState({
      color: props.color
    })

  }

  clickSquare() {
    if (this.state.color === this.props.correctColor) {
      this.props.gameWon(true);
      console.log('correct', this.state.color)

    } else {
      this.setState({
        color: 'transparent'
      })
      //    this.props.gameWon(false);
      console.log('wrong')

    }
  };

  render() {

    return (
      &lt;div className='square square__elem'
        style={{ backgroundColor: this.state.color }}
        onClick={this.clickSquare}&gt;
      &lt;/div&gt;
    );
  }
};

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

<p><strong>Square.test.js Testing:</strong></p>

<pre><code>import React from 'react';

import Square from '../components/Square/Square';

import { shallow, mount } from 'enzyme';


describe('Square component', () =&gt; {

    let wrapper;
    beforeEach(() =&gt; wrapper = shallow(
        &lt;Square
            color={undefined}
            clickSquare={jest.fn()}
        /&gt;
    ));


    it('should render correctly', () =&gt; expect(wrapper).toMatchSnapshot());

    it('should render a &lt;div /&gt;', () =&gt; {
        expect(wrapper.find('div.square.square__elem').length).toEqual(1);
    });

    it('should render the value of color', () =&gt; {
        wrapper.setProps({ color: undefined});
        expect(wrapper.state()).toEqual('transparent');
      });

});
</code></pre>

<blockquote>
  <p>Expected value to equal:
        ""transparent""
      Received:
        {""color"": undefined}</p>

<pre><code>Difference:

  Comparing two different types of values. Expected string but received object.
</code></pre>
</blockquote>
",https://stackoverflow.com/questions/54892546/unit-testing-jest-in-reactjs-component-state,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",54008,True,10,1
How to return different value for a static method which is invoked during the flow during unit testing?,"<p>I'm trying to write unit testing for the following snippet.</p>

<pre><code>class ABC {
    int getMyValue(final Activity activity) {
        if(MyClass.getInstance(activity).getValue() == 1) return 10;
        else return 20;
    }

    void doSomething() {
    }
}
</code></pre>

<p>I've tried something like this to test the <code>doSomething</code> function.</p>

<pre><code>mABC = new ABC();

public void test_doSomething() {
   doReturn(20).when(mABC).getMyValue();
   //validate
}
</code></pre>

<p>How can I test <code>getMyValue</code> similarly? I would like to assert when the value is 1 it's returning me 10 and in all other cases, it's returning me 20.</p>

<p>I'm doing this in my android application. Is there any existing framework that can help me do this?</p>

<p>EDIT:</p>

<p><code>MyClass</code> looks something like this</p>

<pre><code>public class MyClass {

   private static Context mContext;
   public static getInstance(Context context) {
     mContext = context;
     return new MyClass();
   }

   private MyClass() {}

   public void getDreamValue() {
     Settings.Secure.getInt(mContext.getContentResolver(), ""dream_val"", -1);
   }
}
</code></pre>
",https://stackoverflow.com/questions/59444370/how-to-return-different-value-for-a-static-method-which-is-invoked-during-the-fl,"['android', 'unit-testing', 'junit', 'mockito', 'robolectric']",599,True,1,1
enzyme testing react with context api,"<p>I'm trying to test a form. When the form is submitted it should set a state on <code>error: true</code> and then a <code>div</code> with an error information should appear. My test looks like this:</p>

<pre><code> outer = shallow(&lt;Search /&gt;);

 it(""should not submit a form and display an error if title or author is empty"", () =&gt; {
    const Children = outer.props().children({});
    const wrapper = mount(Children);
    const button = wrapper.find(""form button"");
    button.simulate(""submit"", {
      preventDefault() {
        outer.setState({ error: true });
      }
    });
    expect(wrapper.find(""div.error"")).toHaveLength(1);
  });
</code></pre>

<p>Unfortunately it doesn't work. I am new to unit testing and I have no idea if I'm doing it correctly and how should I fix that. </p>

<p>I think I also should get somehow inputs values but don't know how.</p>
",https://stackoverflow.com/questions/56790357/enzyme-testing-react-with-context-api,"['reactjs', 'jestjs', 'enzyme']",156,True,1,1
Angular unit testing form validation - control stays untouched,"<p>I've an Angular component which has form validation. I'm unit testing to make sure it displays an error message if the input is invalid.</p>

<p>But when I try to change the <code>&lt;input&gt;</code> box value, the control's state remains <code>untouched</code> and the error doesn't display.</p>

<p>Here's the code:</p>

<pre><code>&lt;form #zipForm=""ngForm""&gt;
&lt;label&gt;
    &lt;input type=""text"" id=""postalCode"" [(ngModel)]=""postalCode"" #postalCodeElem=""ngModel"" name=""postalCode"" [pattern]=""validationPattern"" required&gt;
    &lt;button type=""button"" (click)=""click(postalCodeElem.value)""&gt;Enroll&lt;/button&gt;
    &lt;div *ngIf=""postalCodeElem.invalid &amp;&amp; postalCodeElem.touched""&gt;
    &lt;span id=""required-postal-code"" *ngIf=""postalCodeElem?.errors?.required""&gt;
        zip/postal code is required
    &lt;/span&gt;
    &lt;span id=""invalidPostalCode"" *ngIf=""postalCodeElem?.errors?.pattern""&gt;
        zip postal code is invalid
    &lt;/span&gt;
    &lt;/div&gt;
&lt;/label&gt;
&lt;/form&gt;
</code></pre>

<p>Test file:</p>

<pre><code>it('should show error in case of invalid postal code', () =&gt; {
    const elem: HTMLElement = fixture.nativeElement;
    const inputElem: HTMLInputElement = elem.querySelector('input');

    inputElem.value = 'L5L2';
    inputElem.dispatchEvent(new Event('input', { bubbles: true }));

    fixture.detectChanges();

    const invalidErrorElem: any = elem.querySelector('span');

    console.log('elem', elem);
    console.log('invalidErrorElem', invalidErrorElem);

    expect(invalidErrorElem).not.toBeNull();
});
</code></pre>

<p>I've created a stackblitz to demo the issue: <a href=""https://stackblitz.com/edit/angular-testing-45zwkn?file=app%2Fapp.component.spec.ts"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/angular-testing-45zwkn?file=app%2Fapp.component.spec.ts</a></p>

<p>Any idea what am I doing wrong?</p>
",https://stackoverflow.com/questions/54442920/angular-unit-testing-form-validation-control-stays-untouched,"['angular', 'unit-testing', 'testing', 'jasmine']",2232,True,1,1
How to write unit tests for kotlin coroutines,"<p>I am trying to unit test the kotlin coroutines. My project is following MVP pattern where the coroutines are used in the presenter like this:</p>

<pre><code>fun authenticateWithUserAndPassword(usernameOrEmail: String, password: String) {
        launchUI(strategy) {
            view.showLoading()
            try {
                val token = retryIO(""login"") {
                    when {
                        settings.isLdapAuthenticationEnabled() -&gt;
                            client.loginWithLdap(usernameOrEmail, password)
                        usernameOrEmail.isEmail() -&gt;
                            client.loginWithEmail(usernameOrEmail, password)
                        else -&gt;
                            client.login(usernameOrEmail, password)
                    }
                }
                val myself = retryIO(""me()"") { client.me() }
                myself.username?.let { username -&gt;
                    val user = User(
                        id = myself.id,
                        roles = myself.roles,
                        status = myself.status,
                        name = myself.name,
                        emails = myself.emails?.map { Email(it.address ?: """", it.verified) },
                        username = username,
                        utcOffset = myself.utcOffset
                    )
                    localRepository.saveCurrentUser(currentServer, user)
                    saveCurrentServer.save(currentServer)
                    localRepository.save(LocalRepository.CURRENT_USERNAME_KEY, username)
                    saveAccount(username)
                    saveToken(token)
                    analyticsManager.logLogin(
                        AuthenticationEvent.AuthenticationWithUserAndPassword,
                        true
                    )
                    view.saveSmartLockCredentials(usernameOrEmail, password)
                    navigator.toChatList()
                }
            } catch (exception: RocketChatException) {
                when (exception) {
                    is RocketChatTwoFactorException -&gt; {
                        navigator.toTwoFA(usernameOrEmail, password)
                    }
                    else -&gt; {
                        analyticsManager.logLogin(
                            AuthenticationEvent.AuthenticationWithUserAndPassword,
                            false
                        )
                        exception.message?.let {
                            view.showMessage(it)
                        }.ifNull {
                            view.showGenericErrorMessage()
                        }
                    }
                }
            } finally {
                view.hideLoading()
            }
        }
    }
</code></pre>

<p>Here launchUI is defined as </p>

<pre><code>/**
 * Launches a coroutine on the UI context.
 *
 * @param strategy a CancelStrategy for canceling the coroutine job
 */
fun launchUI(strategy: CancelStrategy, block: suspend CoroutineScope.() -&gt; Unit): Job =
    MainScope().launch(context = strategy.jobs, block = block)
</code></pre>

<p>CancelStrategy class</p>

<pre><code>class CancelStrategy(owner: LifecycleOwner, val jobs: Job) : LifecycleObserver {

    init {
        owner.lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        jobs.cancel()
    }
}
</code></pre>

<p>I am new to coroutine unit testing and tried writing a basic unit test</p>

<pre><code>@Test
fun check_authentication_of_user() = runBlocking {
    loginPresenter.authenticateWithUserAndPassword(USERNAME, PASSWORD)
    verify(navigator).toChatList()
}
</code></pre>

<p>On running the test I am getting the following error.</p>

<pre><code>java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlinx.coroutines.BuildersKt__Builders_commonKt.launch, parameter context
</code></pre>

<p>Any help regarding how to unit test the given method will be appreciated.</p>
",https://stackoverflow.com/questions/56603445/how-to-write-unit-tests-for-kotlin-coroutines,"['android', 'unit-testing', 'kotlin', 'kotlin-coroutines']",474,False,1,0
Testing crud operations using xunit in an asp.net web api core application,"<p>I am completely new to unit testing and will like to write unit test for my controller 
below using xunit and moq. I understand that you can only mock database transactions and 
make the unit test independent of the database.
How can I go about writing xunit tests for these? any documentation or sample code will be appreciated.
I know how to add the xnit test project to my solution.</p>

<pre><code>    using System;
    using System.Threading.Tasks;
    using CoreServices.Models;
    using CoreServices.Repository;
    using Microsoft.AspNetCore.Mvc;

    namespace CoreServices.Controllers
    {
        [Route(""api/[controller]"")]
        [ApiController]
        public class PostController : ControllerBase
        {
            IPostRepository postRepository;
            public PostController(IPostRepository _postRepository)
            {
                postRepository = _postRepository;
            }

            [HttpGet]
            [Route(""GetCategories"")]
            public async Task&lt;IActionResult&gt; GetCategories()
            {
                try
                {
                    var categories = await postRepository.GetCategories();
                    if (categories == null)
                    {
                        return NotFound();
                    }

                    return Ok(categories);
                }
                catch (Exception)
                {
                    return BadRequest();
                }

            }

            [HttpGet]
            [Route(""GetPosts"")]
            public async Task&lt;IActionResult&gt; GetPosts()
            {
                try
                {
                    var posts = await postRepository.GetPosts();
                    if (posts == null)
                    {
                        return NotFound();
                    }

                    return Ok(posts);
                }
                catch (Exception)
                {
                    return BadRequest();
                }
            }

            [HttpGet]
            [Route(""GetPost"")]
            public async Task&lt;IActionResult&gt; GetPost(int? postId)
            {
                if (postId == null)
                {
                    return BadRequest();
                }

                try
                {
                    var post = await postRepository.GetPost(postId);

                    if (post == null)
                    {
                        return NotFound();
                    }

                    return Ok(post);
                }
                catch (Exception)
                {
                    return BadRequest();
                }
            }

            [HttpPost]
            [Route(""AddPost"")]
            public async Task&lt;IActionResult&gt; AddPost([FromBody]Post model)
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        var postId = await postRepository.AddPost(model);
                        if (postId &gt; 0)
                        {
                            return Ok(postId);
                        }
                        else
                        {
                            return NotFound();
                        }
                    }
                    catch (Exception)
                    {

                        return BadRequest();
                    }

                }

                return BadRequest();
            }

            [HttpPost]
            [Route(""DeletePost"")]
            public async Task&lt;IActionResult&gt; DeletePost(int? postId)
            {
                int result = 0;

                if (postId == null)
                {
                    return BadRequest();
                }

                try
                {
                    result = await postRepository.DeletePost(postId);
                    if (result == 0)
                    {
                        return NotFound();
                    }
                    return Ok();
                }
                catch (Exception)
                {

                    return BadRequest();
                }
            }


            [HttpPost]
            [Route(""UpdatePost"")]
            public async Task&lt;IActionResult&gt; UpdatePost([FromBody]Post model)
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        await postRepository.UpdatePost(model);

                        return Ok();
                    }
                    catch (Exception ex)
                    {
                        if (ex.GetType().FullName == ""Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException"")
                        {
                            return NotFound();
                        }

                        return BadRequest();
                    }
                }

                return BadRequest();
            }

        }
    }
</code></pre>
",https://stackoverflow.com/questions/59472877/testing-crud-operations-using-xunit-in-an-asp-net-web-api-core-application,"['c#', 'asp.net-core-webapi', 'xunit.net']",4029,True,1,1
Angular Unit Test Video Resolution,"<p>I am checking the video resolution of a video file. The code is working well and now I am stuck at unit testing this function.</p>

<p>I tried spying on videoWidth &amp; videoHeight properties with no success. Instead I got error messages saying these properties do not exist. The problem that I found is that the HTMLVideoElement's videoWidth and videoHeight properties are read-only. How can I test it ? </p>

<p>TS </p>

<pre><code>videoResolutionTest(evt: KeyboardEvent) {
        const currentVideo = evt.target as HTMLVideoElement;

        if ((currentVideo.videoWidth &lt;= 720) &amp;&amp; (currentVideo.videoHeight &lt;=500 540)) {
            this.displayError('resolutionError', 2000);
        }
    }
</code></pre>

<p>HTML </p>

<pre><code>&lt;video (loadedmetadata)=""videoResolutionTest($event)""&gt;
&lt;source type=""video/mp4""&gt;
&lt;/video&gt;
</code></pre>
",https://stackoverflow.com/questions/55416150/angular-unit-test-video-resolution,"['angular', 'typescript', 'unit-testing', 'dom', 'jasmine']",384,False,1,1
Unit test: How to test if rails migrations being called?,"<p>I have a method that runs rails migrations. (Part of installation automation of a RAILS app). </p>

<p>I want to test whether this method calls the rails migrations. I don't want to check the results of running migrations because that would be testing rails migrations. Unit testing this method implies I want to check whether my method in turn called rails migration or not.</p>

<p>How to unit test this method in rspec?</p>

<pre><code>def run_migrations
  system('bin/rails db:migrate RAILS_ENV=development')
end
</code></pre>
",https://stackoverflow.com/questions/57265295/unit-test-how-to-test-if-rails-migrations-being-called,"['ruby-on-rails', 'ruby', 'rspec']",129,True,1,2
Aunit test returning blocked for given Sample Apama Projects,"<p>I am trying to use <a href=""https://github.com/antoinewaugh/aunit"" rel=""nofollow noreferrer"">AUnit</a> for Unit testing in apama. So I checked and read tha Aunit package uses Apama Pysys in the backend to test Apama application. </p>

<p>While I was successful in building the Aunit package , I am getting an error in testing the sample Apama monitors given with it. I am continuously getting the Warning: </p>

<pre><code>c:\aunit-master\bin&gt;aunit test Math

Copying C:\aunit-master\workspace\Math/src/Float.mon to C:\aunit-master\.__test\resources\Float.mon

2019-02-26 13:18:30,296 INFO  ==============================================================
2019-02-26 13:18:30,300 INFO  Id   : MathFloatTest
2019-02-26 13:18:30,302 INFO  Title: MathFloatTest
2019-02-26 13:18:30,304 INFO  ==============================================================
2019-02-26 13:18:33,068 WARN  caught &lt;class '_csv.Error'&gt; while running test: iterator should return strings, not bytes (did you open the file in text mode?)
Traceback (most recent call last):
  File ""C:\SoftwareAG2\Apama\third_party\python\Lib\site-packages\pysys\baserunner.py"", line 561, in __call__
    self.testObj.validate()
  File ""C:\aunit-master\.__test\MathFloatTest\run.py"", line 27, in validate
    for row in reader:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
2019-02-26 13:18:33,299 WARN  iterator should return strings, not bytes (did you open the file in text mode?) (&lt;class '_csv.Error'&gt;) ... blocked
2019-02-26 13:18:36,196 WARN  caught &lt;class '_csv.Error'&gt; while running test: iterator should return strings, not bytes (did you open the file in text mode?)
Traceback (most recent call last):
  File ""C:\SoftwareAG2\Apama\third_party\python\Lib\site-packages\pysys\baserunner.py"", line 561, in __call__
    self.testObj.validate()
  File ""C:\aunit-master\.__test\MathIntegerTest\run.py"", line 27, in validate
    for row in reader:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
2019-02-26 13:18:36,203 WARN  iterator should return strings, not bytes (did you open the file in text mode?) (&lt;class '_csv.Error'&gt;) ... blocked
2019-02-26 13:18:36,328 CRIT
2019-02-26 13:18:36,329 CRIT  Completed test run at:  Tuesday 2019-02-26 13:18:36 W. Europe Standard Time
2019-02-26 13:18:36,330 CRIT  Total test duration:    6.04 secs
2019-02-26 13:18:36,330 CRIT
2019-02-26 13:18:36,331 CRIT  Summary of non passes:
2019-02-26 13:18:36,331 CRIT    BLOCKED: MathFloatTest
2019-02-26 13:18:36,332 CRIT    BLOCKED: MathIntegerTest
</code></pre>

<p>And this warning gives the results of the testcase as BLOCKED.</p>
",https://stackoverflow.com/questions/54905259/aunit-test-returning-blocked-for-given-sample-apama-projects,"['apama', 'pysys', 'aunit']",67,True,1,3
NUnit check a call does not throw using fluent assertions,"<p>I developed an extension method with the signature <code>void ThrowIfAny&lt;T&gt;(this IEnumerable&lt;T&gt; e, Func&lt;T, bool&gt; f)</code> and I'm unit testing it. Logically, one of the tests is to check that does not throw. I know that I can write this assert like this:</p>

<pre><code>Assert.DoesNotThrow(() =&gt; anEnum.ThrowIfAny(t =&gt; false));
</code></pre>

<p>However, I'm using constraint based assertions  for the rest of my unit tests, and I'd like to know if this assert can be written using this style, maybe something like this (it doesn't compile):</p>

<pre><code>Assert.That(() =&gt; anEnum.ThrowIfAny(t =&gt; false), Does.Not.Throw);
</code></pre>
",https://stackoverflow.com/questions/58190966/nunit-check-a-call-does-not-throw-using-fluent-assertions,"['c#', 'unit-testing', 'nunit']",338,True,1,2
Pybind11 - Failing in Travis / Virtualenv,"<p>My Pybind project seems to be compiling fine on my system, but when I perform unit testing on travis, it throws the following error:</p>

<pre><code>-- Found PythonInterp: /opt/pyenv/shims/python3.7 (found version ""1.4"") 
CMake Error at 3rdparty/pybind11/tools/FindPythonLibsNew.cmake:95 (message):
  Python config failure:
  pyenv: python3.7: command not found

  The `python3.7' command exists in these Python versions:
    3.7
    3.7.1
</code></pre>

<p>This seems to be something to do with virtualenv which I have never used. I currently have no idea how to solve this issue, and given that its in a travis instance, i'm not sure how to recreate it on my system so I may fix it</p>
",https://stackoverflow.com/questions/54137798/pybind11-failing-in-travis-virtualenv,"['travis-ci', 'pyenv', 'pybind11']",795,False,1,2
Automated Unit Test on Healthkit permission,"<p>I am writing a <code>react-native</code> bridge for healthkit that includes the initialization of Healthkit. I also need to write an unit test for the modules. </p>

<p>I would like to use Travis to auto test on the project. Therefore, I need a automatic way that can press on the <code>Allow</code> button. Otherwise, the permission UI will block the unit testing process.</p>

<p>So, I need to know how automatically press on the allow button.</p>

<p><a href=""https://i.stack.imgur.com/ogblYm.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ogblYm.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/54192377/automated-unit-test-on-healthkit-permission,"['ios', 'objective-c', 'react-native', 'travis-ci']",330,False,1,2
How to test async calls so istanbul will cover it?,"<p>Im testing unit-testing my API. After i wrote all tests i implemented coverage tool <code>istanbul</code>. It covered everything without problems but branches. After looking at report i saw that async calls were not tested, but in reality they were run atleast 5 times. In this case <code>async</code> was run 15 times.</p>

<p>Small example of my test:</p>

<pre><code>describe('GET /tables', () =&gt; {
  it('should GET tables', (done) =&gt; {
    chai.request(server)
      .get('/api/v1/tables')
      .then((res) =&gt; {
        expect(res).to.have.status(200);
        expect(res.body).to.be.a('array');
        done();
      })
      .catch((err) =&gt; {
        done(err)
      })
  });
})
</code></pre>

<p>Part of coverage report for that test:</p>

<pre><code>export default async (req, res) =&gt; {
  let tables = [];
  try {
    tables = await Tables.findAndCountAll({
      where: {
        ...req.filter,
        material: null
      },
      // order: sort ? sort : [],
      limit: req.pagination.limit, 
      offset: req.pagination.offset
    });
  } catch (err) {
    console.log(err);
    return res.status(500).send({ error: 'Internal server error' });
  }
</code></pre>

<p>Line1: Marks <code>async (r</code> and says branch not covered</p>
",https://stackoverflow.com/questions/55625607/how-to-test-async-calls-so-istanbul-will-cover-it,"['javascript', 'unit-testing', 'mocha.js', 'istanbul', 'nyc']",1100,True,1,1
TestBed TypeError: Cannot read property &#39;navigate&#39; of undefined,"<p>I am trying to perform simple route unit test but </p>

<pre><code>TypeError: Cannot read property 'navigate' of undefined
</code></pre>

<p>is thrown. </p>

<p>I am following such tutorial </p>

<p><a href=""https://codecraft.tv/courses/angular/unit-testing/routing/"" rel=""nofollow noreferrer"">https://codecraft.tv/courses/angular/unit-testing/routing/</a></p>

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

<p>routes:</p>

<pre><code>export const routes: Routes = [
  {path: '', pathMatch: 'full', redirectTo: 'welcome'},
  {path: 'welcome', component: WelcomeComponent},
  {path: 'offer', loadChildren: () =&gt; import('./customer-dashboard/customer-dashboard.module').then(mod =&gt; mod.CustomerDashboardModule)},
  {path: 'underConstruction', component: UnderDevelopmentComponent}
];

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

<p>and unit test:</p>

<pre><code>fdescribe('AppRoutingModule', () =&gt; {

    let location: Location;
    let router: Router;
    let fixture;


    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [
                RouterTestingModule.withRoutes(routes),
                WelcomeModule
            ],
            declarations: [
                AppComponent,
            ],
            providers: [
                Location
            ]
        }).compileComponents()
            .then(() =&gt; {
                router = TestBed.get(Router);
                location = TestBed.get(Location);
                fixture = TestBed.createComponent(AppComponent);
                router.initialNavigation();
            })

    });

    it('should navigate from empty path to welcome', fakeAsync(() =&gt; {
        router.navigate(['']);
        tick();
        expect(location.path()).toBe('/welcome');
    }))

})
</code></pre>

<p>Nothing fancy here, this is just basic setup. Looks like TestBed cannot get implementation. Any ideas? 
To be honest I have the same implementation in my other simple project and it works fine there  but here.. </p>
",https://stackoverflow.com/questions/57818321/testbed-typeerror-cannot-read-property-navigate-of-undefined,"['angular', 'unit-testing', 'jasmine', 'karma-runner', 'testbed']",2831,True,1,1
cmake: correct way to find/add visual studio or windows sdk libraries and headers?,"<p>I'm using cmake to generate a Visual Studio project.</p>

<p>Let's say I need to use the following Microsoft-specific libraries and headers:</p>

<ul>
<li>Microsoft C++ Unit Testing Framework (example library location:  <code>c:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Auxiliary\VS\UnitTest\lib\x64\Microsoft.VisualStudio.TestTools.CppUnitTestFramework.lib</code>)</li>
<li>crtdbg for finding memory leaks (example header location:  <code>c:\Program Files (x86)\Windows Kits\10\Include\10.0.17763.0\ucrt\crtdbg.h</code>)</li>
</ul>

<p>I don't want to hardcode these paths into my CMakeLists.txt, or force a developer to pass in the paths during the build.</p>

<p>I expect to be able to do something like this:</p>

<pre><code># 1.  get include paths somehow
# 2.  get lib paths somehow

include_directories(
    ${MSVS_UnitTest_INCLUDE_DIR}
    ${Windows_SDK_INCLUDE_DIR}/ucrt
)

link_directories(
    ${MSVS_UnitTest_LIBRARIES_DIR}/x64
    ${Windows_SDK_LIBRARIES_DIR}/ucrt/x64
)

add_library(MyTest mytest.cpp)

target_link_libraries(MyTest
    libucrt
    Microsoft.VisualStudio.TestTools.CppUnitTestFramework
)
</code></pre>

<p>What's the right way to do #1 and #2?</p>
",https://stackoverflow.com/questions/57862199/cmake-correct-way-to-find-add-visual-studio-or-windows-sdk-libraries-and-header,"['c++', 'visual-studio', 'cmake']",1293,True,6,1
Jest not able to find file import,"<p><code>Jest</code> in my application is not able to find imported file and ends with this error:</p>

<blockquote>
  <p>FAIL  pages_test_files/index.spec.js<br>
    ● Test suite failed to run
      Cannot find module '../styles/sassTokenExports/colors.json' from 'index.js'
      However, Jest was able to find:<br>
          '../pages/index.js'
      You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'json', 'jsx', 'ts', 'tsx', 'node'].<br>
      See <a href=""https://jestjs.io/docs/en/configuration#modulefileextensions-array-string"" rel=""noreferrer"">https://jestjs.io/docs/en/configuration#modulefileextensions-array-string</a></p>
</blockquote>

<p>I am using <code>Jest</code> in <code>nextJS</code> for Unit testing.</p>
",https://stackoverflow.com/questions/59425547/jest-not-able-to-find-file-import,"['unit-testing', 'jestjs', 'enzyme', 'next.js', 'ts-jest']",9136,True,6,1
Request is not async,"<pre><code>public class RollingRequests
    {
        private const int DefaultNumSimultaneousRequests = 10;
        private readonly HttpClient _client; // Don't worry about disposing see https://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed
        private readonly HttpCompletionOption _httpCompletionOption;
        private readonly int _numSimultaneousRequests;

        public RollingRequests() : this(DefaultNumSimultaneousRequests)
        {
        }

        public RollingRequests(int windowSize) : this(new HttpClient(), windowSize)
        {
        }

        public RollingRequests(HttpClient client, int numSimultaneousRequests, HttpCompletionOption httpCompletionOption = HttpCompletionOption.ResponseContentRead)
        {
            _client = client;
            _numSimultaneousRequests = numSimultaneousRequests;
            _httpCompletionOption = httpCompletionOption;
        }

        public async Task ExecuteAsync(List&lt;string&gt; urls, CancellationToken cancellationToken, Action&lt;HttpResponseHeaders, string&gt; requestCallback = null)
        {
            var nextIndex = 0;
            var activeTasks = new List&lt;Task&lt;Tuple&lt;string, HttpResponseMessage&gt;&gt;&gt;();

            var startingIndex = Math.Min(_numSimultaneousRequests, urls.Count);
            for (nextIndex = 0; nextIndex &lt; startingIndex; nextIndex++)
            {
                activeTasks.Add(RequestUrlAsync(urls[nextIndex], cancellationToken));
            }

            while (activeTasks.Count &gt; 0)
            {
                var finishedTask = await Task.WhenAny(activeTasks).ConfigureAwait(false);
                activeTasks.Remove(finishedTask);

                var retryUrl = await ProcessTask(await finishedTask, requestCallback).ConfigureAwait(false);

                // If retrying, add the URL to the end of the queue
                if (retryUrl != null)
                {
                    urls.Add(retryUrl);
                }

                if (nextIndex &lt; urls.Count)
                {
                    activeTasks.Add(RequestUrlAsync(urls[nextIndex], cancellationToken));
                    nextIndex++;
                }
            }
        }

        private async Task&lt;string&gt; ProcessTask(Tuple&lt;string, HttpResponseMessage&gt; result, Action&lt;HttpResponseHeaders, string&gt; requestCallback = null)
        {
            var url = result.Item1;
            using (var response = result.Item2)
            {
                if (!response.IsSuccessStatusCode)
                {
                    return url;
                }

                if (requestCallback != null)
                {
                    string content = null;
                    if (_httpCompletionOption == HttpCompletionOption.ResponseContentRead)
                    {
                        content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }

                    requestCallback(response.Headers, content);
                }

                return null;
            }
        }

        private async Task&lt;Tuple&lt;string, HttpResponseMessage&gt;&gt; RequestUrlAsync(string url, CancellationToken ct)
        {
            var response = await _client.GetAsync(url, _httpCompletionOption, ct).ConfigureAwait(false);
            return new Tuple&lt;string, HttpResponseMessage&gt;(url, response);
        }
    }
</code></pre>

<p>This is a class that allows for X simultaneous requests to be on-going at once. When I am unit-testing this class and I moq the HttpClient giving each request a 1 second delay the initial <code>activeTasks.Add</code> is taking 5 seconds if I have 5 requests, suggesting to me that RequestUrlAsync isn't truly async.</p>

<p>Can anyone spot the issue?</p>

<p>Edit:
This is how I am sleeping the mocked client</p>

<pre><code>        _messageHandlerMock
                .Protected()
                .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;(MethodToMoq, ItExpr.IsAny&lt;HttpRequestMessage&gt;(), ItExpr.IsAny&lt;CancellationToken&gt;())
                .Callback(() =&gt; Thread.Sleep(1000))
                .ReturnsAsync(callback)
                .Verifiable();
</code></pre>
",https://stackoverflow.com/questions/56210710/request-is-not-async,"['c#', 'asynchronous', 'async-await']",169,True,-1,2
how to test component with fetch operation in reactJS,"<p>I have the following component</p>

<pre><code>import React, { Component } from 'react';

export class SomeComponent extends Component {
  constructor() {
    super();

    this.state = {
      firstName: '',
      lastName: '',
      isDone: false
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
  }

  public render() {
    return (
      &lt;div&gt;
        &lt;form onSubmit={this.handleSubmit}&gt;
          &lt;label&gt;
            firstName:
            &lt;input
              type=""text""
              name=""firstName""
              placeholder=""enter your first name""
              value={this.state.firstName}
              onChange={this.handleInputChange}
            /&gt;
          &lt;/label&gt;
          &lt;label&gt;
            lastName:
            &lt;input
              type=""text""
              name=""lastName""
              placeholder=""enter your last name""
              value={this.state.lastName}
              onChange={this.handleInputChange}
            /&gt;
          &lt;/label&gt;
          &lt;div&gt;
            &lt;input type=""submit"" value=""Submit"" /&gt;
          &lt;/div&gt;
        &lt;/form&gt;
      &lt;/div&gt;
    );
  }

  private handleInputChange(event) {
    const target = event.target;
    const name = target.name;
    const value = target.value;

    this.setState({ [name]: value });
  }

  private handleSubmit(event) {
    event.preventDefault();

    this.setState({ isDone: true });

    const nameMatch = () =&gt; {
      return !(this.state.firstName.match('^Cel.*') &amp;&amp; this.state.firstName.endsWith('on'));
    };

    if (nameMatch()) {
      alert('Please enter a valid name');
      return;
    }

    if (!this.state.lastName.endsWith('on')) {
      alert('check lastname too');
      return;
    }
    this.getFullName();
  }

  private getFullName() {


    const params = {
      firstName: this.state.firstName,
      lastName: this.state.lastName
    };

    const urlendPoint = `https://github.com/`;

    // (urlendPoint as any).search = new URLSearchParams(params);

    fetch(urlendPoint)
      .then(response =&gt; response.json())
      .then(data =&gt; data)
      .catch(error =&gt; {
        alert('Please check the names and try again');
      });

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

<p>as part of the unit testing, In react using Jest and enzyme, I have the following test case</p>

<pre><code>it('should fetch data correctly', (done) =&gt; {
            fetch.mockResponseOnce(JSON.stringify([]));
 let wrapper = shallow(&lt;SomeComponent /&gt;).instance();
  expect(wrapper.state.fullName).toEqual([]);
});
</code></pre>

<p>Here I'm trying to mock the fetch operation and test the getfullName() function that has been defined. </p>

<p>On doing this, I get the error <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.</code></p>

<p>I do not understand whats going wrong though. How should I mock the function such that I mock the fetch and test the function?  </p>
",https://stackoverflow.com/questions/58104258/how-to-test-component-with-fetch-operation-in-reactjs,"['javascript', 'reactjs', 'jestjs', 'enzyme']",52,False,0,0
How to mock a method of a third party package,"<p>I had a simple function which connects to mongoDB and create a new document. 
Now how do I mock the methods of the imported mongo package while unit testing. </p>

<p>Ive tried to mock GinContext by monkeypatching. </p>

<p>But unable to proceed with mocking the actual mongoClient as the package is imported.</p>

<pre class=""lang-golang prettyprint-override""><code>func CreateUser(c GinContext) {
    var userdetail UserDetails
    binderr := c.ShouldBindJSON(&amp;userdetail)
    fmt.Println(binderr)
    if binderr != nil {
        c.JSON(500, gin.H{
            ""message"": ""Input payload not matching"",
            ""error"":   binderr,
        })
        return
    }

    //-- Client if of type *mongo.Client. 

        //-- How do I mock the Client.Database, Client.Database.Connection

    collection := Client.Database(""demo"").Collection(""users"")
    ctx, err1 := context.WithTimeout(context.Background(), 10*time.Second)
    if err1 != nil {
    }
    response, err2 := collection.InsertOne(ctx, userdetail)
    if err2 != nil {
        log.Println(""Some error inserting the document"")
    }
    fmt.Println(response.InsertedID)
    c.JSON(200, gin.H{
        ""message"": ""User created successfully"",
    })
}
</code></pre>

<p>Expected: I should be able to mock or stub Client and provide dummy functionality. Just like in nodeJS we do </p>

<p>spyOn(Client,'Database').and.return(Something)</p>
",https://stackoverflow.com/questions/56391444/how-to-mock-a-method-of-a-third-party-package,"['unit-testing', 'go']",3946,True,3,1
TypeError: _reactNativeLanguages.default.addEventListener is not a function in Jest,"<p>I have completed my first react-native app. Now, I want to do unit testing and get code coverage for the whole application using <strong>jest</strong>. I have used npm packages like <strong><a href=""https://www.npmjs.com/package/i18n-js"" rel=""nofollow noreferrer"">i18n-js</a>, <a href=""https://www.npmjs.com/package/react-native-languages"" rel=""nofollow noreferrer"">react-native-languages</a></strong>.</p>

<p><strong>splash-test.js:</strong></p>

<pre><code>import React from 'react';
import Splash from '../Src/components/authentication/Splash';

import renderer from 'react-test-renderer';


test('renders correctly',()=&gt;{
const tree = renderer.create(
&lt;Splash /&gt;
).toJSON();
expect(tree).toMatchSnapshot();
})
</code></pre>

<p><strong>env.js:</strong></p>

<pre><code>jest.mock('react-native-languages', () =&gt; ({
RNLanguages: {
language: 'en',
languages: ['en'],
},
}));
</code></pre>

<p><strong>package.json:</strong></p>

<pre><code>
{
  ""name"": ""app-name"",
  ""version"": ""1.0.4"",
  ""private"": true,
  ""rnpm"": {
    ""assets"": [
      ""Src/assets/fonts/""
    ]
  },
  ""scripts"": {
    ""start"": ""node node_modules/react-native/local-cli/cli.js start"",
    ""test"": ""jest --coverage --coverageDirectory=output/coverage/jest""
  },
  ""dependencies"": {
    ""i18n-js"": ""^3.1.0"",
    ""react"": ""16.6.3"",
    ""react-native"": ""0.57.8"",
    ""react-native-fast-image-zoom-viewer"": ""^2.3.0"",
    ""react-native-firebase"": ""^5.1.1"",
    ""react-native-gifted-chat"": ""^0.7.2"",
    ""react-native-image-crop-picker"": ""^0.21.3"",
    ""react-native-image-zoom-viewer"": ""^2.2.25"",
    ""react-native-languages"": ""^3.0.1"",
    ""react-native-material-dropdown"": ""^0.11.1"",
    ""react-native-modal"": ""^7.0.2"",
    ""react-native-permissions"": ""^1.1.1"",
    ""react-native-progress"": ""^3.5.0"",
    ""react-native-restart"": ""0.0.9"",
    ""react-native-spinkit"": ""^1.1.1"",
    ""react-native-swiper"": ""^1.5.14"",
    ""react-native-view-toast"": ""0.0.1"",
    ""react-navigation"": ""^3.0.8"",
    ""react-redux"": ""^6.0.0"",
    ""realm"": ""^2.22.0"",
    ""redux"": ""^4.0.1"",
    ""redux-thunk"": ""^2.3.0"",
    ""rn-fetch-blob"": ""^0.10.15"",
    ""tipsi-stripe"": ""^7.1.0""
  },
  ""devDependencies"": {
    ""babel-jest"": ""^23.6.0"",
    ""jest"": ""^23.6.0"",
    ""jest-junit"": ""^6.2.1"",
    ""metro-react-native-babel-preset"": ""^0.51.0"",
    ""react-test-renderer"": ""^16.6.3""
  },
  ""jest"": {
    ""preset"": ""react-native"",
    ""transform"": {
      ""^.+\\.(js)$"": ""&lt;rootDir&gt;/node_modules/react-native/jest/preprocessor.js""
    },
    ""setupFiles"": [
      ""./test/env.js""
    ],
    ""coverageReporters"": [
      ""text""
    ],
    ""reporters"": [
      ""default"",
      ""jest-junit""
    ],
    ""collectCoverageFrom"": [
      ""Src/**/*.{js,jsx}"",
      ""!/node_modules/""
    ],
    ""transformIgnorePatterns"": [
      ""node_modules/(?!(react-native|react-native-languages)/)""
    ]
  },
  ""jest-junit"": {
    ""output"": ""output/coverage/junit/junit.xml"",
    ""usePathForSuiteName"": ""true""
  }
}

</code></pre>

<p>Now, If i give <strong>npm test</strong> it throws an error as i mentioned in <strong>title</strong>. Someone tell me how to bypass all the npm modules i have used in the app.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/54586498/typeerror-reactnativelanguages-default-addeventlistener-is-not-a-function-in-j,"['unit-testing', 'react-native', 'jestjs']",440,False,3,0
"VueJs TestUtil: In jest unit testing, html is not reactive when data is modified in mounted hook","<p>While jest unit testing for a component, if the component has mounted hook to update the data, after that the html is no longer reactive. It's stuck with the data before the modification by mounted hook.<br>
The <strong>testutil</strong> version is: <strong>1.0.0-beta.29</strong></p>

<p>component: count.ts</p>

<pre class=""lang-typescript prettyprint-override""><code>import { Component, Vue } from 'vue-property-decorator';

@Component({
  template: `
  &lt;div&gt;
    count:{{ count }}
    &lt;button @click=""increment""&gt;Increment&lt;/button&gt;
  &lt;/div&gt;
  `,
})
export default class Count extends Vue {
  count = 0;
  mounted() {
    // comment following line, everything works fine.
    this.count = 10;
  }

  increment() {
    this.count++;
  }
}

</code></pre>

<p>testing spec: count.spec.ts</p>

<pre class=""lang-typescript prettyprint-override""><code>import { mount } from '@vue/test-utils';
import Counter from './counter';

it('button click should increment the count', () =&gt; {
  const wrapper = mount(Counter);
  const button = wrapper.find('button');
  button.trigger('click');
  console.log(`wrapper.vm.count=${wrapper.vm.count}`);
  console.log(`html=${wrapper.html()}`);
});

</code></pre>

<p>If I comment out the line in <code>mounted()</code>, everything works fine.   Otherwise, the output will be </p>

<pre><code>wrapper.vm.count=11
html=&lt;div&gt;
  count:0
  &lt;button&gt;Increment&lt;/button&gt;&lt;/div&gt;
</code></pre>

<p>The html is supposed to print <code>count:11</code> instead of <code>count:0</code>.</p>
",https://stackoverflow.com/questions/58385255/vuejs-testutil-in-jest-unit-testing-html-is-not-reactive-when-data-is-modified,"['typescript', 'vue.js', 'jestjs']",327,False,0,0
Testing and verifying an Angular2+ build,"<p>I am having an Angular2+ application.</p>

<p>I have done some unit testing with Karma-Jasmine. But my assumption is that this is only for dev enviroment(pre production). </p>

<p>I am looking for a testing framework through which the ""dist"" folder build can be verified(components, web services, etc...)? so that once the build is taken, some script that do login, should able to verify the response object for login service etc...</p>
",https://stackoverflow.com/questions/57270251/testing-and-verifying-an-angular2-build,"['unit-testing', 'automation', 'angular6']",19,False,-1,1
flask.request mocker.patch.object does not take effect,"<p>In my controller I got this endpoint:</p>
<pre><code>@bp_crawler.route('/insert', methods=['POST'])
def insert_data():
    req = requests.CrawledSocialDataRequest.from_json(json.loads(request.data))
</code></pre>
<p>And then, I try to test this with <code>pytest</code> and <code>pytest-mock</code> for the <code>mocker</code> fixture.</p>
<p>I proceed to mock the <code>request</code> object so that the <code>request.data</code> returns some value that is useful for my unit testing.</p>
<pre><code># arrange
data_to_insert = requests.CrawledSocialDataRequest([
    requests.CrawledSocialDataRecord('cid0', 'content0', 123.4, ['tag0', 'tag1']),
    requests.CrawledSocialDataRecord('cid1', 'content1', 123.4, ['tag1', 'tag2'])
])
request_mock = mocker.patch.object(flask, 'request')
request_mock.data = data_to_insert.serialize()

db_mock = request_mock = mocker.patch.object(api, 'db')

# act
result = controller.insert_data()
</code></pre>
<p>Everything is fine, except when the <code>insert_data()</code> is called.</p>
<p>I get the following exception:</p>
<pre><code>    controllers/v1/tests/test_crawler.py:30: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    controllers/v1/crawler.py:36: in insert_data
        req = requests.CrawledSocialDataRequest.from_json(json.loads(request.data))
    /usr/local/lib/python3.7/site-packages/werkzeug/local.py:347: in __getattr__
        return getattr(self._get_current_object(), name)
    /usr/local/lib/python3.7/site-packages/werkzeug/local.py:306: in _get_current_object
        return self.__local()


name = 'request'

    def _lookup_req_object(name):
        top = _request_ctx_stack.top
        if top is None:
&gt;           raise RuntimeError(_request_ctx_err_msg)
E           RuntimeError: Working outside of request context.
E           
E           This typically means that you attempted to use functionality that needed
E           an active HTTP request.  Consult the documentation on testing for
E           information about how to avoid this problem.
</code></pre>
<p>The mock does not take place and thus the request.data routes control to the <code>flask.globals</code>, having my unit test to fail.</p>
<p>Github links:</p>
<ul>
<li><a href=""https://github.com/deepettas/algotrading-api/blob/master/controllers/v1/crawler.py"" rel=""nofollow noreferrer"">Controller</a></li>
<li><a href=""https://github.com/deepettas/algotrading-api/blob/master/controllers/v1/tests/test_crawler.py"" rel=""nofollow noreferrer"">Test</a></li>
</ul>
",https://stackoverflow.com/questions/57957456/flask-request-mocker-patch-object-does-not-take-effect,"['python', 'unit-testing', 'flask', 'mocking', 'pytest']",2332,True,3,2
403 No valid crumb was included in the request,"<p>I am running a Spring Boot Application and trying to test the application using ""spring-boot-starter-test"". While testing the web services I get a Response with status code 403 -  No valid crumb was included in the request. I am unable to figure out what is missing in the request. I am able to test the service through POSTMAN, however the same request details are failing during Unit Testing.</p>

<pre><code>2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &gt;&gt; ""POST /new-game 

HTTP/1.1[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &gt;&gt; ""Accept: */*[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &gt;&gt; ""Content-Type: application/json; charset=UTF-8[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &gt;&gt; ""Content-Length: 40[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &gt;&gt; ""Host: localhost:8080[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &gt;&gt; ""Connection: Keep-Alive[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &gt;&gt; ""User-Agent: Apache-HttpClient/4.5.7 (Java/1.8.0_144)[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &gt;&gt; ""Accept-Encoding: gzip,deflate[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &gt;&gt; ""[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &gt;&gt; POST /new-game HTTP/1.1
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &gt;&gt; Accept: */*
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &gt;&gt; Content-Type: application/json; charset=UTF-8
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &gt;&gt; Content-Length: 40
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &gt;&gt; Host: localhost:8080
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &gt;&gt; Connection: Keep-Alive
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &gt;&gt; User-Agent: Apache-HttpClient/4.5.7 (Java/1.8.0_144)
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &gt;&gt; Accept-Encoding: gzip,deflate
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &gt;&gt; ""{""firstMove"":true,""playerName"":""Adarsh""}""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &lt;&lt; ""HTTP/1.1 403 No valid crumb was included in the request[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &lt;&lt; ""Date: Sun, 31 Mar 2019 19:48:53 GMT[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &lt;&lt; ""X-Content-Type-Options: nosniff[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &lt;&lt; ""Cache-Control: must-revalidate,no-cache,no-store[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &lt;&lt; ""Content-Type: text/html;charset=iso-8859-1[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &lt;&lt; ""Content-Length: 389[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &lt;&lt; ""Server: Jetty(9.4.z-SNAPSHOT)[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG org.apache.http.wire -  &lt;&lt; ""[\r][\n]""
2019-03-31 14:48:53 [main] DEBUG o.a.h.i.conn.DefaultClientConnection - Receiving response: HTTP/1.1 403 No valid crumb was included in the request
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &lt;&lt; HTTP/1.1 403 No valid crumb was included in the request
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &lt;&lt; Date: Sun, 31 Mar 2019 19:48:53 GMT
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &lt;&lt; X-Content-Type-Options: nosniff
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &lt;&lt; Cache-Control: must-revalidate,no-cache,no-store
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &lt;&lt; Content-Type: text/html;charset=iso-8859-1
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &lt;&lt; Content-Length: 389
2019-03-31 14:48:53 [main] DEBUG org.apache.http.headers - &lt;&lt; Server: Jetty(9.4.z-SNAPSHOT)
</code></pre>
",https://stackoverflow.com/questions/55444862/403-no-valid-crumb-was-included-in-the-request,"['spring', 'spring-boot', 'http', 'apache-httpclient-4.x']",1301,False,0,1
Metod from the mocked bean is not working correctly,"<p>I want to create unit test for a method in service meaning I don't want to use <code>@RunWith(SpringRunner.class)</code> although it would have solved my problem.</p>

<p>This is what my program looks like:</p>

<pre class=""lang-java prettyprint-override""><code>    @Service
    public class MyService {
      private final SomeBean someBean;
      public MyService(SomeBean someBean) {
        this.someBean = someBean;
      }
      public boolean functionToTest() {
        boolean b = someBean.innerFunction();  // inside innerFunction() I return always true;
        return b;
        }
      }
    }

    public class SomeBean extends BaseBean {
      private String value;  // getter, setter
      public SomeBean(String value) {      //this value is always null in test
        super();
        this.value = value;
      }
      public boolean innerFunction() {
        return true;
      }
    }

    @Configuration
    public class SomeBeanConfiguration {
      @Bean
      public SomeBean getSomeBean(@Value(""${prop.value}"") String value) {
        return new SomeBean(value);  //can't get here while debugging test
      }
    }
</code></pre>

<p>And this is how I want to test <code>functionToTest()</code>:</p>

<pre class=""lang-java prettyprint-override""><code>    @RunWith(MockitoJUnitRunner.class)
    public class MyTest {

      @InjectMocks
      MyService service;

      @Mock
      SomeBean someBean;

      @Before
      public void setUp(){
        MockitoAnnotations.initMocks(this);    //although result is the same even without this set up
      }

      @Test
      public void test() {
        assertTrue(service.functionToTest());
      }
    }
</code></pre>

<p>The test always fails because <code>boolean b</code> is <code>false</code> by default and I can't get into innerFunction() with debugger.</p>

<p>Is there any way to mock beans for this kind of unit testing?</p>
",https://stackoverflow.com/questions/56913506/metod-from-the-mocked-bean-is-not-working-correctly,"['java', 'spring', 'unit-testing', 'mockito']",52,True,0,1
"Spark Arrow, toPandas() and wide transformation","<p>What does toPandas() actually do when using arrows optimization?</p>

<p>Is the resulting pandas dataframe safe for wide transformations (that requires data shuffling) on the pandas dataframe eg.<code>.merge</code> operations? what about group and aggregate? What kind of performance limitation should I expect?</p>

<p>I am trying to standardize to Pandas dataframe where possible, due to ease of unit testing and swapability with in-memory objects without starting the monstrous spark instance.</p>
",https://stackoverflow.com/questions/57714161/spark-arrow-topandas-and-wide-transformation,"['python', 'pandas', 'apache-spark', 'apache-arrow']",350,True,0,1
JUnit5 SpringBootTest NullPointerException when testing Service,"<p>I am following a tutorial for unit testing a Service, and I am attempting to use JUnit5 instead of JUnit4 (which is what the tutorial uses). The test works fine when I follow the tutorial exactly with JUnit4, but I get a NullPointerException with JUnit5.</p>

<p>The repository:</p>

<pre class=""lang-java prettyprint-override""><code>public interface CourseRepo extends CrudRepository&lt;Course, Long&gt; {}
</code></pre>

<p>The service:</p>

<pre class=""lang-java prettyprint-override""><code>@Service
public class CourseService {

    private final CourseRepo courseRepo;

    public CourseService(CourseRepo courseRepo) {
        this.courseRepo = courseRepo;
    }

    public Course save(Course course) {
        Course newCourse = courseRepo.save(course);
        return newCourse;
    }

}
</code></pre>

<p>The test:</p>

<pre class=""lang-java prettyprint-override""><code>package com.elovell.blackboard.service;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

import com.elovell.blackboard.domain.Course;
import com.elovell.blackboard.repository.CourseRepo;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;

@ExtendWith(MockitoExtension.class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
public class CourseServiceTest {

    @Mock
    public CourseRepo courseRepo;

    @InjectMocks
    public CourseService courseService;

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testSaveCourse() {

        Course mockCourse = new Course();
        mockCourse.setPk1(1L);
        mockCourse.setCourseId(""ENGL101"");

        when(courseRepo.save(any(Course.class))).thenReturn(mockCourse);
        // save(null) should still return mockCourse
        Course newCourse = courseService.save(null);
        assertEquals(""ENGL101"", newCourse.getCourseId());
    }
}

</code></pre>

<p>Here is the first few lines of the Exception:</p>

<pre><code>java.lang.NullPointerException
    at com.elovell.blackboard.service.CourseServiceTest.testSaveCourse(CourseServiceTest.java:44)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
</code></pre>

<p>The test and dependencies portion of my build file:</p>

<pre><code>test {
    useJUnitPlatform {
        includeEngines 'junit-jupiter'
    }
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    runtimeOnly 'com.h2database:h2'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation(""org.junit.jupiter:junit-jupiter-api:5.5.1"")
    testRuntimeOnly(""org.junit.jupiter:junit-jupiter-engine:5.1.0"")
    testCompile 'org.mockito:mockito-junit-jupiter:2.23.4'
}
</code></pre>
",https://stackoverflow.com/questions/57837993/junit5-springboottest-nullpointerexception-when-testing-service,"['junit5', 'spring-boot-test']",6203,True,0,1
unit test base controller with ILogger,"<p>I have a base controller (i didn't create it btw) in my net core api that basically starts with following:</p>

<pre><code>public abstract class MyBaseController&lt;T&gt; : ControllerBase where T : MyBaseController&lt;T&gt;
{        
    private ILogger&lt;T&gt; _logger;
    protected ILogger&lt;T&gt; Logger =&gt; _logger ?? (_logger = HttpContext?.RequestServices.GetService&lt;ILogger&lt;T&gt;&gt;());
}
</code></pre>

<p>When i am unit testing my other controller that inherits the base controller how do deal with this logger?</p>

<p>currently my unit test class has a constructer with something like</p>

<pre><code>_controller = new cartController(_cartService);
</code></pre>

<p>but then i get stuck.</p>

<p>I will be using xUnit and Moq in the test project.</p>

<p>Any help is appreciated.Thanks</p>
",https://stackoverflow.com/questions/54747916/unit-test-base-controller-with-ilogger,"['c#', 'unit-testing', 'asp.net-core']",583,True,0,2
NoClassDefFoundError on ActivityCompat while unittesting,"<p>I'm trying to use JUnit4, PowerMock for unit testing my Kotlin code in my Android Project and these not instrumentation test cases but plain JUnit test cases. When I run test case, I always error below. Can someone please help to resolve the error, Im not sure if Im missing some dependencies.</p>

<pre><code>java.lang.NoClassDefFoundError: android/support/v4/app/ActivityCompat
</code></pre>

<p>My Gradle depencies are :</p>

<p>build.gradle:</p>

<pre><code>deps.junit          = ""junit:junit:4.12""
deps.mockito        = ""org.mockito:mockito-core:2.7.22""
deps.android_mockito= ""org.mockito:mockito-android:2.7.22""
deps.powermock     = ""org.powermock:powermock-api-mockito2:2.0.0""
deps.powermock_junit = ""org.powermock:powermock-module-junit4:2.0.0""
</code></pre>

<p>app/build.gradle:</p>

<pre><code>androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
testImplementation deps.mockito
testImplementation deps.powermock_junit
androidTestImplementation deps.powermock
androidTestImplementation deps.powermock_junit
</code></pre>

<p>I have bunch of static methods so using PowerMock</p>
",https://stackoverflow.com/questions/55029612/noclassdeffounderror-on-activitycompat-while-unittesting,"['android', 'junit4']",52,False,0,1
Restassured Get response size in KB,"<p>When I do a rest call on postman I see a response size next to status in KB. Example : Size : 605 B</p>

<p>I need this information using rest assured for my unit testing. </p>

<p>Currently I have tried converting the response in byte and got its length however this gives the character count and not the Size of response in Bytes or KBs</p>

<p>Can anyone help how to achieve this</p>
",https://stackoverflow.com/questions/58786841/restassured-get-response-size-in-kb,"['java', 'rest', 'rest-assured']",1112,True,0,1
How to set a const value of a file from test file in node js unit testing,"<p>I am new to node js because of that facing some difficulties while doing unit testing of my code.
My issue is how to set a const value from testing file.
I have one class (ClassA) having two input param fileName and response, I am reading this file cell by cell and comparing its value in while loop.
I question is how to unit test this scenario.</p>

<p>Example :</p>

<p>ClassA.js </p>

<pre><code>function classAFunction(filename,res) { 
try {
        let workbook = XLSX.readFile(filename);
        let sheet_name = 'A';
        let worksheet = workbook.Sheets[sheet_name];
        let columnCount =1;
        let columnCountStartWithB = 'B'+columnCount;
        let valueOfColunBCell='';
        if(worksheet[columnCountStartWithB] != undefined ){
            valueOfColunBCell = worksheet[columnCountStartWithB].v; // how to set this value from test file
        } 

        while(true) {

          // some if else based of cell value 
          // increment value of columnCountStartWithB  B1, B2, B3....
         }

}catch (e){
        res.json({error_code:1,err_desc:""Corupted excel file""});
 }
}
</code></pre>

<p>ClassATest.js </p>

<pre><code>beforeEach(function() {

        mock({
            'fake-file-for-testing-only': 'file content'
          });

      });
 afterEach(mock.restore);

it('function Success Case', function(done) {
        let res = {
            status: sinon.spy(),
            json: sinon.spy()
          }

       //how to set valueOfColunBCell  value from this test file
        parsingUpload('fake-file-for-testing-only', res);

        done();
    });
</code></pre>
",https://stackoverflow.com/questions/59394873/how-to-set-a-const-value-of-a-file-from-test-file-in-node-js-unit-testing,"['node.js', 'unit-testing']",359,False,0,0
Unit testing on STM32,"<p>I am looking for advice on how to do unit testing on my STM32F7 platform. What have people done in the past? What horror stories do you have? What would you do differently? What is problematic with my current plan?</p>

<h2>My Setup</h2>

<ul>
<li>STM32 Nucleo-144 with a custom carrier PCB</li>
<li><code>arm-atollic-eabi-gcc</code> compiler (no C++, for now)</li>
<li>Using Atollic TrueStudio as an IDE</li>
<li>Development done from Ubuntu 16.04</li>
<li>Running FreeRTOS on the board</li>
</ul>

<h2>My Testing Plan</h2>

<p>There are different levels of testing; I am specifically talking about unit testing a library / set of functionality that does NOT depend on external hardware. Things like ""does my ring buffer implementation correctly handle rolling over without memory leaks"" and ""does this bit-shift operation result in the correct endianness in the resulting variable""? So I am focused on those kinds of tests.</p>

<ul>
<li>Convert my project to compile with C++ (and all the associated <code>extern C</code> required)</li>
<li>Refactor my code into a ""library"" portion and an ""application"" portion.</li>
<li>Build <code>googletest</code> (this is what we use for other parts of our system) and link my library into it for testing.</li>
<li>Run the unit tests on the device while running a debug session through Atollic.</li>
</ul>
",https://stackoverflow.com/questions/57415026/unit-testing-on-stm32,"['stm32', 'nucleo', 'stm32f7']",2522,True,4,1
Which unit test set up is correct? Are both tests checking if the function is right and working correctly?,"<p>I just started doing some unit testing for React JS - using Jest / enzyme.
I would like to know which test (format) is more useful and correct to use for future tests. These are 2 different tests that I'm working on it at the moment.</p>

<p><strong>Unit test 1 : I was writing most of my tests based on this set up</strong></p>

<pre><code>import React from 'react';
import Enzyme from 'enzyme';
import { shallow} from 'enzyme';
import EditWorkflow from './EditWorkflow';
import Adapter from 'enzyme-adapter-react-15';


//render must import shallow = method to show object structure
//Unit Test  V
Enzyme.configure({ adapter: new Adapter() })

 describe ('&lt;Workflow /&gt;', () =&gt; {
    it( 'renders 1 &lt;Workflow /&gt; Component', () =&gt; {
        const Component = shallow(&lt;EditWorkflow  name= ""workflow""/&gt;);
       expect(Component).toHaveLength(1);

    });
    describe('It renders props correctly', () =&gt; {
        const Component = shallow(&lt;EditWorkflow name= ""workflow""/&gt;);
        expect(Component.instance().props.name).toBe('workflow');
    })
});
</code></pre>

<p>**Unit test 2
Different way to write an unit test****</p>

<pre><code>import React from 'react';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
import { Login } from './App';
 import renderer from 'react-test-renderer';

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

let defaultProps = {
 getSessionContext: jest.fn(),
 checkSession: jest.fn(),
     }

let mockCheckSession;

describe('Login', () =&gt; {
 beforeEach(() =&gt; {
 mockCheckSession = jest.fn(()=&gt;{return true})
 defaultProps = {
 getSessionContext: jest.fn(),
 checkSession: mockCheckSession,
 }
  })

  it('should render ""authorizing..."" if theres no session ', () =&gt; {
   mockCheckSession = jest.fn(()=&gt;{return false})
   defaultProps.checkSession = mockCheckSession;

  const tree = renderer
  .create(&lt;Login {...defaultProps} /&gt;)
  .toJSON();

  expect(tree).toMatchSnapshot();
})
  it('should render null if there is a session ', () =&gt; {
  mockCheckSession = jest.fn(()=&gt;{return true})
  defaultProps.checkSession = mockCheckSession;    

  const tree = renderer
  .create(&lt;Login {...defaultProps}/&gt;)
  .toJSON();

 expect(tree).toMatchSnapshot();
 })
 })
</code></pre>
",https://stackoverflow.com/questions/54007442/which-unit-test-set-up-is-correct-are-both-tests-checking-if-the-function-is-ri,"['javascript', 'reactjs', 'unit-testing']",74,True,0,1
"Value does not fall within the expected range, when adding parameters, oracle","<p>When adding parameters to Oracle Stored Procedure in Unit Testing, i get error on adding RowId. I tried adding ToString() but then another error - ""ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'CultureInsert'"". I am not sure i am getting to the procedure. The error is in the DoInsert function.</p>

<pre><code>[TestMethod]
public void InsertTest()
{
    var culture = new Culture();
    var insertData = new CultureData();
    insertData.Name = ""insertedName5"";
    insertData.Code = ""en-HK"";
    insertData.Description = ""InsertDescription"";

    var data = culture.Insert(insertData);
}

________________________________________________________

public CultureData Insert(CultureData data)
{
    try
    {
        string oradb = ""Data Source=(DESCRIPTION ="" + ""(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))"" + ""(CONNECT_DATA ="" + ""(SERVER = DEDICATED)"" + ""(SERVICE_NAME = XE)));"" + ""User Id= ****;Password=****;"";

        OracleConnection conn = new OracleConnection(oradb); // C#
        conn.Open();

        using (var cmm = new OracleCommand(""CultureInsert"",conn))
        {

            cmm.CommandType = CommandType.StoredProcedure;

            if (data.Name != null &amp;&amp; data.Code != null &amp;&amp; data.Description != null)
            {
                DoInsert(cmm, data);
            }
            else
            {
                throw new System.Exception(string.Format(""Inserting record failed! Name, Code and Description must be entered!""));
            }

        }
        conn.Dispose();

    }
    catch (SqlException exception)
    {
        SqlExceptionHandler.Throw(exception);
    }

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

<p>This is the stored procedure:</p>

<pre><code>create or replace 
PROCEDURE           CultureInsert(
  v_Id              IN OUT NUMBER,
    v_Code            IN NVARCHAR2,
    v_Name            IN NVARCHAR2,
    v_Description     IN NVARCHAR2,
    v_Disabled        IN NUMBER DEFAULT 0,
    v_RowId           IN RAW,
    v_AuditUser       IN NVARCHAR2,
    v_AuditSessionId  IN RAW)
   as
   v_TransactionName  CHAR(32);
   v_TransCount  NUMBER(10,0);
   v_DisplayField  NVARCHAR2(24);
   SWV_TRANCOUNT NUMBER(10,0);
BEGIN

   v_TransactionName := 'CultureInsert';

   v_TransCount := 1  /*NOT SUPPORTED @@TRANCOUNT*/;

   IF (v_TransCount = 0) then
      SAVEPOINT v_TransactionName;
      SWV_TRANCOUNT := 0;
      SWV_TRANCOUNT := SWV_TRANCOUNT+1;
   ELSE
      NULL;
      -- SAVE TRANSACTION @TransactionName
end if;

   BEGIN 

INSERT INTO Core.Culture(Code,
            Name,
            Description,
            Disabled,
            RowId_)
        VALUES(v_Code,
            v_Name,
            v_Description,
            v_Disabled,
            v_RowId);

      select Core.Culture_Id.CURRVAL into v_Id from dual;
      Core.CultureAuditInsert(v_Id,v_AuditUser,'I',v_AuditSessionId);
      Core.CultureFetch(v_Id,v_AuditUser,v_AuditSessionId);
      v_DisplayField := Core.GetCultureDisplayFieldById(v_Id);
      Core.RecentWorkSave('Core','Culture',v_Id,v_DisplayField,v_AuditUser);
      IF v_TransCount = 0 then
         COMMIT;
         SWV_TRANCOUNT := SWV_TRANCOUNT -1;
      end if;
      EXCEPTION WHEN OTHERS THEN
         IF SWV_TRANCOUNT &gt; 0 then
            ROLLBACK;
            SWV_TRANCOUNT := 0;
         end if;
         --THROW;
   END;

END;
</code></pre>

<p>here is where i get an error:</p>

<pre><code>internal static CultureData DoInsert(OracleCommand cmm, CultureData data)
{
    cmm.Parameters.Add(CultureData.IdProperty, data.Id);
    cmm.Parameters.Add(CultureData.CodeProperty, data.Code);
    cmm.Parameters.Add(CultureData.NameProperty, data.Name);
    cmm.Parameters.Add(CultureData.DescriptionProperty, data.Description);
    cmm.Parameters.Add(CultureData.DisabledProperty, data.Disabled);
    cmm.Parameters.Add(CultureData.RowIdProperty, data.RowId); //here is the problem
    cmm.Parameters.Add(CultureData.AuditUserProperty, Csla.ApplicationContext.User.Identity.Name);
    cmm.Parameters.Add(CultureData.AuditSessionIdProperty, Csla.ApplicationContext.User.Identity.GetSessionId());
    using (OracleDataReader reader = cmm.ExecuteReader())
        return DoFetch(DataReaderHelper.GetReader(reader));
}
</code></pre>
",https://stackoverflow.com/questions/57825031/value-does-not-fall-within-the-expected-range-when-adding-parameters-oracle,"['c#', '.net', 'oracle']",277,False,0,1
"Unit Testing using mocha, node","<p>I'm new to unit testing in the Node world and am struggling with this: I've setup a after cb to delete the records I've added during my tests, however I keep getting an error <code>Error: done() called multiple times</code> every time I delete the record on the db. Here's my code:</p>

<pre><code>after((done) =&gt; {
    User.deleteOne({email: user_email}, function(err, result) {
        if(err) console.log(err);
        console.log(result);
        done();
    });
});
</code></pre>

<p>If I do anything else (like just console something within the <code>after</code> block, I get no error at all.</p>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/55614613/unit-testing-using-mocha-node,"['node.js', 'mocha.js']",29,True,0,1
How to mock on a translation I18n in jasmine karma?,"<p>So I try to do some unit testing on component level with Jasmine karma.</p>

<p>And I am using this translatioin class: I18n</p>

<p>And I have this component:</p>

<pre><code>constructor(
    private qrCodeService: QRCodeDefinitionService,
    private i18n: I18n,
    private blockerService: ScreenBlockerService,
    route: ActivatedRoute,
    private router: Router,
    private fb: FormBuilder
  ) {
    const data = route.snapshot.data;
    this.echeqFamilies = data['echeqFamilies'];
    this.resources = data['resources'];
    this.definition = data.definition;
    this.qrcodeUsedForUpdate = this.definition.qrcode;
    this.qrcodeWithBaseUrl =  this.getFullQrUrl();
  }
</code></pre>

<p>And this is the spec of it:</p>

<pre><code>describe('DefinitionComponent', () =&gt; {
  let component: DefinitionComponent;
  let fixture: ComponentFixture&lt;DefinitionComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        QRCodeDefinitionModule,
        HttpClientTestingModule,
        TranslateModule.forRoot({

        })
      ],
      providers:[]
    })
    .compileComponents();
  }));

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

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

</code></pre>

<p>But I get this error:</p>

<pre><code>Error: StaticInjectorError(DynamicTestModule)[DefinitionComponent -&gt; I18n]: 
  StaticInjectorError(Platform: core)[DefinitionComponent -&gt; I18n]: 
    NullInjectorError: No provider for I18n!
</code></pre>

<p>So how to fix this?</p>

<p>Thank you</p>

<p>The translation class with the I18 functionality:</p>

<pre><code>import { InjectionToken, MissingTranslationStrategy } from ""@angular/core"";
export interface I18n {
    (def: string | I18nDef, params?: {
        [key: string]: any;
    }): string;
}
export interface I18nDef {
    value: string;
    id?: string;
    meaning?: string;
    description?: string;
}
export declare const MISSING_TRANSLATION_STRATEGY: InjectionToken&lt;MissingTranslationStrategy&gt;;
/**
 * A speculative polyfill to use i18n code translations
 */
export declare class I18n {
    constructor(format: string, translations: string, locale: string, missingTranslationStrategy?: MissingTranslationStrategy);
}
</code></pre>

<p>The module where the component is declared:</p>

<pre><code>@NgModule({
  declarations: [ListComponent, DefinitionComponent],
  imports: [
    // Angular
    CommonModule,
    FlexLayoutModule,
    FormsModule,
    ReactiveFormsModule,

    // Angular Material
    DragDropModule,
    MatButtonModule,
    MatCardModule,
    MatCheckboxModule,
    MatDialogModule,
    MatExpansionModule,
    MatFormFieldModule,
    MatIconModule,
    MatInputModule,
    MatSortModule,
    MatPaginatorModule,
    MatSelectModule,
    MatSnackBarModule,
    MatTabsModule,
    MatTableModule,
    MatTreeModule,
    MatDatepickerModule,
    MatNativeDateModule,
    AuthModule,

    // Carapax
    QRCodeDefinitionRoutingModule,
    SharedModule,
  ],
  providers: [
    MatDatepickerModule,
  ]
})
export class QRCodeDefinitionModule { }

</code></pre>

<p>I have it like this:</p>

<pre><code>
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        QRCodeDefinitionModule,
        HttpClientTestingModule,
        TranslateModule.forRoot()
      ],
      providers:[]
    })
    .compileComponents();
  }));
</code></pre>

<p>But still get this error:</p>

<pre><code>Error: StaticInjectorError(DynamicTestModule)[DefinitionComponent -&gt; I18n]: 
  StaticInjectorError(Platform: core)[DefinitionComponent -&gt; I18n]: 
    NullInjectorError: No provider for I18n!
</code></pre>
",https://stackoverflow.com/questions/58817710/how-to-mock-on-a-translation-i18n-in-jasmine-karma,"['javascript', 'angular', 'unit-testing', 'karma-jasmine', 'angular-i18n']",1817,False,0,1
Junit test not passing. New to unit testing services,"<p>Writing a unit test for my Spring Boot service method and I cannot get it to pass. I am a front end developer so I am not very familiar with unit testing in Java. The multipartFile is what is confusing me the most, as well as completing the entire Junit test.</p>

<p>Junit4 with mockito unit test. Tried stackoverflow and google for potential corrections. </p>

<p>Contract Service</p>

<pre><code>@Slf4j
@Service
public class ContractService {

    @Autowired
    public ContractRepository contractRepository;

    @Autowired
    public JdbcTemplate jdbcTemplate;

    @Autowired
    public UserSettingsService userSettingsService;

    @Autowired
    public ContractPermissionsService contractPermissionsService;

    @Autowired
    public OCRSubmissionService ocrSubmissionService;

    @Autowired
    public ContractDocumentStorageService contractDocumentStorageService;

    public Contract getContract(int contractID) {
       Contract contract = contractRepository.getOne(contractID);
       return contract;
    }

    //TODO: come back and reduce contractID / metaID to one ID.
    //TODO: add trigger in DB layer for coterminous
    // TODO: make sure isVisible defaults to false

    /*
    When adding a new contract, the following steps are taken:
    1. SQL transaction is begun
    2. The meta information is stored, and an ID is generated in SQL.
    3. The file is stored with the corresponding document ID.
    4. The meta information is updated with the document link.
    5. A login, submission, and logoff are made to KTA.
    6. As long as all these steps have completed, the transaction is completed
    7. Otherwise, the transaction is cancelled ad an error is thrown (controller returns 500)
     */
    @Transactional(rollbackFor=Exception.class)
    public Contract addNewContract(Contract contract, MultipartFile file) throws Exception {
        Contract newContract = this.contractRepository.save(contract);
        int ID = contract.getId();
        int fileID = this.contractDocumentStorageService.storeFile(file, ID);
        contract.setDocumentPathDesc(Integer.toString(fileID));
        this.addViewingPermissionsForSubmitter(contract);
        Boolean success = this.ocrSubmissionService.SubmitContractForOCR(file, contract.getId());
        if(success) {
            return this.contractRepository.saveAndFlush(newContract);
        } else {
            throw new OCRSubmissionFailureException(""Error in OCR Submission"");
        }
    }
</code></pre>

<p>Contract Service Test</p>

<pre><code>public class ContractServiceTest {

    ContractService contractServiceUnderTest;


    @Before
    public void setUp() {
        contractServiceUnderTest = new ContractService();
        contractServiceUnderTest.contractRepository = mock(ContractRepository.class);
        contractServiceUnderTest.jdbcTemplate = mock(JdbcTemplate.class);
        contractServiceUnderTest.userSettingsService = mock(UserSettingsService.class);
        contractServiceUnderTest.contractPermissionsService = mock(ContractPermissionsService.class);
        contractServiceUnderTest.ocrSubmissionService = mock(OCRSubmissionService.class);
        contractServiceUnderTest.contractDocumentStorageService = mock(ContractDocumentStorageService.class);
    }

    @Test
    public void testAddNewContract() throws Exception {
        // Setup
        final Contract contract = new Contract();
        final MultipartFile file = null;
        final Contract expectedResult = null;

        // Run the test
        final Contract result = contractServiceUnderTest.addNewContract(contract, file);

        // Verify the results
        assertEquals(expectedResult, result);
    }
</code></pre>
",https://stackoverflow.com/questions/55497835/junit-test-not-passing-new-to-unit-testing-services,"['java', 'junit', 'mockito']",185,False,0,0
Mocking a Context.ConnectionId for Unit Testing Signalr .NetCore Messaging Hubs,"<p>My question is regarding getting a context.connection ID value to insert into one of my methods when i'm unit testing my Signalr hubs in .Net CORE. My method looks like this in my test class:</p>
<pre class=""lang-cs prettyprint-override""><code>
    [Fact]
    public async Task TestWorkstationCreation()
    {
        Mock&lt;IHubCallerClients&lt;IWorkstation&gt;&gt; mockClients = new Mock&lt;IHubCallerClients&lt;IWorkstation&gt;&gt;();
        Mock&lt;IWorkstation&gt; mockClientProxy = new Mock&lt;IWorkstation&gt;();
        mockClients.Setup(clients =&gt; clients.All).Returns(mockClientProxy.Object);
        _workstationHub.Clients = mockClients.Object;
        await _workstationHub.RegisterWorkstation(&quot;WKS16&quot;, &quot;Ready&quot;, new Dictionary&lt;string, string&gt; {{&quot;OS&quot;, &quot;Windows 10&quot;}, {&quot;Exam&quot;, &quot;GRE, TOEFL&quot;}});
        mockClientProxy.Verify(c =&gt; c.WorkstationRegistered(It.IsAny&lt;WorkstationDataModel&gt;(), It.IsAny&lt;string&gt;()), Times.AtLeastOnce);
    }
</code></pre>
<p>In my hub class, this is the method:</p>
<pre class=""lang-cs prettyprint-override""><code>    public async Task RegisterWorkstation(string id, string status, Dictionary&lt;string, string&gt; capabilities)
    {
        _logger.LogInformation(
            &quot;Registering a Workstation with id: {id}, status: {status}, and capabilities: {capabilities}&quot;,
            id, status, string.Join(&quot;,&quot;, capabilities));
        var workstationAdded = AddWorkstation(id, status, capabilities, Context.ConnectionId);
        var message = workstationAdded == null
            ? $&quot;A workstation with the id: {id} already exists!&quot;
            : $&quot;A workstation with the id: {id}, status: {status}, and capabilities: {string.Join(&quot;,&quot;, capabilities)} &quot; +
              &quot;was added to the current list of workstations available.&quot;;
        await Clients.All.WorkstationRegistered(workstationAdded, message);
    }
</code></pre>
<p>When testing, it throws an Object reference not set null pointer exception at Context.ConnectionId. Is there someway to mock a Context.Connection Id that can be used?</p>
",https://stackoverflow.com/questions/56871939/mocking-a-context-connectionid-for-unit-testing-signalr-netcore-messaging-hubs,"['asp.net-core', '.net-core', 'signalr', 'xunit', 'asp.net-core-signalr']",2004,True,0,1
JUnit5 comparing two ArrayLists results in No tests Found with test runner,"<p>Good Evening! Can somebody explain to me why am I getting this message? : <strong>No tests found with test runner 'JUnit5'</strong></p>

<p>@Test is at the end of the RestaurantMenuTest.class</p>

<p>Here is the test class:</p>

<pre><code>@ExtendWith(MenuEngineParameterResolver.class)
@DisplayName(""Test of Restaurant Menu"")
class RestaurantMenuTest {

ListOfPurchasedDishes listOfPurchasedDishes = new ListOfPurchasedDishes();

@Test
@DisplayName(""test name"")
void creatingListArrayWithPurchasedItems() {

    //here I create items the customer wants to purchase
    MenuItem item1 = new MenuItem(""PL01"", ""Pierogi ruskie z cebulką"", 28);
    MenuItem item2 = new MenuItem(""PL01"", ""Pierogi ruskie z cebulką"", 28);
    MenuItem item3 = new MenuItem(""DPL02"", ""Naleśniki z czekoladą"", 12);
    MenuItem item4 = new MenuItem(""DPL02"", ""Naleśniki z czekoladą"", 12);
    MenuItem item5 = new MenuItem(""AC01"", ""Czerwone wino wytrawne"", 18);
    MenuItem item6 = new MenuItem(""AC02"", ""Czerwone wino półwytrawne"", 18);
    MenuItem item7 = new MenuItem(""NAC01"", ""Woda"", 10);
    MenuItem item8 = new MenuItem(""NAC01"", ""Woda"", 10);
    MenuItem item9 = new MenuItem(""NAC06"", ""Cytryna"", 0);
    MenuItem item10 = new MenuItem(""NAC07"", ""Lód"", 0);
    MenuItem item11 = new MenuItem(""NAC06"", ""Cytryna"", 0);
    MenuItem item12 = new MenuItem(""NAC07"", ""Lód"", 0);

    //here I create an exemplary list I would like to get as an output
    List&lt;MenuItem&gt; expectedListOfPurchasedItems = new ArrayList&lt;&gt;();
    expectedListOfPurchasedItems.add(item1);
    expectedListOfPurchasedItems.add(item2);
    expectedListOfPurchasedItems.add(item3);
    expectedListOfPurchasedItems.add(item4);
    expectedListOfPurchasedItems.add(item5);
    expectedListOfPurchasedItems.add(item6);
    expectedListOfPurchasedItems.add(item7);
    expectedListOfPurchasedItems.add(item8);
    expectedListOfPurchasedItems.add(item9);
    expectedListOfPurchasedItems.add(item10);
    expectedListOfPurchasedItems.add(item11);
    expectedListOfPurchasedItems.add(item12);

    //here is the method of the program, the method is shown below in ListOfPurchasedDishes.class
    listOfPurchasedDishes.purchaseDish(item1);
    listOfPurchasedDishes.purchaseDish(item2);
    listOfPurchasedDishes.purchaseDish(item3);
    listOfPurchasedDishes.purchaseDish(item4);
    listOfPurchasedDishes.purchaseDish(item5);
    listOfPurchasedDishes.purchaseDish(item6);
    listOfPurchasedDishes.purchaseDish(item7);
    listOfPurchasedDishes.purchaseDish(item8);
    listOfPurchasedDishes.purchaseDish(item9);
    listOfPurchasedDishes.purchaseDish(item10);
    listOfPurchasedDishes.purchaseDish(item11);
    listOfPurchasedDishes.purchaseDish(item12);

    ArrayList&lt;MenuItem&gt; purchasedItems = listOfPurchasedDishes.listOfPurchasedItems();

    //neither this
    assertEquals(expectedListOfPurchasedItems, purchasedItems);
    //nor this works
    Assert.assertArrayEquals(expectedListOfPurchasedItems.toArray(), purchasedItems.toArray());


}//end of void creatingListArrayWithPurchasedItems
}//end of class RestaurantMenuTest
</code></pre>

<p>Here MenuItem has 3 fields:</p>

<pre><code>private String id;
private String name;
private double price;

public MenuItem(String id, String name, double price) {
    this.id = id;
    this.name = name;
    this.price = price;
}
</code></pre>

<p>And ListOfPurchasedDishes.class looks like this</p>

<pre><code>public class ListOfPurchasedDishes {

private ArrayList&lt;MenuItem&gt; purchasedItems = new ArrayList&lt;&gt;();

public ListOfPurchasedDishes() {}

public void purchaseDish(MenuItem menuItem) {
    purchasedItems.add(menuItem);
}//end of public void purchaseDish()

public ArrayList&lt;MenuItem&gt; listOfPurchasedItems() {
    return this.purchasedItems;
}//end of public ArrayList&lt;MenuItem&gt; listOfPurchasedItems()
}//end of public class ListOfPurchasedDishes
</code></pre>

<p>I am new to Unit Testing, and I have no clue what am I doing wrong in this example. Can someone point me into the right direction? Thanks!</p>
",https://stackoverflow.com/questions/59237520/junit5-comparing-two-arraylists-results-in-no-tests-found-with-test-runner,"['java', 'junit5']",29,False,0,0
Getting NotAMockException on Calendar.getInstance() mocking,"<p>I am trying to mock <code>Calendar.getInstance()</code> for unit testing purpose. </p>

<p>I am thus using PowerMock (<code>powermock-core:2.0.4</code> &amp; <code>powermock-module-junit4:2.0.4</code>) and its Mockito API (<code>powermock-api-mockito2:2.0.4</code>).</p>

<p>I am well aware that similar cases <a href=""https://stackoverflow.com/questions/9275840/java-how-to-mock-calendar-getinstance"">do</a> <a href=""https://stackoverflow.com/questions/38148077/mockito-mock-and-change-calendar-getistance?noredirect=1&amp;lq=1"">exist</a>, but I am facing an exception that does not seem to appear on other's case.</p>

<p>Indeed, when doing </p>

<pre class=""lang-java prettyprint-override""><code>mockStatic(Calendar.class);
when(Calendar.getInstance()).thenReturn(aCalendar);
</code></pre>

<p>on a test method within a class annotated  with </p>

<pre class=""lang-java prettyprint-override""><code>@RunWith(PowerMockRunner.class)
@PrepareForTest({DateUtils.class})
</code></pre>

<p>I get the following error : <code>org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class java.lang.Class</code>.</p>

<p>What did I do wrong and how to solve it ?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/58749932/getting-notamockexception-on-calendar-getinstance-mocking,"['java', 'android', 'unit-testing', 'powermockito']",233,False,0,1
How to have different Teamcity VSBuild Configurations (Debug/Release) for each specific branch?,"<p>I have a build configuration that does my building and unit testing for all of my branches of my project. I have another configuration that does my deploying. I need the first configuration to do the build with a ""Debug"" target if its against a ""development"" environment and a ""Release"" target against the rest. Is there a way to go about this without having to make different build configurations?</p>
",https://stackoverflow.com/questions/54794175/how-to-have-different-teamcity-vsbuild-configurations-debug-release-for-each-s,"['msbuild', 'teamcity', 'msdeploy']",59,False,0,1
java.lang.AssertionError: Server is sending a non-null replay context but our replayModes=[],"<p>When I try to connect to the oracle database from a separate main class,</p>

<pre><code> try {
            Connection connection = DriverManager.getConnection(""jdbc:oracle:thin:@host:port/service"", ""username"", ""pwd"");
</code></pre>

<p>I am able to connect but when I use the same connection inside a test ng or junit test, am getting the following error : </p>

<pre><code>java.lang.AssertionError: Server is sending a non-null replay context but our replayModes=[]
</code></pre>

<p>Could someone please help me to understand what is happening !</p>

<p>Just tried the answers from this link and it dint work for me :
<a href=""https://stackoverflow.com/questions/53383705/why-does-my-oracle-datasource-have-a-replay-error-only-when-unit-testing"">Why does my Oracle DataSource have a replay error only when unit testing?</a></p>
",https://stackoverflow.com/questions/57404758/java-lang-assertionerror-server-is-sending-a-non-null-replay-context-but-our-re,"['java', 'sql', 'oracle', 'junit']",2379,True,2,1
Unit testing FTP in Java (JSch &amp; MockFtpServer),"<p>I'm using JCraft's JSch library for as a FTP client for my program, it's working fine. But I had difficulties creating a mock (MockFtpServer) for unit testing. </p>

<pre><code>import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.mockftpserver.fake.FakeFtpServer;
import org.mockftpserver.fake.UserAccount;
import org.mockftpserver.fake.filesystem.FileEntry;
import org.mockftpserver.fake.filesystem.FileSystem;
import org.mockftpserver.fake.filesystem.UnixFakeFileSystem;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Properties;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SFTPManagerTest {

static FakeFtpServer fakeFtpServer;

@BeforeClass
public static void startFTP() throws Exception {
    fakeFtpServer = new FakeFtpServer();
    fakeFtpServer.setServerControlPort(9999);

    FileSystem fileSystem = new UnixFakeFileSystem();
    fileSystem.add(new FileEntry(""/data/JFS_HCID_APPLICATION_STATUS_20190109.TXT"", ""&lt;schema/&gt;""));
    fakeFtpServer.setFileSystem(fileSystem);

    UserAccount userAccount = new UserAccount(""user"", ""password"", ""/"");
    fakeFtpServer.addUserAccount(userAccount);
    fakeFtpServer.start();
}

@Test
public void getFileListing() {

    try {
        JSch jsch = new JSch();
        Session jschSession = jsch.getSession(""user"", ""localhost"", 9999);
        jschSession.setPassword(""password"");

        Properties config = new Properties();
        config.put(""StrictHostKeyChecking"", ""no"");
        jschSession.setConfig(config);
        jschSession.connect();

        Channel jschChannel = jschSession.openChannel(""ftp"");
        jschChannel.connect();
        ChannelSftp channel = (ChannelSftp) jschChannel;
        Vector v = channel.ls(""/data"");
        Assert.assertNotNull(v);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

@AfterClass
public static void stopFTP() {
    fakeFtpServer.stop();
}
}
</code></pre>

<p>Dependencies:</p>

<ul>
<li>com.jcraft:jsch:0.1.55</li>
<li>org.mockftpserver:MockFtpServer:2.7.1</li>
</ul>

<p>Output: it always stuck/stall during executing test method, not finishing. When stuck/stalling I could access the MockFtpServer with WinSCP or FTP CLI. From the log it seems the command from JSch not recognized.</p>

<pre class=""lang-none prettyprint-override""><code>2019-02-18 17:54:15,996 INFO  [Thread-0] org.mockftpserver.core.server.AbstractFtpServer: Connection accepted from host /127.0.0.1
2019-02-18 17:54:16,002 INFO  [Thread-6] org.mockftpserver.core.command.AbstractTrackingCommandHandler: Sending reply [220 Service ready for new user. (MockFtpServer 2.7.1; see http://mockftpserver.sourceforge.net)]
2019-02-18 17:54:16,004 INFO  [Thread-6] org.mockftpserver.core.session.DefaultSession: Received command: [SSH-2.0-JSCH-0.1.54]
2019-02-18 17:54:16,004 WARN  [Thread-6] org.mockftpserver.core.command.UnsupportedCommandHandler: No CommandHandler is defined for command [SSH-2.0-JSCH-0.1.54]
2019-02-18 17:54:16,005 INFO  [Thread-6] org.mockftpserver.core.command.AbstractTrackingCommandHandler: Sending reply [502 Command not implemented: SSH-2.0-JSCH-0.1.54.]
</code></pre>

<p>Where did i go wrong?</p>
",https://stackoverflow.com/questions/54746688/unit-testing-ftp-in-java-jsch-mockftpserver,"['java', 'ftp', 'mocking', 'jsch']",3162,True,2,1
TypeError: Cannot read property &#39;viewManagersNames&#39; of undefined - Integrating Jest and Enzyme with React Native TypeScript Package,"<p>I'm trying to integrate Jest unit testing with Enzyme on my React-Native Typescript package, but after reading docs and tutorials, I can't seem to make it work.<br/><br/>
<strong>The problem only happens</strong> when using <code>LinearGradient</code> from <code>expo-linear-gradient</code>.<br/>
After having configured the file settings (see below), running <code>npm test</code> throws the error :<br/><br/> </p>

<pre><code>TypeError: Cannot read property 'viewManagersNames' of undefined at 
requireNativeViewManager (node_modules/@unimodules/react-native- 
adapter/src/NativeViewManagerAdapter.tsx:26:10) at Object.&lt;anonymous&gt; 
(node_modules/expo-linear-gradient/src/NativeLinearGradient.ios.tsx:20:59) 
at Object.&lt;anonymous&gt; (node_modules/expo-linear- 
gradient/src/LinearGradient.tsx:5:34).
</code></pre>

<p>I have tried to link the @unimodules/react-native-adapter as it seems that it's what's causing the issue, but I then get the error : <br/></p>

<pre><code>SyntaxError: Unexpected token {

  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
  at Object.&lt;anonymous&gt; (node_modules/@unimodules/core/src/AdapterProxy.ts:1:50)
</code></pre>

<p><strong>package.json</strong> : </p>

<pre><code>{
   ...
  ""scripts"": {
    ""build"": ""tsc"",
    ""format"": ""prettier --write \""src/**/*.ts\"" \""src/**/*.js\"""",
    ""lint"": ""tslint -p tsconfig.json"",
    ""test"": ""jest --config jest.config.json --detectOpenHandles"",
    ""prepare"": ""npm run build"",
    ""prepublishOnly"": ""npm test &amp;&amp; npm run lint"",
    ""preversion"": ""npm run lint"",
    ""version"": ""npm run format &amp;&amp; git add -A src"",
    ""postversion"": ""git push &amp;&amp; git push --tags""
  },
  ""devDependencies"": {
    ""@babel/plugin-proposal-class-properties"": ""^7.5.5"",
    ""@babel/plugin-proposal-nullish-coalescing-operator"": ""^7.4.4"",
    ""@babel/preset-env"": ""^7.6.3"",
    ""@babel/preset-flow"": ""^7.0.0"",
    ""@babel/preset-react"": ""^7.6.3"",
    ""@types/enzyme"": ""^3.10.3"",
    ""@types/enzyme-adapter-react-16"": ""^1.0.5"",
    ""@types/jest"": ""^24.0.18"",
    ""@types/react"": ""^16.9.5"",
    ""@types/react-native"": ""^0.60.19"",
    ""@types/react-test-renderer"": ""^16.9.0"",
    ""@unimodules/core"": ""^4.0.0"",
    ""@unimodules/react-native-adapter"": ""^4.0.0"",
    ""babel-jest"": ""^24.9.0"",
    ""babel-plugin-transform-export-extensions"": ""^6.22.0"",
    ""enzyme"": ""^3.10.0"",
    ""enzyme-adapter-react-16"": ""^1.15.0"",
    ""enzyme-to-json"": ""^3.4.2"",
    ""install"": ""^0.13.0"",
    ""jest"": ""^24.9.0"",
    ""jest-expo"": ""^35.0.0"",
    ""metro-react-native-babel-preset"": ""^0.55.0"",
    ""npm"": ""^6.12.0"",
    ""prettier"": ""^1.18.2"",
    ""react"": ""16.10.2"",
    ""react-dom"": ""16.10.2"",
    ""react-native"": ""0.61.2"",
    ""react-native-renderer"": ""^15.5.3"",
    ""react-test-renderer"": ""^16.10.2"",
    ""ts-jest"": ""^24.1.0"",
    ""tslint"": ""^5.20.0"",
    ""tslint-config-prettier"": ""^1.18.0"",
    ""typescript"": ""^3.6.3""
  },
  ""dependencies"": {
    ""@babel/plugin-proposal-optional-chaining"": ""^7.6.0"",
    ""expo-linear-gradient"": ""^7.0.1"",
    ""lodash"": ""^4.17.14""
  },
  ""peerDependencies"": {
    ""react"": ""*"",
    ""react-dom"": ""*"",
    ""react-native"": ""*""
  }
}
</code></pre>

<p><strong>jest.config.json</strong>: </p>

<pre><code>{
  ""preset"": ""react-native"",
  ""transform"": {
    ""^.+\\.js$"": ""&lt;rootDir&gt;/node_modules/react-native/jest/preprocessor.js"",
    ""\\.(ts|tsx)$"": ""ts-jest""
  },
  ""setupFiles"": [""./src/setupTests.js""],
  ""globals"": {
    ""ts-jest"": {
      ""tsConfig"": ""tsconfig.jest.json""
    }
  },
  ""transformIgnorePatterns"": [
    ""node_modules/(?!(react-native|react-native-skeleton-content|expo-linear-gradient|@unimodules/core)/)""
  ],
  ""moduleFileExtensions"": [""ts"", ""tsx"", ""js""],
  ""testRegex"": ""(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$""
}
</code></pre>

<p><strong>babel.config.js</strong>: </p>

<pre><code>module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-flow'],
  plugins: [
    '@babel/plugin-proposal-class-properties',
    '@babel/plugin-proposal-nullish-coalescing-operator',
    '@babel/plugin-proposal-optional-chaining',
  ],
};
</code></pre>

<p><strong>setupTests.js</strong>: </p>

<pre><code>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });
</code></pre>

<p><strong>tsconfig.jest.json</strong>: </p>

<pre><code>{
  ""extends"": ""./tsconfig"",
  ""compilerOptions"": {
    ""jsx"": ""react"",
    ""module"": ""commonjs""
  }
}
</code></pre>

<p><strong>tsconfig.json</strong>: </p>

<pre><code>{
  ""compilerOptions"": {
    ""target"": ""es5"",
    ""module"": ""commonjs"",
    ""jsx"": ""react-native"",
    ""noEmit"": true,
    ""strict"": true,
    ""moduleResolution"": ""node"",
    ""baseUrl"": ""./"",
    ""allowSyntheticDefaultImports"": true,
    ""esModuleInterop"": true,
    ""exclude"": [""node_modules""]
  }
}

</code></pre>

<p><strong>SkeletonContent.test.tsx</strong>: </p>

<pre><code>import React from 'react';
import { SkeletonContent } from '../SkeletonContent';
import { shallow } from 'enzyme';

describe('SKC', () =&gt; {
  const wrapper = shallow&lt;SkeletonContent&gt;(&lt;SkeletonContent /&gt;);

  describe('rendering', () =&gt; {
    it('is defined', () =&gt; {
      expect(wrapper).toBeDefined();
    });
  });
});
</code></pre>
",https://stackoverflow.com/questions/58351358/typeerror-cannot-read-property-viewmanagersnames-of-undefined-integrating-j,"['typescript', 'react-native', 'jestjs', 'expo', 'enzyme']",1397,True,5,1
How to test functional component with async callback inside useEffect using snapshots,"<p>I'm trying to write unit tests on my component, it looks like this.</p>

<pre><code>export const myComponent = ({text, list, getData = transport.getData}) =&gt; {
const [rows, setRows] = React.useState([]);

    React.useEffect(() =&gt; {
        const fetchData = async () =&gt; {
           const rows = await getData(list);
           setRows(rows);
        };
        fetchData();
    }, [list]);

    if (rows.length === 0) {
       return null;
    }

    return (
        // some JSX
    );
};
</code></pre>

<p>The problem is that component fetches data via async function, so it will be called after the component check if <code>rows</code> is empty and return null.</p>

<pre><code>if (rows.length === 0) {
   return null;
}
</code></pre>

<p>I mocked <code>getData</code> so it should return some values. But still, I couldn't understand how I should cover this component with unit testing. I suppose it should be a snapshot, perhaps it is not right.</p>

<p>My test:</p>

<pre><code>import React from 'react';
import {myComponent} from '../components/myComponent';
import renderer from 'react-test-renderer';

describe('myComponent', () =&gt; {
    test('should renders correctly', async () =&gt; {
        const mock = {
            text: 'text',
            list: [],
            getData: () =&gt;
                Promise.resolve([
                    {
                        // ...
                    },
                ]),
        };
        const component = renderer.create(&lt;myComponent text={mock.text} 
list={mock.list} getData={mock.getData}/&gt;);
        let popup = component.toJSON();
        expect(popup).toMatchSnapshot();
    });
});
</code></pre>
",https://stackoverflow.com/questions/57778786/how-to-test-functional-component-with-async-callback-inside-useeffect-using-snap,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'react-test-renderer']",795,False,2,1
Unable to verify a call to a method on the mocked object with multiple interface,"<p>I'm trying to write unit test for <code>TranslateResponse()</code>.</p>

<pre><code>private async Task TranslateResponse(Policy policy)
{
  foreach(t in translatorFactory.BuildTranslator())
  {
    var policyTranslator=t as IPolicyAwareTranslator;
    policyTranslator?.SetPolicy(policy);
  }
}
</code></pre>

<p>The <code>TranslateResponse()</code> has many other translators though, but for now, I limited it to just one.
The <code>BuildTranslator</code> is as</p>

<pre><code>public async Task&lt;List&lt;ITranslator&gt;&gt; BuildTranslators()
{
   return new List&lt;ITranslator&gt;()
   {
     new PolicyTranslator()
   }
}
</code></pre>

<p>Here I'm returning the <code>PolicyTranslator</code> which implements <code>ITranslator</code> and <code>IPolicyAwareTranslator</code></p>

<p><code>ITranslator</code> has <code>Translate()</code> while <code>IPolicyAwareTranslator</code> has <code>SetPolicy(Policy policy)</code> respectively.
Now that for Unit testing, I create a Mock of <code>ITranslator</code> and set it up and I create the Mock of <code>IPolicyTranslator</code> via As&lt;>. </p>

<pre><code>Mock&lt;ITranslator&gt; mockedTranslator=new Mock&lt;ITranslator&gt;();
mockedTranslator.Setup(t =&gt; t.Translate(_translatorDataAccessor.Object));

var mockedPolicyTranslator = mockedTranslator.As&lt;IPolicyAwareTranslator&gt;();
mockedPolicyTranslator.Setup(t =&gt; t.SetPolicy(It.IsAny&lt;Policy&gt;()));

List&lt;ITranslator&gt; translators = new List&lt;ITranslator&gt;(new List&lt;ITranslator&gt;() { mockedTranslator.Object });
translatorFactory.Setup(t =&gt; t.BuildTranslators(It.IsAny&lt;string&gt;())).ReturnsAsync(translators);
</code></pre>

<p>Still the verify call fails.
I'm I going in the right direction or missing something? </p>

<pre><code>mockedPolicyTranslator.Verify(t =&gt; t.SetPolicy(new UnknownPolicy()), Times.AtLeastOnce);
</code></pre>
",https://stackoverflow.com/questions/58999349/unable-to-verify-a-call-to-a-method-on-the-mocked-object-with-multiple-interface,"['c#', 'unit-testing', 'moq']",31,True,2,1
Unit Testing MassTransit Consumer With XUnit,"<p>My team is just getting started with using MassTransit and we are trying to figure out how unit testing IConsumer implementations work. The MassTransit documentation is incomplete and all of the examples I have found so far use NUnit. We are trying to use XUnit with Moq to do our unit testing. </p>

<p>I know that we need to set up one instance of the MassTransit test harness, which in NUnit is done with a OneTimeSetup and to replicate that we should use IClassFixture in XUnit. I'm struggling with getting that to work with the test harness, though.</p>

<p>I have seen Chris Patterson's ConsumerTest_Specs.cs example on the MassTransit GitHub, but I'm having a hard time translating it to work in XUnit and Moq.
<a href=""https://github.com/MassTransit/MassTransit/blob/master/src/MassTransit.Tests/Testing/ConsumerTest_Specs.cs"" rel=""nofollow noreferrer"">https://github.com/MassTransit/MassTransit/blob/master/src/MassTransit.Tests/Testing/ConsumerTest_Specs.cs</a></p>

<p>I'm trying to test a very simple consumer to start with. All it does is receive the message and then make a call to a repository. I want to write an XUnit test that mocks the repository and verifies that the repository method was called. </p>

<p>Does anyone have any examples of how to do something like this?</p>

<pre><code>public class NewVMRequestRejectedConsumer : IConsumer&lt;INewVMRequestRejected&gt;
{
    private readonly INewVMRequestRepository _newVMRequestRepository;

    public NewVMRequestRejectedConsumer(INewVMRequestRepository newVMRequestRepository)
    {
        _newVMRequestRepository = newVMRequestRepository;
    }

    public Task Consume(ConsumeContext&lt;INewVMRequestRejected&gt; context)
    {
        _newVMRequestRepository.AddReasonForRejection(context.Message.RequestId, context.Message.Reason);
        return Task.CompletedTask;
    }
}
</code></pre>
",https://stackoverflow.com/questions/55642001/unit-testing-masstransit-consumer-with-xunit,"['c#', '.net', 'moq', 'xunit', 'masstransit']",1690,True,3,1
console errors while testing react component with font-awesome icon,"<p>I am using font-awesome in react project and using <code>jest</code> with <code>enzyme</code> for testing.
I am able to display the font-awesome icons but while performing unit testing, it is throwing following errors:</p>

<pre><code>console.error node_modules/@fortawesome/react-fontawesome/index.js:325
    Could not find icon { prefix: 'fas', iconName: 'arrow-right' }
console.error node_modules/@fortawesome/react-fontawesome/index.js:325
    Could not find icon { prefix: 'fas', iconName: 'arrow-right' }
console.error node_modules/@fortawesome/react-fontawesome/index.js:325
    Could not find icon { prefix: 'fas', iconName: 'arrow-right' }
console.error node_modules/@fortawesome/react-fontawesome/index.js:325
    Could not find icon { prefix: 'fas', iconName: 'arrow-right' }
console.error node_modules/@fortawesome/react-fontawesome/index.js:325
    Could not find icon { prefix: 'fas', iconName: 'arrow-right' }
</code></pre>

<p><strong>Note:</strong> It is happening only when I am testing component using <code>mount</code> method of <code>enzyme</code>. Issue is not happening when I test component using <code>shallow</code> method of <code>enzyme</code>.</p>

<p>I have imported the icons and added in library as follow:</p>

<pre><code>import { library } from '@fortawesome/fontawesome-svg-core';
import { fab } from '@fortawesome/free-brands-svg-icons';
import { faArrowRight } from '@fortawesome/free-solid-svg-icons';
...
library.add(fab, faArrowRight);
</code></pre>

<p>I have used icon as below:</p>

<pre><code>&lt;FontAwesomeIcon icon='arrow-right' /&gt;
</code></pre>

<p>I am using following packages:</p>

<pre><code>...
""@fortawesome/fontawesome-svg-core"": ""^1.2.20"",
""@fortawesome/free-brands-svg-icons"": ""^5.10.0"",
""@fortawesome/free-regular-svg-icons"": ""^5.10.0"",
""@fortawesome/free-solid-svg-icons"": ""^5.10.0"",
""@fortawesome/react-fontawesome"": ""^0.1.4"",
""enzyme"": ""^3.10.0"",
""enzyme-adapter-react-16"": ""^1.14.0"",
""react"": ""^16.9.0"",
""react-dom"": ""^16.9.0"",
...
</code></pre>
",https://stackoverflow.com/questions/57701921/console-errors-while-testing-react-component-with-font-awesome-icon,"['reactjs', 'unit-testing', 'font-awesome', 'enzyme']",2789,True,4,2
Return the result of a mocked method to another mocked method,"<p>I've got a class that has the following implementation:</p>

<pre><code>public sealed class HotelRepository : IHotelRepository
{
    private readonly string _dataSource;

    public HotelRepository(string dataSource) =&gt; _dataSource = dataSource;

    /// &lt;inheritdoc /&gt;
    public async Task&lt;IEnumerable&lt;Hotel&gt;&gt; GetAllAsync() =&gt;
        await Task.Run(() =&gt; JObject.Parse(File.ReadAllText(_dataSource))[""hotels""].ToList().Select(x =&gt; x.ToObject&lt;Hotel&gt;()));

    /// &lt;inheritdoc /&gt;
    public async Task&lt;IEnumerable&lt;Hotel&gt;&gt; GetListByMatchAsync(string name) =&gt;
        await GetAllAsync().ContinueWith(x =&gt; x.Result.Where(y =&gt; y.Name.Contains(name, StringComparison.CurrentCultureIgnoreCase)));
}
</code></pre>

<p>As you can see, the <code>GetListByMatchAsync</code> method calls <code>GetAllAsync</code>, then does some logic before returning the result.</p>

<p>When I tried to mock this repository for unit testing, I'm struggling to get a result out of <code>GetListByMatchAsync</code> as it always fails as a null reference exception.</p>

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

<pre><code>[TestCase(""Test"", ""X"")]
[TestCase(""Hotel"", ""X"")]
[TestCase(""Name"", ""X"")]
public async Task GetListByMatchAsync_GetHotelListByMatchingNameAsync_ReturnsFiveMatchingHotels(string name, string nonMatch)
{

    _hotelRepositoryMock = new Mock&lt;IHotelRepository&gt;();
    _hotelRepository = _hotelRepositoryMock.Object;

    // Set up sample data.
    var data = new List&lt;Hotel&gt;
    {
        new Hotel{Id = 1, Name = $""{name}"", Description = ""Description2"", Location = ""Location2"", Rating = Rating.Two},
        new Hotel{Id = 2, Name = $""{name.ToUpper()}"", Description = ""Description1"", Location = ""Location1"", Rating = Rating.Five},
        new Hotel{Id = 3, Name = $""{name.ToLower()}"", Description = ""Description2"", Location = ""Location2"", Rating = Rating.Three},
        new Hotel{Id = 4, Name = $""{name} {nonMatch}"", Description = ""Description2"", Location = ""Location2"", Rating = Rating.One},
        new Hotel{Id = 5, Name = nonMatch, Description = ""Description2"", Location = ""Location2"", Rating = Rating.One},
    };

    // Set up mock methods and ensure these method returns any sample data.
    _hotelRepositoryMock.Setup(x =&gt; x.GetListByMatchAsync(It.IsAny&lt;string&gt;()));
    _hotelRepositoryMock.Setup(x =&gt; x.GetAllAsync()).ReturnsAsync(data);


    var result = await _hotelRepository.GetListByMatchAsync(name);

    // Cast to list to make assertions.
    var hotels = result.ToList();

    Assert.That(hotels, Is.TypeOf&lt;List&lt;Hotel&gt;&gt;());
    Assert.That(hotels.Count, Is.EqualTo(4));
}
</code></pre>

<p>How can I make this test work such that the <code>GetListByMatchAsync</code> mock method does some logic after calling the mocked <code>GetAllAsync</code> method?</p>
",https://stackoverflow.com/questions/55206847/return-the-result-of-a-mocked-method-to-another-mocked-method,"['c#', 'unit-testing', 'moq']",524,True,1,1
How to Unit Test Exceptions in Kotlin Android,"<p>I am trying to write a unit test that tests if the exception is thrown, but I am not entirely sure how to do that.</p>

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

<pre><code>class GpsInfo {

    private lateinit var locationManager : LocationManager

    fun getGpsInfo(activity: Activity) : Location? {
        locationManager = activity.getSystemService(Context.LOCATION_SERVICE) as LocationManager

        var gpsCoordinates: Location
        try {
            gpsCoordinates = getGpsCoordinatesFromGpsProvider(locationManager)
        } catch(e: UnableAccessGPSProvider) {
            gpsCoordinates = getGpsCoordinatesFromNetwork(locationManager)
        } catch(e: Exception) {
            throw UnableGetGpsCoordinates(""Cant get GPS coordinates"")
        }

        return gpsCoordinates
    }

    private fun getGpsCoordinatesFromGpsProvider(locationManager: LocationManager) : Location {
        val gpsCoordinates = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
        if (gpsCoordinates == null) {
            throw UnableAccessGPSProvider(""Cant get GPS coordinates from GPS Provider"")
        }
        return gpsCoordinates
    }

    private fun getGpsCoordinatesFromNetwork(locationManager: LocationManager) : Location {
        val gpsCoordinates = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
        if (gpsCoordinates == null) {
            throw UnableAccessNetwork(""Cant get GPS coordinates from network"")
        }
        return gpsCoordinates
    }
</code></pre>

<p>And here my sad unit testing attempt, I am trying to achieve it with a mockking class:</p>

<pre><code>import android.app.Activity
import io.mockk.every
import io.mockk.mockk
import org.junit.*
import kotlin.test.assertFailsWith

class GpsServiceUnitTest {
    private val gps = mockk&lt;GpsInfo&gt;()

    @Before
    fun iniz() {
        every { gps.getGpsInfo(Activity()) } throws UnableAccessGPSProvider(""No GPS found"")
    }

    @Test
    fun testFails() {
        assertFailsWith(UnableAccessGPSProvider::class) {
            gps.getGpsInfo(Activity())
        }
    }
}
</code></pre>

<p>How can I achieve this? I need to feed the function something so it would throw the exception, but I don't see how this would work.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/58185364/how-to-unit-test-exceptions-in-kotlin-android,"['android', 'unit-testing', 'kotlin', 'junit', 'mocking']",2622,True,1,2
Is it ok to place test double implementations on the main java code,"<p>With regards to <a href=""https://martinfowler.com/bliki/TestDouble.html"" rel=""nofollow noreferrer"">test doubles</a> is it ok to place them on the main code so that they can be used, when testing code that contains the original library jar as a dependency?</p>

<p>There is code that assists me on unit testing (test doubles) on a library I implemented. Is it ok to keep this code in the jar so that it can be used by code that uses the library as a dependency.</p>
",https://stackoverflow.com/questions/55729476/is-it-ok-to-place-test-double-implementations-on-the-main-java-code,"['java', 'testing', 'test-double']",51,True,1,1
JS unit testing using enzyme: how to wait for setState within component&#39;s method to finish before proceeding with test case,"<p>I have a component <code>MyComponent</code> with method <code>doSomething</code> that updates a state, and <code>renderChildren</code> that renders child components based on these states:</p>

<pre><code>class MyComponent extends Component {
  constructor(props) {
    super(props);
    ...
    this.state = {
      renderChildA: true,
      renderChildB: false,
    };
  }

  doSomething = (params) =&gt; {
    // Do something...

    this.setState({ 
      renderChildA: false,
      renderChildB: true,
    });
  }

  renderChildren = () =&gt; {
    const { renderChildA, renderChildB } = this.state;
    if (renderChildA) {
      return &lt;ChildComponentA /&gt;;
    } else if (renderChildB) {
      return &lt;ChildComponentB /&gt;;
    }
  }

  render() {
    return (
      &lt;div&gt;
        {this.renderChildren()}
        ...
      &lt;/div&gt;
    );
  }
}
</code></pre>

<p><em>NOTE: the component is also connected to Redux, but has been simplified.</em></p>

<p>For unit testing, I'm calling <code>doSomething</code> and verifying that <code>ChildComponentB</code> is visible:</p>

<pre><code>test('doSomething should trigger ChildComponentB to pop up', () =&gt; {
  const wrapper = shallow(
    &lt;MyComponent
    ...
    /&gt;,
  ).dive();

  wrapper.instane().doSomething(params); // assume params is defined

  const childComponentB = wrapper.find('ChildComponentB');
  expect(childComponentB).toHaveLength(1);
});
</code></pre>

<p>However, the test case above fails:</p>

<pre><code>my-component.test.jsx &gt; Some test group name &gt; doSomething should trigger ChildComponentB to pop up

    expect(received).toHaveLength(length)

    Expected value to have length:
      1
    Received:
      // Some giant JSON object
    recevied.length:
      0

      xxx |    const childComponentB = wrapper.find('ChildComponentB');
      xxx |    expect(childComponentB).toHaveLength(1);
      xxx |  });
</code></pre>

<p>Based on the logging, I'm seeing that <code>setState</code> within <code>doSomething</code> is triggered after <code>expect</code> statement in the test case. I suspect this is happening since <a href=""https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync""><code>setState</code> is asynchronous</a>, but I don't know a workaround for this (other than <code>setTimeout</code>).</p>
",https://stackoverflow.com/questions/57280880/js-unit-testing-using-enzyme-how-to-wait-for-setstate-within-components-method,"['javascript', 'reactjs', 'enzyme']",7777,True,7,4
How do I conduct a min unit test in c?,"<p>I have written code for a parser for the LOGO turtle graphics programming language and need to test it. </p>

<p>I would like to use min unit (<a href=""http://www.jera.com/techinfo/jtns/jtn002.html#Example"" rel=""nofollow noreferrer"">http://www.jera.com/techinfo/jtns/jtn002.html#Example</a>) as it seems the most simple way of testing. A small section of my parser code is below. Please could you give me an example using my own code on how to implement the min unit testing?</p>

<p>Thanks in advance:)</p>

<pre><code>int main(int argc, char **argv)
{
   int x;
   FILE *input_file;
   Prog input; /* struct to hold file*/

   if (check_inputs(argc) != true) {
      return EXIT_FAILURE;
   }

   input.current_line = 0;
   for(x=0; x&lt;MAX_LINES; x++) {
     input.words[x][0] = '\0';
   }

   input_file = fopen(argv[1], ""r"");
   if (input_file == NULL) {
      fclose(input_file);
      fprintf(stderr, ""Failed to open %s\n"", argv[1]);
      return EXIT_FAILURE;
   }

   x = 0;
   while(fscanf(input_file, ""%s"", input.words[x++]) == 1
                                     &amp;&amp; x &lt; MAX_LINES) {
      assert(x &lt; MAX_LINES);
   }

   start_parse(&amp;input);
   printf(""All instructions parsed okay if no other error messages printed!\n"");
   fclose(input_file);
   free(input_file);
   return EXIT_SUCCESS;
}


/*check command line inputs and return file name as a string*/
int check_inputs (int argc)
{
   if (argc != ARG_NUM) {
      fprintf(stderr,""Incorrect number of argumemts.\n"");
      return false;
   }
   return true;
 }


/*structs */
struct prog {
   char words[MAX_LINES][MT_SIZE];
   int vars[NUM_VARS];
   int current_line;
   int current_var;
};
typedef struct prog Prog;
</code></pre>
",https://stackoverflow.com/questions/54382925/how-do-i-conduct-a-min-unit-test-in-c,"['c', 'turtle-graphics']",173,False,1,0
Unit Testing Express with mocha/chai/sinon - how do I test my res.send object shape?,"<p>I am unit testing the individual components that lead up to an API response, in other words, I'm testing it independently of a route since every route runs through this component</p>

<p>I need to test that the function responsible for sending my express response is the correct shape, but without sending an actual HTTP request I can't figure out how to test it.</p>

<p>Here is my component</p>

<pre><code>'use strict'

const moment = require('moment')
module.exports = (req, res, payload) =&gt; {
  try {
    let data = []
    if (payload.token) data.push({ token: payload.token })
    data.push({ [payload.resource]: payload.data })
    res.send({
      status: 'OK',
      recordCount: payload.data.length,
      startTimestamp: req.start.toDate(),
      endTimestamp: moment().toDate(),
      timeTaken: moment().toDate().getTime() - req.start.toDate().getTime(),
      data: data
    })
  } catch (error) {
    return res.status(500).json({
      errors: [{
        location: 'n/a',
        param: 'n/a',
        msg: 'something happened when generating the response'
      }]
    })
  }
}
</code></pre>

<p>here is my current test ...</p>

<pre><code>const chai = require('chai')
const sinonChai = require('sinon-chai')
const { mockReq, mockRes } = require('sinon-express-mock')
const moment = require('moment')
const present = require('../../src/lib/present')

chai.use(sinonChai)

describe('unit test the present lib method', () =&gt; {
  it('should return the expected shape', (done) =&gt; {
    const req = mockReq({
      start: moment().toDate(),
      body: {}
    })
    const res = mockRes()
    const shape = present(req, res, {
      resource: 'empty_array',
      data: []
    })
    shape.should.have.own.property('data') // doesnt work
    // AssertionError: expected { Object (append, attachement, ...) } to have own property 'data'
    done()
  })
})
</code></pre>
",https://stackoverflow.com/questions/56471968/unit-testing-express-with-mocha-chai-sinon-how-do-i-test-my-res-send-object-sh,"['node.js', 'express', 'mocha.js', 'chai', 'sinon']",813,False,1,1
How to implement middleware with go-swagger?,"<p>I am using go-swagger to create API endpoint and the business logic is called inside the handler function directly , which is working fine . I need to implement ""Middleware"" , which can also ease in unit testing which I am doing using mockery and testify . Below is the code . </p>

<h3><code>Swagger.yml</code></h3>

<p>I have provided only sample code for endpoint</p>

<pre><code>---
swagger: ""2.0""
info:
  description: Swagger api for VM Manager
  title: vmManager
  version: 1.0.0
consumes:
- application/json
produces:
- application/json
schemes:
- http
paths:
  /createVM:
    post:
      tags:
        - vmManager
      operationId: createVM
      parameters:
        - name: body
          in: body
          schema:
            $ref: ""#/definitions/vmInput""
      responses:
        201:
          description: Created
          schema:
            $ref: ""#/definitions/response""
        default:
          description: error
          schema:
            $ref: ""#/definitions/errorObject""
</code></pre>

<h3><code>configure_vmmanager.go</code></h3>

<p>Call from above swagger comes here</p>

<pre><code>api.VMManagerCreateVMHandler = vm_manager.CreateVMHandlerFunc(func(params vm_manager.CreateVMParams) middleware.Responder {
        log.Debugf(""Create VM Handler Called"")
        log.Infof(""Payload Data : %v , VM Name : %v , Request ID : %v"", params.Body.ConfigData, params.Body.VMName, params.Body.RequestID)  
        log.WithFields(log.Fields{
            ""Request Payload"": params.Body,
        }).Infof(""Request Payload to  CreateVMHandler: "")

        vmOutput, err := resthandler.CreateVMHandler(params.Body)
        if err != nil {
                log.Errorf(""Eror while creating VM %v :"" ,err)
                 errorObject := &amp;models.ErrorObject{ErrorDetails: err ,}
    // TODO Addition for custom error code
                //return vm_manager.NewCreateVMDefault(*ErrorCode).WithPayload(&amp;models.Error{ErrorCode: errorCode, ErrorDesc: err.ErrorDesc})
                return vm_manager.NewCreateVMDefault(int(*err.ErrorCode)).WithPayload(errorObject)
        }
        log.WithFields(log.Fields{
            ""Response of CreateVMHandler"":vmOutput,
        }).Infof(""Response from  CreateVMHandler :"")
        return vm_manager.NewCreateVMCreated().WithPayload(vmOutput)
    })
</code></pre>

<h3><code>create_vm_handler.go</code></h3>

<p>Definition part</p>

<pre><code>func CreateVMHandler(item *models.VMInput) (*models.Response, *models.ErrorDetails) {
.
.
.
return serverOut, nil
}
</code></pre>

<p>Please comment in case of any additional information is needed.</p>
",https://stackoverflow.com/questions/59045045/how-to-implement-middleware-with-go-swagger,"['go', 'middleware', 'go-swagger']",1248,False,1,0
How to get value of nested props function for unit testing,"<p>I have an issue with getting value of nested props function.</p>

<p><code>this.props.user.getPerson().getData()</code></p>

<p><code>getPerson</code> returns new object with person related data.</p>

<p><code>getData</code> returns person related data.</p>

<p>It's separated for readability and I want to make it work for unit testing.</p>

<p>Test 1: </p>

<pre><code> let _wrapper,
    initialProps

  beforeEach(() =&gt; {
    initialProps = {
      user: {
        getPerson: () =&gt; {}
      }
    }
    _wrapper = shallow(&lt;Test1 {...initialProps} /&gt;)
  })
some tests...
})
</code></pre>

<p>It returned <code>TypeError: Cannot read property 'getData' of undefined</code>.</p>

<p>Test2</p>

<pre><code> let _wrapper,
    initialProps

  beforeEach(() =&gt; {
    initialProps = {
      user: {
        getPerson: () =&gt; { getData: () =&gt; {} }
      }
    }
    _wrapper = shallow(&lt;Test2 {...initialProps} /&gt;)
  })
some tests...
})
</code></pre>

<p>It returned <code>TypeError: Cannot read property 'getData' of undefined</code>
Same error as Test1.</p>

<p>I tried to get value of props function by passing function however it didn't work from second function.</p>

<p>How can I get value of nested props function? </p>
",https://stackoverflow.com/questions/54558581/how-to-get-value-of-nested-props-function-for-unit-testing,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",132,True,1,1
React test fails on wrapper.instance(),"<p>I'm new to React unit testing and I'm trying to write a test for a component method.</p>

<p>Taking the below example, I need to write a test for the <code>changeHandler</code> method of <code>ComponentA</code>:</p>

<pre><code>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

class ComponentA extends Component {
    changeHandler = () =&gt; {
        // additional logic here
    }

    render() {

        return (
            &lt;div&gt;
                &lt;Field
                    name='text'
                    onChange={ () =&gt; this.changeHandler() }
                    component={renderTextField}&gt;
                &lt;/Field&gt;
            &lt;/div&gt;
        );
    }
}

ComponentA.contextTypes = {
    router: PropTypes.object.isRequired
}

const mapStateToProps = (state)=&gt; ({

})

const mapDispatchToProps = (dispatch) =&gt; ({

})

export default reduxForm({
    form: 'componentForm',
})(connect(mapStateToProps, mapDispatchToProps)(ComponentA));
</code></pre>

<p>This is how I tried to achieve my goal:</p>

<pre><code>import React from 'react';
import ComponentA from './ComponentA';
import { createMount } from '@material-ui/core/test-utils';
import Enzyme from 'enzyme';
import { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import configureMockStore from 'redux-mock-store';

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

describe('Component Form', () =&gt; {
  let mount, store, wrapper;

  const mockStore = configureMockStore({});
  beforeEach(() =&gt; {
    store = mockStore([]),
    mount = createMount({strict: false}),
    wrapper = shallow(&lt;ComponentA store={store}/&gt;).dive()
  });


  it('should change values', () =&gt; {
    wrapper.instance().changeHandler()
  });
});
</code></pre>

<p>But running the tests I'm getting</p>

<blockquote>
  <p>TypeError: wrapper.instance(...).changeHandler is not a function` </p>
</blockquote>

<p>I'm not sure what I'm doing wrong... am I missing something?</p>

<p>Additional details:  </p>

<p>using <code>shallow().dive().dive().dive().dive().dive().dive().dive()</code> the <code>changeHandler</code> method shows up, but I'm getting <code>undefined</code> when doing <code>console.log(wrapper.instance().changeHandler()</code>:</p>

<pre><code>  ComponentA {
        props: 
         { array: 
            { insert: [Function],
              move: [Function],
              pop: [Function],
              push: [Function],
              remove: [Function],
              removeAll: [Function],
              shift: [Function],
              splice: [Function],
              swap: [Function],
              unshift: [Function] },
           anyTouched: false,
           asyncValidate: [Function],
           asyncValidating: false,
           blur: [Function],
           change: [Function],
           clearSubmit: [Function],
           destroy: [Function],
           dirty: false,
           dispatch: [Function: dispatch],
           error: undefined,
           form: 'campaign',
           handleSubmit: [Function],
           initialize: [Function],
           initialized: false,
           initialValues: undefined,
           invalid: false,
           pristine: true,
           reset: [Function],
           resetSection: [Function],
           submitting: false,
           submitFailed: false,
           submitSucceeded: false,
           touch: [Function],
           untouch: [Function],
           valid: true,
           warning: undefined,
           currentUser: { username: 'test', userId: 1 },
           codes: { bitlyCompany: [] },
           config: { classificationsPermissions: [Object] },
           codeConfiguration: { status: 'In Progress' },
           store: 
            { getState: [Function: getState],
              getActions: [Function: getActions],
              dispatch: [Function: dispatch],
              clearActions: [Function: clearActions],
              subscribe: [Function: subscribe],
              replaceReducer: [Function: replaceReducer] },
           pure: true,
           validate: [Function],
           triggerSubmit: undefined,
           autofill: [Function],
           clearFields: [Function],
           clearSubmitErrors: [Function],
           clearAsyncError: [Function],
           submit: [Function],
           storeSubscription: 
            Subscription {
              store: [Object],
              parentSub: [Object],
              onStateChange: [Function: bound onStateChange],
              unsubscribe: [Function: unsubscribe],
              listeners: [Object] },
           },
        context: { router: undefined },
        refs: {},
        updater: 
         Updater {
           _renderer: 
            ReactShallowRenderer {
              _context: [Object],
              _element: [Object],
              _instance: [Circular],
              _newState: null,
              _rendered: [Object],
              _rendering: false,
              _forcedUpdate: false,
              _updater: [Circular],
              _dispatcher: [Object],
              _workInProgressHook: null,
              _firstWorkInProgressHook: null,
              _isReRender: false,
              _didScheduleRenderPhaseUpdate: false,
              _renderPhaseUpdates: null,
              _numberOfReRenders: 0 },
           _callbacks: [] },
        changeHandler: [Function],
        setState: [Function], }
</code></pre>
",https://stackoverflow.com/questions/58023729/react-test-fails-on-wrapper-instance,"['javascript', 'reactjs', 'jestjs', 'enzyme']",3014,True,4,1
Cant read property &#39;model&#39; of undefined,"<p>This is my foree' into mongoose methods.  Any suggestions really appreciated.  Mocha is complaining about it cannot find my model collection (in my code is the ""this.model('User'.... line)).  I am using sinon stub to stub out Model and method name.</p>

<p>Unit testing the schema (validating validators) went well.  I am trying to get my head wrapped around a simple mongoose.method.</p>

<p>tony
<a href=""https://i.stack.imgur.com/Z7f7J.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Z7f7J.jpg"" alt=""code failure""></a></p>

<p>Mongoose method (bottom portion of mongoose schema file):</p>

<pre><code>userSchema.methods.findUser = (cb) =&gt; {
this.model('User').findOne({
    lname: this.lname
}, (err, val) =&gt; {
    cb(!!val);
});
};
module.exports = mongoose.model('User', userSchema);
</code></pre>

<p>My test for this method:</p>

<pre><code>it('gets a User', (done) =&gt; {
  sinon.stub(User, 'findOne');
  let u = new User({ lname: 'Pickles' });

  u.findUser();

  sinon.assert.calledWith(User.findOne, { lname: 'Pickles' });
  done();
});
</code></pre>
",https://stackoverflow.com/questions/54385356/cant-read-property-model-of-undefined,"['mongoose', 'methods', 'sinon']",58,True,1,1
Unit test controller with IConfiguration using Moq and Mock setup returns null,"<p>New to Unit Testing web api.
I am writing a Unit test to Test a controller and I have to mock Iconfiguration. The appsettings,json has a section called &quot;AppSettings&quot;, I'm trying to mock it.</p>
<p>Also, the mock.setup returns null value in the controller causing it to fail.</p>
<p>Here is my controller:</p>
<pre><code>    private readonly ILogger _logger;
    private readonly IConfiguration _configuration;
    private readonly ICarPairingTable PairingTable;
    private readonly ICarDealerSettingsTable DealerSettingsTable;
    static AppSettings appSettings = null;
    public CarController(IConfiguration configuration, ICarPairingTable carPairingTable, ICarDealerSettingsTable settingsTable)
    {
        _configuration = configuration;
        appSettings = configuration.Get&lt;AppSettingsModel&gt;().AppSettings;
        PairingTable = carPairingTable;
        DealerSettingsTable = settingsTable;
    }
    
    [HttpGet]
    public ActionResult Get(string id){
        string DealerId =&quot;&quot;;
        
            
                DealerId = PairingTable.GetDealerId(id).Result;
                if (string.IsNullOrEmpty(DealerId))
                {
                    result = new ReturnResult
                    {
                        status = &quot;Fail&quot;,
                        data = &quot;ID is invalid&quot;
                    };
                    return NotFound(result);
                }
           
           
            
            SettingsInfo info = DealerSettingsTable.GetSettingsInfo(DealerId).Result;
            if (info == null)
            {
                result = new ReturnResult
                {
                    status = &quot;Fail&quot;,
                    data = &quot;Not Found&quot;
                };
                return NotFound(result);

            }
            result = new ReturnResult
            {
                status = &quot;Success&quot;,
                data = info
            };
            return Ok(result);
    }
    
</code></pre>
<p>Here is my Unit Test:</p>
<pre><code>   [Fact]
    public void Test1()
    {
        var mockConfig = new Mock&lt;IConfiguration&gt;();
        var configurationSection = new Mock&lt;IConfigurationSection&gt;();

        configurationSection.Setup(a =&gt; a.Value).Returns(&quot;testvalue&quot;);
        mockConfig.Setup(a =&gt; a.GetSection(&quot;AppSettings&quot;)).Returns(configurationSection.Object);

        var mock1 = new Mock&lt;ICarPairingTable&gt;();
       
        mock1.Setup(p =&gt; p.GetDealerId(&quot;456&quot;)).ReturnsAsync(&quot;123&quot;);
        var mock2 = new Mock&lt;ICarDealerSettingsTable&gt;();
        SettingsInfo mockSettings = new SettingsInfo()
        {
            DealerId = &quot;123&quot;,
            
            Name=&quot;Dealer1&quot;
        };
        mock2.Setup(p =&gt; p.GetSettingsInfo(&quot;123&quot;)).ReturnsAsync(()=&gt;mockSettings);
        
        CarController controller = new CarController(mockConfig.Object,  mock1.Object, mock2.Object);
        var result = controller.Get(&quot;456&quot;);

        //Dont know what to assert

    }
</code></pre>
<p>Wrote unit test, but not sure if my approach is correct, Help will be appreciated.</p>
",https://stackoverflow.com/questions/57278008/unit-test-controller-with-iconfiguration-using-moq-and-mock-setup-returns-null,"['c#', 'unit-testing', 'configuration', 'moq']",1242,True,1,1
How to test nested service call containing SwitchMap,"<p>I have a two service call nested on service component and I am using the swithcMap for it. Code is something like like below which works perfectly fine but unit test is not working. Can someone suggest what I am doing wrong on unit testing?</p>

<pre><code>myService():Observable&lt;HttpResponse&lt;any&gt;&gt;{
   return this.http.get&lt;string&gt;(this.firstURL)
      .pipe(
          switchMap(res1 =&gt;{
          return this.http.get&lt;any&gt;(res1['val1']['val2']);
         }
      })
}
</code></pre>

<p>For testing above code I have something like this </p>

<pre><code>it('should call http', () =&gt; {
   serv.myService().subscribe(res =&gt;
      expect(res.val).toBe(100)
   )

var req = httpMockServ.expectOne('testUrl');
req.flush({val:10});

});
</code></pre>

<p>Looks like it is not mocking the second http call. I am getting can not read property val2 of undefined. </p>
",https://stackoverflow.com/questions/57103053/how-to-test-nested-service-call-containing-switchmap,"['angular', 'angular-test']",353,False,1,0
What API is there for selecting iTunes library location?,"<p>How does one programatically set the iTunes library location on macOS to custom locations using e.g. C / Obj-C or Swift API?</p>

<p>Alternatively, environmental settings, such as modifying plists, using the <code>defaults</code> CLI tool, or similar approaches, are also OK for me.</p>

<p>Ordinarily, selecting a custom iTunes library location is done by launching iTunes while holding down the option key. I need to be able to do this in e.g. a unit testing environment / programatically.</p>
",https://stackoverflow.com/questions/57366876/what-api-is-there-for-selecting-itunes-library-location,"['macos', 'cocoa', 'itunes', 'ituneslibrary']",86,False,1,1
Is there a way to wait for the DOM to update in Angular?,"<p>If I have something like the following</p>

<pre><code>&lt;form #myForm=""ngForm""&gt;
  &lt;input *ngFor=""let item of items; index as i"" [name]=""'input_' + i"" [(ngModel)]=""item"" myValidationAttribute&gt;
&lt;/form&gt;
</code></pre>

<p>and I have a function that updates items and I need to wait form the form to update before submitting the form</p>

<pre><code>updateAndSubmit() {
  this.items = newItems;
  setTimeout(() =&gt; {
    if (this.myForm.valid) {
      // Do stuff with valid form
    }
  });
}
</code></pre>

<p>Is using setTimeout like this the preferred way of waiting for the DOM refresh or is there something along the line of fixture.whenStable() used in unit testing?</p>

<p>setTimeout just doesn't feel right, like it is a dirty hack.</p>

<p>Here is a StackBlitz <a href=""https://stackblitz.com/edit/angular-pv4tyb"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/angular-pv4tyb</a></p>
",https://stackoverflow.com/questions/59149132/is-there-a-way-to-wait-for-the-dom-to-update-in-angular,"['angular', 'angular-forms']",1658,True,3,2
How to properly unit test constexpr functions,"<p>If I have a <code>constexpr</code> function, should there be both a runtime verification, and a compile time verification?</p>

<p>If there is only a compile-time check <code>static_assert</code>, then the function will not be included in any code coverage statistics. However, if there is only a runtime check, there is no verification that the function actually works in a <code>constexpr</code> context.</p>

<p>In short, the question is whether or not both runtime unit-testing <em>and</em> <code>static_assert</code>s are needed to test the same thing.</p>
",https://stackoverflow.com/questions/59180520/how-to-properly-unit-test-constexpr-functions,"['c++', 'unit-testing', 'constexpr']",767,False,3,1
Conflict between react script and jest version 24.7.1,"<p>After creating a react app with 'create-react-app' things have been successful till now. I have made a working react project. But now that I'm looking to implement unit testing with jest. </p>

<p>Using npm to install: 'npm install --save-dev jest'
Then running: npm ls jest I notice that the react-script is looking for a jest version that is significantly older.</p>

<p>package.json:</p>

<pre><code>""dependencies"": {
""react"": ""^16.8.1"",
""react-dom"": ""^16.8.1"",
""react-redux"": ""^6.0.0"",
""react-scripts"": ""2.1.5"",
""redux"": ""^4.0.1""
},

""devDependencies"": {
""jest"": ""^24.7.1""
},

""scripts"": {
""start"": ""react-scripts start"",
""build"": ""react-scripts build"",
""test"": ""jest"",
""eject"": ""react-scripts eject""
}
</code></pre>

<p>npm ls jest result:</p>

<pre><code>+-- jest@24.7.1
`-- react-scripts@2.1.5
  `-- jest@23.6.0
</code></pre>

<p>npm start error:</p>

<pre><code>There might be a problem with the project dependency tree.
It is likely not a bug in Create React App, but something you need to fix 
locally.

The react-scripts package provided by Create React App requires a         
dependency:

""jest"": ""23.6.0""

Don't try to install it manually: your package manager does it 
automatically.
However, a different version of jest was detected higher up in the tree:

C:\Users\userName\sample js codes\redux\songs\node_modules\jest (version: 
24.7.1)
</code></pre>

<p>Is there a solution to solve this dependency version issue?</p>
",https://stackoverflow.com/questions/55630841/conflict-between-react-script-and-jest-version-24-7-1,"['javascript', 'node.js', 'reactjs', 'jestjs']",4277,True,6,1
Does anyone have experience with the ElasticMock python module?,"<p>I am trying to integrate the ElasticMock python module into my unit testing, but I am having a hard time using it along with methods I have already created in my code.</p>

<pre class=""lang-py prettyprint-override""><code>import datetime
from elasticmock import elasticmock
from elasticmock.fake_elasticsearch import FakeElasticsearch


function test_me(self):
    doc = {
        'author': 'test_author',
        'text': 'Elasticsearch: cool. bonsai cool.',
        'timestamp': datetime.datetime.now()
    }

    fake_elasticsearch = FakeElasticsearch()
    f_index = fake_elasticsearch.index(index='test_index', doc_type='_doc', body=doc, id=1)
self.assertIsNotNone(r_index)
</code></pre>

<p>I expect when using the actual Elasticsearch module's get() method that I will be able to retrieve this index, and its contents from the local host unless this has nothing to do with the local host, and just spawns the index in memory during runtime.</p>
",https://stackoverflow.com/questions/56781428/does-anyone-have-experience-with-the-elasticmock-python-module,"['python', 'dictionary', 'elasticsearch', 'request', 'python-unittest']",565,False,3,0
C# MissingMethodException with DispatchProxy and FakeItEasy,"<p>I'm writing a class library with .NET Core and I'm using interception (DispatchProxy) for handling cross-cutting concerns.</p>

<p>Now I have the problem that when unit testing the decorated object I get the following Exception:</p>

<pre><code>Exception thrown: 'System.MissingMethodException' in System.Private.CoreLib.dll
Exception thrown: 'System.Exception' in FakeItEasy.dll
Exception thrown: 'System.Reflection.TargetInvocationException' in System.Private.CoreLib.dll
</code></pre>

<p>Also when debugging I noticed that a specific method of a dynamically generated object (which is mocked with FakeItEasy) is not executed. </p>

<p>Is the problem that you can't mock dynamic generated objects? Or maybe that FakeItEasy is itself using interception with Castle.DynamicProxy?</p>
",https://stackoverflow.com/questions/59064509/c-missingmethodexception-with-dispatchproxy-and-fakeiteasy,"['c#', 'unit-testing', 'exception', 'castle-dynamicproxy', 'fakeiteasy']",157,False,3,0
test matlab classes defined in different folder,"<p>I've the following matlab project structure:</p>

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

<p><code>tests</code> folder contains test classes that must be executed with the testing framework. The class <code>PostgreSQLConnectionOptionsTest</code> is the following one</p>

<pre><code>classdef PostgreSQLConnectionOptionsTest &lt; matlab.unittest.TestCase

  methods (Test)

    function testDefaultConstructor(this)
      options = WTrade.Database.PostgreSQLConnectionOptions();
      this.verifyEqual(options.getHostName(), """");
      this.verifyEqual(options.getPort(), ""0"");
      this.verifyEqual(options.getDatabaseName(), """");
      this.verifyEqual(options.getUsername(), """");
      this.verifyEqual(options.getPassword(), """");
    end
  end
end
</code></pre>

<p>The script <code>runAllTests</code> contains the following code:</p>

<pre><code>import matlab.unittest.TestSuite

databaseSuite = TestSuite.fromFolder(""tests/WTrade/Database"");
result = run(databaseSuite);
</code></pre>

<p>When I run the script I obtain the following output, with an error:</p>

<pre><code>&gt;&gt; runAllTests
Running PostgreSQLConnectionOptionsTest

================================================================================
Error occurred in PostgreSQLConnectionOptionsTest/testDefaultConstructor and it did not run to completion.
    ---------
    Error ID:
    ---------
    'MATLAB:undefinedVarOrClass'
    --------------
    Error Details:
    --------------
    Undefined variable ""WTrade"" or class ""WTrade.Database.PostgreSQLConnectionOptions"".

    Error in PostgreSQLConnectionOptionsTest/testDefaultConstructor (line 6)
          options = WTrade.Database.PostgreSQLConnectionOptions();
================================================================================
.
Done PostgreSQLConnectionOptionsTest
__________

Failure Summary:

     Name                                                    Failed  Incomplete  Reason(s)
    =======================================================================================
     PostgreSQLConnectionOptionsTest/testDefaultConstructor    X         X       Errored.
</code></pre>

<p>Basically I cannot use the <code>PostgreSQLConnectionOptions</code> inside the test class because it's not found.</p>

<p>How can I fix the code so I can perform unit testing maintaining code and tests folder separated?</p>
",https://stackoverflow.com/questions/58580792/test-matlab-classes-defined-in-different-folder,"['matlab', 'unit-testing', 'class']",109,True,0,2
Unable to do unit testing of Python AWS code,"<p>I have never done unit testing before, so I am not able to understand how to do it in any module of my code. </p>

<p>I have coded functons for tag insertion and deletion in AWS using boto3. I will attach the code of a function below. I need to know how to unit test the code without using mocking. Or is it even possible?</p>

<pre class=""lang-python prettyprint-override""><code>def tagging_insertion(self, source_objectname, tagset):
    s3_client = boto3.client('s3', region_name=self.parameter[""default_region""])
    s3_client.put_object_tagging(
        Bucket = self.parameter[""SourceBucketName""],
        Key = source_objectname,
        Tagging = tagset
    )
</code></pre>

<p>This is part of the code I want to unit test.</p>
",https://stackoverflow.com/questions/58471200/unable-to-do-unit-testing-of-python-aws-code,"['python', 'amazon-web-services', 'python-unittest']",49,False,-1,1
How to use Nsubstitue for method with different arguments and return values?,"<p>For unit testing I am using <code>NSubstitue</code> to stub my repository method (say <code>IRepo.GetOrder(orderId)</code>) I am able to stub this for one specific argument like :</p>

<pre><code>IRepo RepoSub = Substitute.For&lt;IRepo&gt;();
Order ord = new Order{/*...*/}
RepoSub.GetOrder(Arg.Is&lt;int&gt;(123)).ReturnsForAnyArgs(ord);
</code></pre>

<p>However BL method I am testing makes use of <code>Repository</code> for multiple Order Ids in array passed as an i/p parameter to that BL method (<code>int[] orderIds</code>). I am not sure how can I use <code>NSubstitue</code> for varying arguments in <code>RepoSub</code> <code>GetOrder</code>. I tried figuring out in Nsubstitue document, but no luck.</p>

<p>Any help appreciated. Thanks!!  </p>
",https://stackoverflow.com/questions/57981359/how-to-use-nsubstitue-for-method-with-different-arguments-and-return-values,"['c#', 'unit-testing', 'mocking', 'nsubstitute']",452,True,0,1
Simulate native/unmanaged exception in C#,"<p>For the purposes on unit testing I would like to generate a native/unmanaged <em>CRT</em> exception in C# so we can test what happens.</p>

<p>I can write a c++ DLL and corrupt the stack etc but I'm wondering if there is a nice way to do this in C#. I thought about calling a Windows DLL incorrectly etc.</p>

<p>Is there any way to reliably generate an exception like this on Windows 10 in C#?</p>
",https://stackoverflow.com/questions/58793618/simulate-native-unmanaged-exception-in-c,"['c#', 'exception', 'interop']",94,True,0,1
Having issues unit testing internal class in c#,"<p>So i'm having an issues unit testing the PermissionRequirementFilter below. This class was perviusly being DI'd into the unit test but something has changed and im unsure whats happend. Its complaining about the protection level of the class as its an internal based class. </p>

<p><strong>MainClass:</strong></p>

<pre><code>public class PermissionRequirementAttribute : TypeFilterAttribute
{
    public PermissionRequirementAttribute(string permissions) : base(typeof(PermissionRequirementFilter))
    {
        Arguments = new object[]
        {
            Regex.Split(permissions, @"",\s*"").ToList()
        };
    }
}

internal class PermissionRequirementFilter : IAuthorizationFilter
{
    private readonly IEnumerable&lt;string&gt; _requiredPermissions;
    private readonly IOrganisationsServiceProxy _organisationsProxy;

    public PermissionRequirementFilter(
        IOrganisationsServiceProxy organisationsProxy,
        IEnumerable&lt;string&gt; requiredPermissions)
    {
        _requiredPermissions = requiredPermissions;
        _organisationsProxy = organisationsProxy;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
    }
}
</code></pre>

<p><strong>TestConstructor</strong>:
The test class looks like the code below but the import isnt letting me DI the class into the test class.</p>

<pre><code>public class PermissionRequirementAttributeTests
{
    private readonly IEnumerable&lt;string&gt; _testPermissions;
    private readonly PermissionRequirementFilter _permissionRequirementFilter;
    private readonly Mock&lt;IOrganisationsServiceProxy&gt; _organisationProxy;

    public PermissionRequirementAttributeTests()
    {
        _organisationProxy = new Mock&lt;IOrganisationsServiceProxy&gt;();
        _testPermissions = new List&lt;string&gt; { ""myPermission"", ""mySecondPermission"", ""myThirdPermission"" };
        _permissionRequirementFilter = new PermissionRequirementFilter(_organisationProxy.Object, _testPermissions);
    }
}
</code></pre>

<p>Any help would be great thanks in advance.</p>
",https://stackoverflow.com/questions/58984865/having-issues-unit-testing-internal-class-in-c,"['c#', 'dependency-injection', 'xunit']",51,False,0,0
How to autowire inside a @Configuration class during JUnit tests?,"<p>I'm testing a module of my multi module spring boot project.</p>

<p>I'm unit testing a class annotated as @Configuration. There is a method that uses a class that is injected with @Autowired. During JUnit tests, I got a NullPointer because the Autowired is not working. How to make it work?</p>

<p>The application is working fine, my problem is only happening on JUnit tests.</p>

<p>I tried some annotations found in other answers</p>

<pre><code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {BasicConfiguration.class, SomeClass.class})
@TestPropertySource(locations= ""classpath:applicationTest-configs-ok.properties"")
public class BasicConfigurationTest {

  @Autowired
  BasicConfiguration basicConfig;
</code></pre>

<pre><code>@Configuration
public class BasicConfiguration {

  @Autowired
  private SomeClass someClass ;  &lt;--- this is not working

  @Bean
  AnotherClass someMethod(){
    return someClass.doSomething(); &lt;--- nullpointer
  }
</code></pre>

<pre><code>@Component
SomeClass {
  @Value(""${test.param}""))   &lt;--- defined in applicationTest-configs-ok.properties
  String myParam;
}
</code></pre>

<p>someClass should be injected</p>
",https://stackoverflow.com/questions/55497729/how-to-autowire-inside-a-configuration-class-during-junit-tests,"['java', 'unit-testing', 'spring-boot']",1054,True,0,1
"How do i mock a list of Key,Value pairs (in angular) which does not have indices?","<p>I am unit testing an <strong>angular</strong> application using <strong>Jasmine</strong> and i am in it.
The application has a back-end written in <strong>Spring boot</strong>, which exposes some API's.</p>

<p>The content received from one of the API's (GET request) is a <strong>List of Mapped Key,Value(Object,Value) pairs</strong>.</p>

<p>What i want is to mock the response such that it looks the same as below (result).</p>

<pre><code>Like this =&gt; [
                 key: value *//does not have an index*
             ]

Accessed like this =&gt; this.list = result['someList'];
</code></pre>

<p>For example, </p>

<pre><code>constructor(private httpClient: HttpCLient) {}

ngOnInit() {
    this.getAll().subscribe(result =&gt; {
        this.someListInsideResult = result['someList'];
        console.log('result: ', result);
        console.log('someListInsideResult: ', someListInsideResult);
    }
}

getAll() {
    this.headers = new HttpHeaders().set('X-Authorization', 'Bearer  ' + token).set('X-Requested-With', 'XMLHttpRequest').set('Content-Type', 'application/json');
    return httpClient.get(url, {headers: headers});
}
</code></pre>

<p>console:</p>

<pre><code>// actual respose(result)
result: [
            key1: value1
            key2: value2
            ...
            ...
            someList: 0: ""stringValue""
                      1: ""ENUM""
                      2: null
        ]

// list inside the response
someListInsideResult: 0: ""stringValue""
                      1: ""ENUM""
                      2: null
</code></pre>

<p>if anyone can help that will very grateful.</p>

<p>thanks in advance.</p>
",https://stackoverflow.com/questions/54805497/how-do-i-mock-a-list-of-key-value-pairs-in-angular-which-does-not-have-indices,"['javascript', 'java', 'angular', 'spring-boot', 'jasmine']",1797,True,3,1
Jest &amp; React &amp; Typescript &amp; React-Testing-Library error,"<p>I have a React/NextJS project setup using Typescript and am adding unit testing with Jest and React Testing Library.</p>

<p>A unit test for my component looks like this:</p>

<pre><code>import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { render } from '@testing-library/react';

import AppLayout from '.';

describe('&lt;AppLayout&gt;', () =&gt; {
  it('renders children', () =&gt; {
    const children = 'Test';
    const props = { pathname: '/' };
    const component = &lt;AppLayout {...props}&gt;{children}&lt;/AppLayout&gt;;
    const { getByText } = render(component);
    expect(getByText(children)).toBeInTheDocument();
  });
});
</code></pre>

<p>This throws the following error:</p>

<pre><code>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"".
</code></pre>

<p>Here's some key files in my project to help:</p>

<p><strong>.babelrc</strong></p>

<pre><code>{
  ""env"": {
    ""development"": {
      ""presets"": [""next/babel""],
      ""plugins"": [""babel-plugin-styled-components""]
    },
    ""production"": {
      ""presets"": [""next/babel""],
      ""plugins"": [
        ""@babel/plugin-transform-react-inline-elements"",
        [""babel-plugin-styled-components"", { ""displayName"": false }]
      ]
    }
  }
}
</code></pre>

<p><strong>tsconfig.js</strong></p>

<pre><code>{
  ""compilerOptions"": {
    ""allowJs"": true,
    ""allowSyntheticDefaultImports"": true,
    ""alwaysStrict"": true,
    ""esModuleInterop"": true,
    ""forceConsistentCasingInFileNames"": true,
    ""jsx"": ""preserve"",
    ""isolatedModules"": true,
    ""lib"": [
      ""dom"",
      ""es2017""
    ],
    ""module"": ""esnext"",
    ""moduleResolution"": ""node"",
    ""noEmit"": true,
    ""noFallthroughCasesInSwitch"": true,
    ""noImplicitReturns"": true,
    ""noUnusedLocals"": true,
    ""noUnusedParameters"": true,
    ""removeComments"": true,
    ""resolveJsonModule"": true,
    ""skipLibCheck"": true,
    ""sourceMap"": true,
    ""strict"": true,
    ""target"": ""esnext""
  },
  ""exclude"": [
    "".next"",
    ""node_modules""
  ]
}
</code></pre>

<p><strong>jest.config.js</strong></p>

<pre><code>module.exports = {
  roots: ['./'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
};
</code></pre>

<p>My project compiles and runs fine but I'm guessing there's some configuration issue I need to fix to get my unit tests running correctly. Any ideas?</p>
",https://stackoverflow.com/questions/58365634/jest-react-typescript-react-testing-library-error,"['javascript', 'reactjs', 'typescript', 'unit-testing', 'jestjs']",2085,True,0,1
Flask where to read csv data for use in views,"<p>I'm wondering where the read_csv method should live, in order for it to be accessible by the views in flask, and for optimum unit testing. Ideally for unit tests, I assume I wouldn't want to read the CSV data, so it should be easily mockable?</p>

<p>I'm currently importing data after creating the application, before the views. The views are then accessing the dataframe. Should this be handled elsewhere?</p>

<p>Currently set up like:</p>

<pre><code>application = Flask(__name__)

df = pd.read_csv(filename)

# views below...

</code></pre>
",https://stackoverflow.com/questions/56613310/flask-where-to-read-csv-data-for-use-in-views,"['python', 'flask']",56,True,-1,1
Firebase stub transaction,"<p>I am trying to stub a transaction over real time database table.The transaction is inside a function called by a trigger (non HTTP). I can fire the trigger, but I'm not able to stub transaction like this:</p>

<pre><code>var codeRef = admin.database().ref('last_code')
return codeRef.transaction(function (currentCode) {
    return currentCode + 1
})
    .then(result =&gt; {
        const {error, committed, snapshot} = result
        return snapshot.val()
    })
</code></pre>

<p>I am using stub Sinon with mocha <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">Unit testing of Cloud Functions</a>. This is the way I tried:</p>

<pre><code>const test = require('firebase-functions-test')();
adminInitStub = sinon.stub(admin, 'initializeApp');
// Now we can require index.js and save the exports inside a namespace called myFunctions.
myFunctions = require('../index');
const refParam = 'last_code';
const databaseStub = sinon.stub();
const refStub = sinon.stub();
const transactionStub = sinon.stub();
Object.defineProperty(admin, 'database', { get: () =&gt; databaseStub });
databaseStub.returns({ ref: refStub });
refStub.withArgs(refParam).returns({transaction: function(code) =&gt; ({committed: true, snapshot: 999});
</code></pre>

<p>But stub transaction fails. I am sure that last line is incorrect, but don't see the solution.</p>
",https://stackoverflow.com/questions/58196943/firebase-stub-transaction,"['firebase', 'firebase-realtime-database', 'sinon', 'stubbing']",174,True,0,1
"How to create “FTPS” Mock Server for unit test in Java, Getting Error - javax.net.ssl.SSLException: 502 Command not implemented: AUTH","<p>I need to mock ""FTPS"" server as part of unit testing. I am getting ""javax.net.ssl.SSLException: 502 Command not implemented: AUTH"" via using mock FTPS Server.</p>

<p>I went through <a href=""http://mockftpserver.sourceforge.net/"" rel=""nofollow noreferrer"">http://mockftpserver.sourceforge.net/</a> and <a href=""https://stackoverflow.com/questions/14042033/how-to-create-a-ftps-mock-server-to-unit-test-file-transfer-in-java"">How to create a &quot;FTPS&quot; Mock Server to unit test File Transfer in Java</a> but didn't find a way to connect as FTPS server. </p>

<pre class=""lang-java prettyprint-override""><code>import java.io.File;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPSClient;
import org.mockftpserver.fake.FakeFtpServer;
import org.mockftpserver.fake.UserAccount;

public class FtpsMockTest {
    private FakeFtpServer fakeFtpServer;

    public FtpsMockTest(int port, String userName, String password, File homeDir){
        fakeFtpServer = new FakeFtpServer();
        fakeFtpServer.setServerControlPort(port);
        fakeFtpServer.addUserAccount(new UserAccount(userName, password, homeDir.getAbsolutePath()));
    }

    public static FTPSClient createFtpsClient(String hostname, Integer port, String username, String password)
            throws Exception {

        FTPSClient ftpsClient = new FTPSClient(""TLS"", false);

        ftpsClient.connect(hostname, port);
        ftpsClient.enterLocalPassiveMode();

        boolean loginStatus = ftpsClient.login(username, password);
        if (!loginStatus) {
            throw new Exception(""FTPS client login failed."");
        }

        ftpsClient.execPBSZ(0);
        ftpsClient.execPROT(""P"");
        ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpsClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);

        return ftpsClient;
    }

    public static void main(String[] args) throws Exception {
        FtpsMockTest test = null;
        try {
            test = new FtpsMockTest(990, ""test"", ""test"", new File(""C:\\FuncTest""));
            test.start();

            FTPSClient ftpsClient = createFtpsClient(""127.0.0.1"", 990, ""test"", ""test"");
            FTPFile[] listFiles = ftpsClient.listFiles(""C:/Test"");
            System.out.println(""*** total available files ***"" + listFiles.length);
        }finally {
            test.stop();
        }
    }

    public void start(){
        fakeFtpServer.start();
        System.out.println(""**** FAKE FTPS Server Started ***"");
    }

    public void stop(){
        fakeFtpServer.stop();
        System.out.println(""**** FAKE FTPS Server Stopped ***"");
    }
}
</code></pre>

<p>I used above code to connect FTPS server, but i am getting below error. Could you please provide any input to solve below error.</p>

<pre><code>Exception in thread ""main"" javax.net.ssl.SSLException: 502 Command not implemented: AUTH.

    at org.apache.commons.net.ftp.FTPSClient.execAUTH(FTPSClient.java:214)
    at org.apache.commons.net.ftp.FTPSClient._connectAction_(FTPSClient.java:196)
    at org.apache.commons.net.SocketClient.connect(SocketClient.java:164)
    at org.apache.commons.net.SocketClient.connect(SocketClient.java:184)
    at com.asos.mule.core.connector.ftps.functional.FtpsMockTest.createFtpsClient(FtpsMockTest.java:25)
    at com.asos.mule.core.connector.ftps.functional.FtpsMockTest.main(FtpsMockTest.java:47)
</code></pre>
",https://stackoverflow.com/questions/57359102/how-to-create-ftps-mock-server-for-unit-test-in-java-getting-error-javax-ne,"['java', 'mocking', 'ftps', 'apache-commons-net']",1251,True,3,1
Javascript issue when using let,"<p>I have the below js for unit testing an error handler:</p>

<pre><code>import assert from 'assert';
import deepClone from 'lodash.clonedeep';
import deepEqual from 'lodash.isequal';
import { spy } from 'sinon';
import errorHandler from './index';

function getValidError(constructor = SyntaxError) {
  let error = new constructor();
  error.status = 400;
  error.body = {};
  error.type = 'entity.parse.failed';
  return error;
}

describe('errorHandler', function() {
  let err;
  let req;
  let res;
  let next;
  let clonedRes;
  describe('When the error is not an instance of SyntaxError', function() {
    err = getValidError(Error);
    req = {};
    res = {};
    next = spy();
    clonedRes = deepClone(res);
    errorHandler(err, req, res, next);

    it('should not modify res', function() {
      assert(deepEqual(res, clonedRes));
    });

    it('should call next()', function() {
      assert(next.calledOnce);
    });
  });

  ...(#other test cases all similar to the first)

  describe('When the error is a SyntaxError, with a 400 status, has a `body` property set, and has type `entity.parse.failed`', function() {
    err = getValidError();
    req = {};
    let res = {
      status: spy(),
      set: spy(),
      json: spy()
    };
    let next = spy();
    errorHandler(err, req, res, next);

    it('should set res with a 400 status code', function() {
      assert(res.status.calledOnce);
      assert(res.status.calledWithExactly(400));
    });

    it('should set res with an application/json content-type header', function() {
      assert(res.set.calledOnce);
      assert(res.set.calledWithExactly('Content-Type', 'application/json'));
    });

    it('should set res.json with error code', function() {
      assert(res.json.calledOnce);
      assert(res.json.calledWithExactly({ message: 'Payload should be in JSON format' }));
    });
  });
});
</code></pre>

<p>Notice that I have <code>let</code> in front of <code>res</code>, <code>next</code> and <code>clonedRes</code> in the describe block for 'When the error is a SyntaxError...'.</p>

<p>Without the <code>let</code> in front of these, I get failures in my tests. I do not understand why I need to add the <code>let</code> for these again, but not for the <code>err</code> and <code>req</code> in that same block. Could anyone help me out with an explanation?</p>
",https://stackoverflow.com/questions/54975647/javascript-issue-when-using-let,"['javascript', 'unit-testing', 'let']",1848,True,0,1
Firebase stub transaction,"<p>I am trying to stub a transaction over real time database table.The transaction is inside a function called by a trigger (non HTTP). I can fire the trigger, but I'm not able to stub transaction like this:</p>

<pre><code>var codeRef = admin.database().ref('last_code')
return codeRef.transaction(function (currentCode) {
    return currentCode + 1
})
    .then(result =&gt; {
        const {error, committed, snapshot} = result
        return snapshot.val()
    })
</code></pre>

<p>I am using stub Sinon with mocha <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">Unit testing of Cloud Functions</a>. This is the way I tried:</p>

<pre><code>const test = require('firebase-functions-test')();
adminInitStub = sinon.stub(admin, 'initializeApp');
// Now we can require index.js and save the exports inside a namespace called myFunctions.
myFunctions = require('../index');
const refParam = 'last_code';
const databaseStub = sinon.stub();
const refStub = sinon.stub();
const transactionStub = sinon.stub();
Object.defineProperty(admin, 'database', { get: () =&gt; databaseStub });
databaseStub.returns({ ref: refStub });
refStub.withArgs(refParam).returns({transaction: function(code) =&gt; ({committed: true, snapshot: 999});
</code></pre>

<p>But stub transaction fails. I am sure that last line is incorrect, but don't see the solution.</p>
",https://stackoverflow.com/questions/58196943/firebase-stub-transaction,"['firebase', 'firebase-realtime-database', 'sinon', 'stubbing']",174,True,0,1
Javascript issue when using let,"<p>I have the below js for unit testing an error handler:</p>

<pre><code>import assert from 'assert';
import deepClone from 'lodash.clonedeep';
import deepEqual from 'lodash.isequal';
import { spy } from 'sinon';
import errorHandler from './index';

function getValidError(constructor = SyntaxError) {
  let error = new constructor();
  error.status = 400;
  error.body = {};
  error.type = 'entity.parse.failed';
  return error;
}

describe('errorHandler', function() {
  let err;
  let req;
  let res;
  let next;
  let clonedRes;
  describe('When the error is not an instance of SyntaxError', function() {
    err = getValidError(Error);
    req = {};
    res = {};
    next = spy();
    clonedRes = deepClone(res);
    errorHandler(err, req, res, next);

    it('should not modify res', function() {
      assert(deepEqual(res, clonedRes));
    });

    it('should call next()', function() {
      assert(next.calledOnce);
    });
  });

  ...(#other test cases all similar to the first)

  describe('When the error is a SyntaxError, with a 400 status, has a `body` property set, and has type `entity.parse.failed`', function() {
    err = getValidError();
    req = {};
    let res = {
      status: spy(),
      set: spy(),
      json: spy()
    };
    let next = spy();
    errorHandler(err, req, res, next);

    it('should set res with a 400 status code', function() {
      assert(res.status.calledOnce);
      assert(res.status.calledWithExactly(400));
    });

    it('should set res with an application/json content-type header', function() {
      assert(res.set.calledOnce);
      assert(res.set.calledWithExactly('Content-Type', 'application/json'));
    });

    it('should set res.json with error code', function() {
      assert(res.json.calledOnce);
      assert(res.json.calledWithExactly({ message: 'Payload should be in JSON format' }));
    });
  });
});
</code></pre>

<p>Notice that I have <code>let</code> in front of <code>res</code>, <code>next</code> and <code>clonedRes</code> in the describe block for 'When the error is a SyntaxError...'.</p>

<p>Without the <code>let</code> in front of these, I get failures in my tests. I do not understand why I need to add the <code>let</code> for these again, but not for the <code>err</code> and <code>req</code> in that same block. Could anyone help me out with an explanation?</p>
",https://stackoverflow.com/questions/54975647/javascript-issue-when-using-let,"['javascript', 'unit-testing', 'let']",1848,True,0,1
Jest Testing for React components,"<p>Hello below I have my navigation component</p>

<pre><code>class Nav extends Component {
constructor(props){
    super(props);
    this.state = {
        anchorEl: null,
        layoutMode: 'desktop',
        value: tabs.findIndex(tab =&gt; {return tab.href === this.props.router.pathname; })
    };
}

render() {
    const { classes, authenticated, user } = this.props;
    const { anchorEl, value } = this.state;
    const open = Boolean(anchorEl);
    let firstLetter;
    if (user) {
        firstLetter = user.email.charAt(0);
    }
    return (
        &lt;AppBar className={classes.appBar} position=""static""&gt;
            &lt;Toolbar className={classes.toolbar}&gt;
                &lt;img src=""/static/images/Bluelight_Header_Bitmap.jpg"" alt=""blpd logo"" className = {classes.logo}/&gt;
                {authenticated &amp;&amp; this.state.layoutMode ==='desktop' ? (
                    &lt;Grid container
                        direction =""row""
                        justify=""flex-end""
                        alignItems=""center""&gt;
                        &lt;div&gt;
                            &lt;Tabs id=""Tab"" value={value} onChange={this.handleChange}&gt;
                                {tabs.map(tab =&gt; {
                                    return (&lt;LinkTab key={tab.href} classes={{ root: this.props.classes.tabRoot }} label={tab.label} alt={tab.label} href={tab.href}/&gt;);})}
                            &lt;/Tabs&gt;
                        &lt;/div&gt;
                    &lt;/Grid&gt;
                ) : (
                    authenticated &amp;&amp; &lt;BurgerMenu/&gt;
                )}
                &lt;div style={{ marginLeft: 'auto' }}&gt;
                    &lt;IconButton
                        aria-owns={open ? 'menu-appbar' : undefined}
                        aria-haspopup=""true""
                        onClick={this.handleMenu}
                        color=""inherit""
                        alt=""Icon Button""
                        aria-label=""Login Button""
                        style={{margin: '5px'}}
                    &gt;
                        {!authenticated ? &lt;div&gt;&lt;/div&gt; :
                            &lt;AccountCircle/&gt;
                        }
                    &lt;/IconButton&gt;
                    &lt;Menu
                        id=""menu-appbar""
                        anchorEl={anchorEl}
                        anchorOrigin={{
                            vertical: 'top',
                            horizontal: 'right',
                        }}
                        transformOrigin={{
                            vertical: 'top',
                            horizontal: 'right',
                        }}
                        open={open}
                        onClose={this.handleClose}
                    &gt;
                        {user &amp;&amp; &lt;MenuItem divider={true}&gt;
                            &lt;CardHeader
                                titleTypographyProps={{ variant:'title' }}
                                subheaderTypographyProps={{ variant:'body2' }}
                                avatar={&lt;Avatar&gt;{firstLetter}&lt;/Avatar&gt;}
                                title={user.email}
                                subheader={user.email}

                            /&gt;
                        &lt;/MenuItem&gt;}
                        &lt;MenuItem onClick={this.handleClose}&gt;Profile&lt;/MenuItem&gt;
                        &lt;MenuItem onClick={this.handleClose}&gt;My account&lt;/MenuItem&gt;
                        {authenticated?
                            &lt;a href='/auth/logout'&gt;&lt;MenuItem&gt;Logout&lt;/MenuItem&gt;&lt;/a&gt;:
                            &lt;a href='/auth'&gt;&lt;MenuItem&gt;Login&lt;/MenuItem&gt;&lt;/a&gt;
                        }
                    &lt;/Menu&gt;
                &lt;/div&gt;
            &lt;/Toolbar&gt;
        &lt;/AppBar&gt;
    );    }}
</code></pre>

<p>I need to test this component, within my nav.test.js file i have the following code</p>

<pre><code>describe('NavBar', () =&gt; {
  const intialState = {
    ui: { width: 1361 },
    auth: { authenticated: true }
  };

  let container;
  beforeEach(() =&gt; {
    container = mount(&lt;Nav /&gt;);
  });

  it('should contain an AppBar', () =&gt; {
    expect(container.find(AppBar)).toHaveLength(1);
  });
});
</code></pre>

<p>However when running my tests i receive the following error <a href=""https://i.stack.imgur.com/I5G35.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/I5G35.png"" alt=""enter image description here""></a></p>

<p>Can anyone see where i am going wrong? I have tried to find the problem by reading documentation with Jest and mount seems to be the best option, however i am new to unit testing so this could be wrong. Thankyou </p>
",https://stackoverflow.com/questions/55224144/jest-testing-for-react-components,"['javascript', 'reactjs', 'jestjs', 'enzyme', 'mount']",1151,False,0,2
How to mock with JestJS injected dependency in class ES6?,"<p>I'm trying to get some dependance inversion going in a small NodeJS project. I want to have mocked instances of personal classes that I can inject in other classes.</p>

<p>This is for the lates node and jest version, I have read Jest documentation and nothing seem to be what I'm looking for.</p>

<pre><code>class A {

    getStr(): string {
        return ""bob"";
    }
}

class B {
    private a: A;

    constructor(a: A){
        this.a = a;
    }

    getA(): string {
        return a.getStr();
    }
}

const b = new B(mocked instance of A)
</code></pre>

<p>I expect to be able to interact with the injected mock and see if it's been called in unit testing.</p>
",https://stackoverflow.com/questions/56796866/how-to-mock-with-jestjs-injected-dependency-in-class-es6,"['node.js', 'mocking', 'jestjs']",56,True,0,1
VSCode - Php unit test?,"<p>I'm making a test.php and trying to unit test this.</p>
<p>It's my first time ever unit testing in VSCode in PHP.</p>
<p>My code looks like:</p>
<pre class=""lang-php prettyprint-override""><code>&lt;?php
    
    class TestCase extends PHPUnit\Framework\TestCase
    {
        public function test(){
            $this-&gt;assertTrue(false);
        }
    
        public function test1(){
            $this-&gt;assertTrue(true);
        }
    }
</code></pre>
<p>But when I hover the TestCase and press (F1) and choose (Better PHPUnit: Run), its saying &quot;No task to run found. Configure Tasks...&quot;</p>
<p>Image 1:<br />
<a href=""https://i.stack.imgur.com/JYD7I.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/JYD7I.png"" alt=""enter image description here"" /></a></p>
<p>Image 2:<br />
<a href=""https://i.stack.imgur.com/K6FxI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/K6FxI.png"" alt=""enter image description here"" /></a></p>
<p>If I'm supposed to add a Task... Which one should I choose and how do I navigate it to my test.php?</p>
",https://stackoverflow.com/questions/59397659/vscode-php-unit-test,"['php', 'phpunit']",554,False,0,1
How do I write simple test to check the behaviour of MatDialog in Angular 2?,"<p>I have the following component:</p>

<pre><code>@Component({
  selector: 'my-form',
  templateUrl: './my-form.component.html',
})
export class MyFormComponent implements OnInit {

  @Input('company') company: CompanyInfo;
  private config: ConfigInterface | null;

  constructor(private companyService: CompanyService, private something: Something, private dialog: MatDialog) {
  }
  ngOnInit() {
    ....
  }

  theMtehodWhichIWantToTest(company: string) {
    if (someTest.indexOf(domain)) {
      this.dialog.open(MyAllertComponent, {
        data: {
          title: 'blah',
        },
      });
    }
  }
}
</code></pre>

<p>My poor and failing unit test:</p>

<pre><code>describe( 'MyFormComp', () =&gt; {
  it('should open MatDialog if email is from popular domain', () =&gt; {
    const dialog = {} as MatDialog;
    const comp = new MyComponent({} as CompanyService, {} as Something, dialog);
    comp.getCompanys(company);
    expect(dialog.open(AlertComponent));
  });
})
</code></pre>

<p>The error message: <code>TypeError: dialog.open is not a function</code></p>

<p>Yes, I know why I have this error message - I am not mocking the dialog correctly and the functon <code>open</code> is not available. Can someone tell me how to make <code>open</code> available using <a href=""https://jasmine.github.io/pages/docs_home.html"" rel=""nofollow noreferrer"">jasmine</a> (I.e. how to properly mock MatDialog?)</p>

<p>I am quite new to js unit testing so, just telling me what to google will not be very helpful for me.</p>
",https://stackoverflow.com/questions/54146188/how-do-i-write-simple-test-to-check-the-behaviour-of-matdialog-in-angular-2,"['javascript', 'angular', 'typescript', 'unit-testing', 'jasmine']",2306,True,0,1
Why isn&#39;t store.dispatch() getting called in the subscribe block?,"<p>So I have a MatDialog Box which on close sends some form values. I then dispatch an action in the afterClosed method provided by MatDialogRef.</p>

<p>This works quite alright when I manually test it. But while unit testing, the dispatch isn't called and my test fails.</p>

<p>My Code that runs when opening the dialog &amp; dispatches the action when closed.</p>

<pre><code>openAddUserDialog() {
     this.addUserDialog = this.dialog.open(AddUserDialogComponent, {
      width: 'max-content',
      height: 'max-content',
      minWidth: '35vw',
      minHeight: '20vh',
      autoFocus: false
    });

     this.addUserDialog.afterClosed().subscribe(result =&gt; {
      console.log(result);
      this.store.dispatch({type: UserActions.ActionTypes.TryAddUser, payload: result.value});
    });
  }
</code></pre>

<p>The Mock for MatDialog</p>

<pre><code>export class MatDialogMock {
  open() {
    return {
      afterClosed: () =&gt; of(initialValue)
    };
  }
}
</code></pre>

<p>TestBed Config</p>

<pre><code> beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [MaterialModule, ReactiveFormsModule, BrowserAnimationsModule],
      declarations: [ UserManagementDialogComponent ],
      providers: [{provide: MatDialog, useClass: MatDialogMock}, provideMockStore({initialState})]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(UserManagementDialogComponent);
    component = fixture.componentInstance;

    store = TestBed.get(Store);
    spyOn(store, 'dispatch').and.callThrough();
    dialog = TestBed.get(MatDialog);

    fixture.detectChanges();
  });
</code></pre>

<p>And the test that should pass</p>

<pre><code>it('should dispatch an action when the form is submitted', fakeAsync(() =&gt; {

    spyOn(dialog, 'open').and.callThrough();
    const dialogRef = dialog.open();

    dialogRef.afterClosed().subscribe(result =&gt; {
      console.log('verbrberbhyn', result);
      expect(result).toEqual(initialValue);

      tick();

      expect(store.dispatch).toHaveBeenCalledTimes(1);
      expect(store.dispatch).toHaveBeenCalledWith({
        type: UserAtions.ActionTypes.TryAddUser,
        payload: initialValue
      });
    });
  }));
</code></pre>
",https://stackoverflow.com/questions/55271487/why-isnt-store-dispatch-getting-called-in-the-subscribe-block,"['angular', 'jasmine', 'angular-material2', 'ngrx', 'ngrx-store-4.0']",395,True,0,1
Unit testing if text == null,"<p>I am doing some unit tests with microsoft unit testing</p>

<p>I have this piece of code:</p>

<pre><code>public void AddComment(Case c, string text)
        {
            if (text == null)
            {
                return;
            }

            var comment = UnitOfWork.GetRepository&lt;CaseComment&gt;().Create();

            comment.Case = c;
            comment.Account = _userInfoProvider.UserName;
            comment.DateUtc = DateTimeHelper.UtcNow();
            comment.Text = text;

            UnitOfWork.GetRepository&lt;CaseComment&gt;().Insert(comment);
        }
</code></pre>

<p>And I have a Unit test for this piece of cdoe:</p>

<pre><code> if (text == null)
            {
                return;
            }
</code></pre>

<p>I the unit test like this:</p>

<pre><code> [TestMethod]
        public void BaseProcess_Should_AddCommentIfNull()
        {
            string text = null;

            var result = string.IsNullOrEmpty(text);

            Assert.AreEqual(text, null);

        }
</code></pre>

<p>It shows green. But the code coverage is still yellow and not blue.</p>

<p>Thank you</p>

<p>I have it now like this:</p>

<pre><code> [TestMethod]
        public void BaseProcess_Should_AddCommentIfNull()
        {
            string comment = ""Comment"";
            var newInstance = new Case
            {

                Reference = comment,                
                DateSubmitted = DateTime.Now,                      
                Status = CaseStatus.Submitted,
            };          

            string text = null;

            var result = string.IsNullOrEmpty(text);
            Action act = () =&gt; CorrectionRequestCaseProcess.AddComment(newInstance, comment);

            Assert.AreEqual(text, null);

        }
</code></pre>

<p>But if I do it like this:</p>

<pre><code> [TestMethod]
        public void BaseProcess_Should_AddCommentIfNull()
        {
            string comment = """";
            var newInstance = new Case
            {

                Reference = comment,                
                DateSubmitted = DateTime.Now,                      
                Status = CaseStatus.Submitted,
            };          

            string text = null;

            var result = string.IsNullOrEmpty(text);
            Action act = () =&gt; CorrectionRequestCaseProcess.AddComment(newInstance, text);

            Assert.AreEqual(text, null);

        }
</code></pre>

<p>Nothing changed<code>enter code here</code></p>

<p>And I wrote a other unit test like this:</p>

<pre><code>[TestMethod]
public void BaseProcess_should_equalToNull()
{
    string comment = ""Comment"";
    var newInstance = new Case
    {

        Reference = comment,
        DateSubmitted = DateTime.Now,
        Status = CaseStatus.Submitted,
    };

    var newComment = new CaseComment();
    newComment.Case = newInstance;
    newComment.Account = _userInfoProvider.UserName;
    newComment.DateUtc = DateTimeHelper.UtcNow();
    newComment.Text = comment;

    var comment2 = _testUnitOfWork.GetRepository&lt;CaseComment&gt;().Create();
    _testUnitOfWork.GetRepository&lt;CaseComment&gt;().Insert(newComment);
}
</code></pre>
",https://stackoverflow.com/questions/54590723/unit-testing-if-text-null,"['c#', 'unit-testing']",1432,False,0,1
How to stub dependencies in unit tests when using TypeScript and Sinon,"<p>I am using TypeScript to build a Koa REST API and I'm using a dependency injection library called Awilix to make unit testing simpler.</p>

<p>If I wasn't using TypeScript, I would write my unit tests thus:</p>

<pre class=""lang-js prettyprint-override""><code>  // setup
  const userService = {
    getUserById: sinon.stub(),
  };
  const userController = factory(userService);

  // example test
  it('works', () =&gt; {
    userController();
    expect(userService.getUserById).to.have.been.called();
  });
</code></pre>

<p>As the userService interface has more methods than just <code>getUserById</code> though, when you use TypeScript, I get errors like:</p>

<p><code>Property 'insert' is missing in type '{ getUserById: SinonStub&lt;any[], any&gt;; }' but required in type 'UserServiceInterface'.</code></p>

<p>Is there a way of getting around this without having to stub out every single method of a dependency? </p>

<p>Thanks</p>
",https://stackoverflow.com/questions/57716288/how-to-stub-dependencies-in-unit-tests-when-using-typescript-and-sinon,"['typescript', 'dependency-injection', 'mocha.js', 'tdd', 'sinon']",612,False,0,1
Integration testing DAO INSERT statement,"<p>I need to perform an integration test for an INSERT statement.<br>
Basically, I want an automated test that ensures that the SQL written in that query is in fact correct.<br>
I'm not sure on how to write this integration test.  </p>

<p>You need to take into account the following thoughts:  </p>

<ul>
<li>The method performs a fire-and-forget type INSERT, so unit testing it is IMO not useful.  </li>
<li>I cannot write a findById method, because the record doesn't have an ID. An id is useless in my case, because these records will never be retrieved by id. Moreover, this would cause a chicken-and-egg problem because either findById or insert statements may be wrong.    </li>
</ul>

<p>I've seen a bunch of posts that immediately start about discussing unit testing. I don't want to unit test this, I want to write an integration test that ensures my SQL query is correct.  </p>

<p>I am not looking for specific code, I am looking for the correct conceptual way to test my sql query performed in the code (in my case it happens to be Java).<br>
Could you give me some advice?  </p>

<p>Code: </p>

<pre><code>public void insertPostStat(PostStat postStat) {
    final String sql = ""INSERT INTO post_stat(created_at, geom, google_place_id, google_place_name) "" +
            ""VALUES(?, ST_SetSRID(ST_MakePoint(? , ? ), 4326), ?, ?"";

    KeyHolder holder = new GeneratedKeyHolder();
    SqlParameterSource param = new MapSqlParameterSource()
            .addValue(""created_at"", postStat.getCreatedAtMs())
            .addValue(""longitude"", postStat.getLongitude())
            .addValue(""latitude"", postStat.getLatitutde())
            .addValue(""google_place_id"", postStat.getGooglePlaceId())
            .addValue(""google_place_name"", postStat.getGooglePlaceName());
    template.update(sql,param, holder);
}
</code></pre>
",https://stackoverflow.com/questions/54873130/integration-testing-dao-insert-statement,"['java', 'integration-testing']",756,True,1,1
with Googletest i am not able to mock system function,"<p>I am trying to mock the system fun ioctl and socket but it is always calling the original definition of system function. Here is the gtest code i have written using gmock.</p>

<p>Please go through the code and help me find what is wrong.
Is there a way to mock the system functions using gmock in unit testing. If any please provide me with an example code that mocks system function.</p>

<p>In the test.hpp file</p>

<pre><code>class SystemFun
{
    public:
        virtual ~SystemFun() {}
        virtual int ioctl(int inetSocket, int counters, struct ifreq *device) = 0;
        virtual int socket(int domain, int type, int protocol) = 0;
};

class SystemFunMock : public SystemFun
{
    private:
        static SystemFunMock *oSystemFunMockInstance;
        static bool instanceFlag;
    public:
        virtual ~SystemFunMock() { instanceFlag = false; }
        MOCK_METHOD3(ioctl, int(int inetSocket, int counters ,struct ifreq *device));
        MOCK_METHOD3(socket, int(int domain, int type, int protocol));
        static SystemFunMock *getInstance()
        {
            if (!instanceFlag)
            {
                oSystemFunMockInstance = new SystemFunMock();
                instanceFlag = true;
            }
            return oSystemFunMockInstance;
        }
};

In the test.cpp file the code
bool SystemFunMock::instanceFlag = false;
SystemFunMock* SystemFunMock::oSystemFunMockInstance = NULL;

int socket(int domain, int type, int protocol)
{
    SystemFunMock* oSystemFunMock = SystemFunMock::getInstance();
    return oSystemFunMock-&gt;socket(domain, type, protocol);
}
int ioctl(int inetSocket, int counters, struct ifreq *device)
{
    SystemFunMock* oSystemFunMock = SystemFunMock::getInstance();
    return oSystemFunMock-&gt;ioctl(inetSocket, counters, device);
}

TEST_F(EtherPortUT, linuxHalCommonTest)    
{
    SetUp();    
    SystemFunMock* oSystemFunMock = SystemFunMock::getInstance();    
    {    
        InSequence s;    
        EXPECT_CALL(*oSystemFunMock, ioctl(_,_,_))
            .WillOnce(Return(0))
            .WillOnce(Return(-1));
        EXPECT_CALL(*oSystemFunMock, socket(_,_,_))
            .WillOnce(Return(-1));
    }
.....
pLNXNetIface-&gt;getLinkSpeed( 356,  &amp;speed ); // this fun def has 2 ioctl     calls but calling the original function.
pLNXNetIface-&gt;watchNetLink( iPort ); // this fun def has socket call.
...

}

Definition of the functions getLinkSpeed
bool LinuxNetworkInterface::getLinkSpeed( int sd, uint32_t *speed )
{
     struct ifreq ifr;
     struct ethtool_cmd edata;
     ifr.ifr_ifindex = ifindex;
     if( ioctl( sd, SIOCGIFNAME, &amp;ifr ) == -1 )
     {
          GPTP_LOG_ERROR
               ( ""%s: SIOCGIFNAME failed: %s"", __PRETTY_FUNCTION__,
                 strerror( errno ));
          return false;
     }
     ifr.ifr_data = (char *) &amp;edata;
     edata.cmd = ETHTOOL_GSET;
     if( ioctl( sd, SIOCETHTOOL, &amp;ifr ) == -1 )
     {
          GPTP_LOG_ERROR
               ( ""%s: SIOCETHTOOL failed: %s"", __PRETTY_FUNCTION__,
                 strerror( errno ));
          return false;
     }
...
}
</code></pre>
",https://stackoverflow.com/questions/57950808/with-googletest-i-am-not-able-to-mock-system-function,"['unit-testing', 'googletest', 'googlemock']",1061,True,0,1
How to write inner class test method in Python with Unittest,"<p>In Java when doing unit testing it is common to have a test class that contains multiple inner classes for each method of the class to test. Each inner class can have multiple testing methods to test a specific functionality of the related method.</p>

<p>I am trying to do the same thing in Python with unittest, but it seems that the inner classes' methods are not executed. For example:</p>

<pre><code>import unittest

class OuterTestClass(unittest.TestCase):

    print(""start outer class"")

    def test_should_do_something(self):

            self.assertTrue( True )

            print(""outer method test completed"")

    class InnerTestClass(unittest.TestCase):

        print(""start inner class"")

        def test_should_do_something(self):

            self.assertTrue( True )

            print(""inner method test completed"")


</code></pre>

<p>Expected behavior:</p>

<pre><code>&gt; start outer class
&gt; start inner class
&gt; inner method test completed
&gt; outer method test completed
</code></pre>

<p>Actual behavior:</p>

<pre><code>&gt; start outer class
&gt; start inner class
&gt; outer method test completed
</code></pre>

<p>Is it possible to execute the inner class methods as well with unittest ?</p>
",https://stackoverflow.com/questions/56140684/how-to-write-inner-class-test-method-in-python-with-unittest,"['python', 'tdd', 'inner-classes', 'python-unittest']",3737,True,8,1
Debbuger of Vue.js TypeScript project with WebStorm doesn&#39;t stop at break point,"<p>I created new project with WebStorm with TypeScript setting. Then, debugger break point doesn't work.</p>

<h1>My settings</h1>

<h1>Version</h1>

<ul>
<li>node 12.10</li>
<li>vue/cli 3.11.0</li>
</ul>

<h1>Project setting</h1>

<ol>
<li>Babel</li>
<li>TypeScript</li>
<li>Router</li>
<li>CSS Pre-processors</li>
<li>Unit Testing</li>
</ol>

<h1>Build setting</h1>

<ol>
<li>Class Style Syntax => Yes</li>
<li>User Babel alongside Typescript => Yes</li>
<li>Use historymode => No</li>
<li>Css Pre proccessor: Sass/Scss dart-sass</li>
</ol>

<h1>Code</h1>

<p>Debug point is on the <code>console.log(""started"")</code></p>

<pre><code>&lt;template&gt;
  &lt;div id=""app""&gt;
    &lt;img alt=""Vue logo"" src=""./assets/logo.png""&gt;
    &lt;HelloWorld msg=""Welcome to Your Vue.js + TypeScript App""/&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script lang=""ts""&gt;
import { Component, Vue } from 'vue-property-decorator';
import HelloWorld from './components/HelloWorld.vue';

console.log(""satarted"")

@Component({
  components: {
    HelloWorld,
},
})
export default class App extends Vue {}
&lt;/script&gt;

&lt;style lang=""scss""&gt;
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
&lt;/style&gt;
</code></pre>

<p>Debug setting of WebStorm:</p>

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

<p>Then I click debug button, but it not stop at break point.</p>

<p><code>package.json, tsconfig.json</code> and other files are default setting.</p>
",https://stackoverflow.com/questions/59083944/debbuger-of-vue-js-typescript-project-with-webstorm-doesnt-stop-at-break-point,"['typescript', 'vue.js', 'webstorm']",2203,True,5,2
VS Code Jest and Cypress intellisense doesn&#39;t work properly with Chai,"<p>I am using Jest as unit testing framework and bellow intellisense is correct:</p>

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

<p>However, when I install Cypress <code>""cypress"": ""^3.2.0""</code>, the same code now displaying error <code>Property 'toMatch' does not exist on type 'Assertion'. Did you mean 'match'?</code>. The reason for that IMO is Cypress install typings under <code>node_modules/cypress/types/chai/index.d.ts</code> and VS Code is picking them for intellisense. Both Jest and Cypress have dependency on Chai assertion library. Intellisense after installing Cypress:
<a href=""https://i.stack.imgur.com/EdoB9.png"" rel=""noreferrer""></a></p>

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

<p>Is there a way to tell VS Code which Chai intellisense to use in specific folder? Or is there some way to specify it in <code>jsconfig.json</code> file?</p>
",https://stackoverflow.com/questions/55765616/vs-code-jest-and-cypress-intellisense-doesnt-work-properly-with-chai,"['visual-studio-code', 'jestjs', 'intellisense', 'cypress']",5126,True,5,3
ValidationError: child &quot;password&quot; fails because [&quot;password&quot; is required],"<p>ValidationError: child ""password"" fails because [""password"" is required] error is showing when run the test</p>

<p>I am using <code>hapijs</code> <code>v17.2.3</code> and <code>mongodb</code> as back-end. I am trying to perform unit testing using the <code>lab</code> and <code>code</code> .
This is my tests.js </p>

<pre><code>'use strict';

const Hapi = require('hapi');
const application = require('../app');
const Code = require('code');
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const getServer = function () {
    const server = new Hapi.Server();
    server.connection();
    return server.register(application)
        .then(() =&gt; server);
};

 ......
 ......
 ......


lab.test('Simply test the unique route', (done) =&gt; {

    const signUpData = {
        method: 'POST',
        url: '/signup',
        payload: {
            name: 'vulcan',
            password: 'vulcan@123',
            verify: 'vulcan@123',
            email: 'vulcan@gmail.com',
            username: 'vulcan',
            referredBy: 'admin@gg',
            dob: '12/08/1994'
        }
    };

    getServer()
        .then((server) =&gt; server.inject(signUpData))
        .then((response) =&gt; {

            Code.expect(response.statusCode).to.equal(200);
            const payload = JSON.parse(response.payload);
            Code.expect(payload).to.exist();

            done();
        })
        .catch(done);
});
</code></pre>

<p>when I am run the above code I got the following error </p>

<pre><code>{ ValidationError: child ""password"" fails because [""password"" is required]
    at Object.exports.process (/home/jeslin/projects/hapi/gamergully/node_modules/joi/lib/errors.js:196:19)
    at internals.Object._validateWithOptions (/home/jeslin/projects/hapi/gamergully/node_modules/joi/lib/types/any/index.js:675:31)
    at module.exports.internals.Any.root.validate (/home/jeslin/projects/hapi/gamergully/node_modules/joi/lib/index.js:146:23)
    at Object.internals.implementation [as cookie] (/home/jeslin/projects/hapi/gamergully/node_modules/hapi-auth-cookie/lib/index.js:95:25)
    at module.exports.internals.Auth._strategy (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/lib/auth.js:52:47)
    at Object.register (/home/jeslin/projects/hapi/gamergully/lib/auth.js:6:116)
    at internals.Server.register (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/lib/server.js:451:35)
    at &lt;anonymous&gt;
    at process._tickCallback (internal/process/next_tick.js:189:7)
    at Function.Module.runMain (module.js:696:11)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3
  isJoi: true,
  name: 'ValidationError',
  details:
   [ { message: '""password"" is required',
       path: [Array],
       type: 'any.required',
       context: [Object] } ],
  _object:
   { password: undefined,
     cookie: 'GG-auth',
     isSecure: false,
     clearInvalid: true,
     ttl: 86400000,
     redirectTo: '/login',
     appendNext: true,
     redirectOnTry: false,
     isSameSite: 'Lax' },
  annotate: [Function] }
</code></pre>

<p>I can't figure out what the error is and I have wasted much time for solve it</p>

<p><strong>this is my controller for signup which have all the validation with <code>joi</code></strong></p>

<pre><code>exports.postForm = {
    description: 'Submit the signup page',
    tags: ['api'],
    notes: 'accepts name password verify and email',

    auth: {
        mode: 'try',
        strategy: 'session'
    },
    validate: {
        payload: {
            name: Joi.string().required(),
            password: Joi.string().min(4).max(20).required(),
            verify: Joi.string().required(),
            email: Joi.string().email().required(),
            username: Joi.string().min(3).max(20).required(),
            referredBy: Joi.any(),
            dob: Joi.date().required().label('Date of Birth')
        },
        failAction: (request, h, error) =&gt; {
            // Boom bad request
            console.log('Validation Failed');
            request.yar.flash('error', error.details[0].message.replace(/['""]+/g, ''));
            return h.redirect('/signup').takeover();
        }
    },
    handler: async (request, h) =&gt; {
        try {

            ................

            ................

            var user = {
                name: request.payload.name,
                password: reques67t.payload.password,
                email: request.payload.email,
                username: request.payload.username,
                referralName: request.payload.username + '@gg',
                emailConfirmationToken: uuidv1(),
                dob: request.payload.dob
            };
            // Then save the user
            let data = await signupHelper.signUpUser(user, request);
            if (data.statusCode === 200) {

                if (request.payload.referredBy) {

                    request.yar.flash('success', 'Account created, Please Login');

                }
            } else {
                request.yar.flash('error', data.message);
                return h.redirect('/signup');
            }
        } catch (error) {
            console.log('error occired = ', error);

            return h.redirect('/signup');
        }
    }
};
</code></pre>
",https://stackoverflow.com/questions/54216512/validationerror-child-password-fails-because-password-is-required,"['node.js', 'chai', 'hapi.js', 'lab']",2034,True,2,1
How to identify a winforms button control that has no AutomationId?,"<p>I've been tasked to find out how to implement UI automation for desktop apps with appium-dotnet-driver. I've successfully managed to use the windows calculator app for UI unit testing.</p>

<p>That being said, having a lot of trouble with my company's winforms app because some elements either don't have an AutomationId or it changes every time something is clicked on the program.</p>

<p>Is there an easy way to define the AutomationId for a control type (i.e. Button)?</p>
",https://stackoverflow.com/questions/56057733/how-to-identify-a-winforms-button-control-that-has-no-automationid,"['c#', 'winforms', 'ui-automation']",1051,True,2,1
Workflow execution fails when a worker is restarted on the same workflow service client,"<p>We're in the process of writing a .NET Cadence client and ran into an issue while unit testing workflows.  When we start a worker, execute a workflow, stop the worker, start it again, and then try and execute another workflow, the first workflow completes, but any workflow after the first hangs during the <code>client.ExecuteWorkflow()</code> call, eventually failing with a <code>START_TO_CLOSE</code> timeout.  I replicated this behavior by munging the greetings <a href=""https://github.com/samarabbas/cadence-samples/"" rel=""nofollow noreferrer"">cadence-samples</a> workflow.  See the loop in <code>func main()</code>:</p>
<pre><code>package main

import (
    &quot;context&quot;
    &quot;time&quot;

    &quot;go.uber.org/cadence/client&quot;
    &quot;go.uber.org/cadence/worker&quot;
    &quot;go.uber.org/zap&quot;

    &quot;github.com/pborman/uuid&quot;

    &quot;github.com/samarabbas/cadence-samples/cmd/samples/common&quot;
)

// This needs to be done as part of a bootstrap step when the process starts.
// The workers are supposed to be long running.
func startWorkers(h *common.SampleHelper) worker.Worker {
    // Configure worker options.
    workerOptions := worker.Options{
        MetricsScope: h.Scope,
        Logger:       h.Logger,
    }
    return h.StartWorkers(h.Config.DomainName, ApplicationName, workerOptions)
}

func startWorkflow(h *common.SampleHelper) client.WorkflowRun {
    workflowOptions := client.StartWorkflowOptions{
        ID:                              &quot;greetings_&quot; + uuid.New(),
        TaskList:                        ApplicationName,
        ExecutionStartToCloseTimeout:    time.Minute,
        DecisionTaskStartToCloseTimeout: time.Minute,
    }
    return h.StartWorkflow(workflowOptions, SampleGreetingsWorkflow)
}

func main() {

    // setup the SampleHelper
    var h common.SampleHelper
    h.SetupServiceConfig()

    // Loop:
    //  - start a worker
    //  - start a workflow
    //  - block and wait for workflow result
    //  - stop the worker
    for i := 0; i &lt; 3; i++ {

        // start the worker
        // execute the workflow
        workflowWorker := startWorkers(&amp;h)
        workflowRun := startWorkflow(&amp;h)

        // create context
        // get workflow result
        var result string
        ctx, cancel := context.WithCancel(context.Background())
        err := workflowRun.Get(ctx, &amp;result)
        if err != nil {
            panic(err)
        }

        // log the result
        h.Logger.Info(&quot;Workflow Completed&quot;, zap.String(&quot;Result&quot;, result))

        // stop the worker
        // cancel the context
        workflowWorker.Stop()
        cancel()
    }
}
</code></pre>
<h3>This is not a blocking issue and will probably not come up in production.</h3>
<h3>Background:</h3>
<p>We (<a href=""https://stackoverflow.com/users/4807144/jeff-lill"">Jeff Lill</a> and I) noticed this issue during unit testing workflows in our .NET Cadence client.  When we run our workflow tests individually they all pass, but when we run multiple at a time (sequentially, not in parallel), we see the behavior described above.  This is because of the cleanup done in the .NET Cadence client <code>dispose()</code> method called after a test completes (pass or fail).  One of the dispose behaviors is to stop workers created during a test.  When the next test runs, new workers are created using the same workflow service client, and this is where the issue arises.</p>
",https://stackoverflow.com/questions/56694671/workflow-execution-fails-when-a-worker-is-restarted-on-the-same-workflow-service,['cadence-workflow'],2463,False,0,0
"IllegalArgumentException: Parameter specified as non-null is null: method kotlinx.coroutines.BuildersKt__Builders_commonKt.launch, parameter context","<p>I am trying to unit test the below function which uses kotlin coroutines </p>

<pre><code>fun authenticateWithUserAndPassword(usernameOrEmail: String, password: String) {
        launchUI(strategy) {   //line 76
            view.showLoading()
            try {
                val token = retryIO(""login"") {
                    when {
                        settings.isLdapAuthenticationEnabled() -&gt;
                            client.loginWithLdap(usernameOrEmail, password)
                        usernameOrEmail.isEmail() -&gt;
                            client.loginWithEmail(usernameOrEmail, password)
                        else -&gt;
                            client.login(usernameOrEmail, password)
                    }
                }
                val myself = retryIO(""me()"") { client.me() }
                myself.username?.let { username -&gt;
                    val user = User(
                        id = myself.id,
                        roles = myself.roles,
                        status = myself.status,
                        name = myself.name,
                        emails = myself.emails?.map { Email(it.address ?: """", it.verified) },
                        username = username,
                        utcOffset = myself.utcOffset
                    )
                    localRepository.saveCurrentUser(currentServer, user)
                    saveCurrentServer.save(currentServer)
                    localRepository.save(LocalRepository.CURRENT_USERNAME_KEY, username)
                    saveAccount(username)
                    saveToken(token)
                    analyticsManager.logLogin(
                        AuthenticationEvent.AuthenticationWithUserAndPassword,
                        true
                    )
                    view.saveSmartLockCredentials(usernameOrEmail, password)
                    navigator.toChatList()
                }
            } catch (exception: RocketChatException) {
                when (exception) {
                    is RocketChatTwoFactorException -&gt; {
                        navigator.toTwoFA(usernameOrEmail, password)
                    }
                    else -&gt; {
                        analyticsManager.logLogin(
                            AuthenticationEvent.AuthenticationWithUserAndPassword,
                            false
                        )
                        exception.message?.let {
                            view.showMessage(it)
                        }.ifNull {
                            view.showGenericErrorMessage()
                        }
                    }
                }
            } finally {
                view.hideLoading()
            }
        }
    }
</code></pre>

<p>here is the definition of launchUI</p>

<pre><code>fun launchUI(strategy: CancelStrategy, block: suspend CoroutineScope.() -&gt; Unit): Job =
    MainScope().launch(context = strategy.jobs, block = block)
</code></pre>

<p>here is the cancel Strategy class</p>

<pre><code>class CancelStrategy(owner: LifecycleOwner, val jobs: Job) : LifecycleObserver {

    init {
        owner.lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        jobs.cancel()
    }
}
</code></pre>

<p>I am new with unit testing with coroutines and have written a very basic test for the above function to gets some hand on coroutine testing</p>

<pre><code>   @Test
    fun authenticateUserSuccessfuly() = runBlocking {
        loginPresenter.setupView()
        loginPresenter.authenticateWithUserAndPassword(""username"", ""password"")
        verify(view).showLoading()
        verify(saveCurrentServer).save(currentServer)
    }
</code></pre>

<p>On running the test I am getting the following error If someone can suggest how to test the above function It will be a great help.</p>

<pre><code>java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlinx.coroutines.BuildersKt__Builders_commonKt.launch, parameter context

    at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt)
    at kotlinx.coroutines.BuildersKt.launch(Unknown Source)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default(Builders.common.kt:47)
    at kotlinx.coroutines.BuildersKt.launch$default(Unknown Source)
    at chat.rocket.android.util.extension.CoroutinesKt.launchUI(Coroutines.kt:15)
    at chat.rocket.android.authentication.login.presentation.LoginPresenter.authenticateWithUserAndPassword(LoginPresenter.kt:76)
    at chat.rocket.android.authentication.login.presentation.LoginPresenterTest$authenticateUserSuccessfuly$1.invokeSuspend(LoginPresenterTest.kt:101)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:233)
    at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.kt:116)
    at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:76)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:53)
    at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:35)
    at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
    at chat.rocket.android.authentication.login.presentation.LoginPresenterTest.authenticateUserSuccessfuly(LoginPresenterTest.kt:99)
    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.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/56250508/illegalargumentexception-parameter-specified-as-non-null-is-null-method-kotlin,"['android', 'unit-testing', 'kotlin', 'kotlin-coroutines']",788,False,2,0
MockWebServer: java.lang.NoSuchMethodError,"<p>Trying MockWebServer for the first time on a Groovy/Spring project that uses Spock for unit testing.</p>

<p>I added MockWebServer dependencies as directed (I had to add the second line myself to avoid errors, but it's not documented:</p>

<pre><code>testImplementation(""com.squareup.okhttp3:mockwebserver:4.0.0"")
testImplementation(""org.jetbrains.kotlin:kotlin-stdlib:1.3.40"")
</code></pre>

<p>I have a basic Spock test that looks like this:</p>

<pre><code>def 'server'() {
    setup:
    MockWebServer server = new MockWebServer()

    expect:
    server
}
</code></pre>

<p>But it fails with this output:</p>

<pre><code>java.lang.NoSuchMethodError: okhttp3.internal.Util.immutableListOf([Ljava/lang/Object;)Ljava/util/List;

    at okhttp3.mockwebserver.MockWebServer.&lt;init&gt;(MockWebServer.kt:176)
</code></pre>

<p>Is there another dependency I'm missing? Does MockWebServer not play well with Groovy and Spock?</p>

<p>For what it's worth, using version 3.1.4 seems to work:</p>

<pre><code>testImplementation(""com.squareup.okhttp3:mockwebserver:3.14.2"")
</code></pre>

<p>(I'm a first time user of MockWebServer)</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/56854548/mockwebserver-java-lang-nosuchmethoderror,"['spock', 'okhttp', 'mockwebserver']",5397,True,10,2
How do I fix Null Pointer Exception when I have already assigned value,"<p>I am writing unit testing for a function using roboelectric and facing null pointer exception but I have already assigned the variable.
I'm pretty new to this so if any mistake please pardon me.</p>

<pre><code>@Before
public void setup() {

    intent = new Intent(context, Xyz.class);
    intent.putExtra(""abc"", ""abc"");

    xyz = Robolectric.buildActivity(Xyz.class, intent)
            .create().start().get();
}

@Test
public void onConfigurationChanged() {
    int currentOrientation = xyz.getRequestedOrientation();
    RelativeLayouot gifframe = xyz.findViewById(R.id.gif_frame);
    assertNotNull(gifframe);
    assertEquals(gifframe.getVisibility(), VISIBLE);
    }
}
</code></pre>

<p>I expect thee gifframe to be able to get the visibility but gifframe is returning a null value. everywhere I searched a solution to this is to assign the value before calling it. I have assigned the value in the previous line.</p>
",https://stackoverflow.com/questions/55467271/how-do-i-fix-null-pointer-exception-when-i-have-already-assigned-value,"['java', 'android', 'unit-testing', 'robolectric']",148,False,1,2
How to create ArgumentMatchers.any(type: Class&lt;T&gt;) for testing in Kotlin?,"<p>I'm trying to unit test a class that uses the following service:</p>

<pre><code>parserService.parseJsonStringToModel(json: String, adapterClass: Class&lt;T&gt;): T?
</code></pre>

<p>My first approach was to use <code>ArgumentMatchers</code> to implement unit testing as follows:</p>

<pre><code>Mockito.`when`(parserService.parseJsonStringToModel(ArgumentMatchers.any(), ArgumentMatchers.any&lt;CreateAccountRequest&gt;().javaClass)).thenReturn(null)
</code></pre>

<p>Since <code>ArgumentMatchers.any()</code> returns <code>null</code> in Kotlin, that produces <code>NullPointerException</code> for non nullable types. So I give a try to <a href=""https://github.com/nhaarman/mockito-kotlin"" rel=""nofollow noreferrer"">Mockito-Kotlin</a> library to avoid this problem. The approach looks like following:</p>

<pre><code>whenever(parserService.parseJsonStringToModel(any(), any&lt;CreateAccountRequest&gt;().javaClass)).thenReturn(null)
</code></pre>

<p>Used library solves the problem for first argument but still produces <code>NullPointerException</code> for passed second argument.</p>

<p>So, how can I create an <code>ArgumentMatchers</code> for <code>Class&lt;T&gt;</code> type arguments?</p>
",https://stackoverflow.com/questions/56686906/how-to-create-argumentmatchers-anytype-classt-for-testing-in-kotlin,"['kotlin', 'mockito', 'mockito-kotlin']",1392,True,1,1
How to stub an instance of an object not declared in file,"<p>sorry I am a bit new to unit testing, so not sure if this will be incredibly obvious or not, I currently have this code in a strapi framework</p>

<pre><code>'use strict';
const {HOST,PORT,Bucket,cfurl} = require('../../../config/consts');
const strapi             = require('strapi');
const axios              = require('axios');
const NodeCache          = require('node-cache');
const cache              = new NodeCache();

module.exports = {
  getBanner: async (ctx) =&gt; {
    let bnr;
    if(ctx.hasOwnProperty('params') &amp;&amp; ctx.params.hasOwnProperty('_id') &amp;&amp; ctx.params._id != 'undefined'){
      bnr = await Banner.find({stores: ctx.params._id}).limit(1);
    }
    if(!bnr || bnr.length &lt; 1){
      bnr = await Banner.find({""store"":{""$exists"": false}}).limit(1);
    }  
    ctx.send(JSON.stringify(bnr));
  }
};
</code></pre>

<p>I am lost as to how to go about stubbing the Banner object, as it is not declared from inside of the file. This is the test I have been trying to run, which returns 'ReferenceError: Banner is not defined'</p>

<pre><code>const sinon = require('sinon');
const proxyquire = require('proxyquire');
const mongoose = require('mongoose');
const mocha = require('mocha');
const assert = require('chai').assert;

describe.only('Unit test: Banner Controller Test', () =&gt; {


    describe('Test getBanner', () =&gt; {
        let sandbox;
        let fns;
        before((done) =&gt; {

            sandbox = sinon.createSandbox();
            var schema = new mongoose.Schema()
            var Banner = mongoose.model('Banner', schema);
            let success = sandbox.stub(Banner, 'find').returns({hello: ""there""})

            fns = proxyquire('../../api/banner/controllers/Banner', {
                success
            })
            done()
        })

        it('should return a function call with a JSON object', (done) =&gt; {
            fns.getBanner((ctx) =&gt; {
                //returns 'ReferenceError: Banner is not defined' when run
            });
            done();
        })
    })



});
</code></pre>

<p>Any help solving this would be greatly appreciated!</p>
",https://stackoverflow.com/questions/58347373/how-to-stub-an-instance-of-an-object-not-declared-in-file,"['node.js', 'mongodb', 'unit-testing', 'strapi']",272,True,1,1
how to configure dependencies in asp.net core,"<p>I have an ASP.Net Core 2.1 application. I need to register &amp; inject few dependencies of <code>AWS</code>.</p>

<p>Currently, the implementation looks like this:</p>

<pre><code>public abstract class BaseService
{
    protected readonly IConfiguration _configuration;
    protected readonly RegionEndpoint _region;
    protected readonly IAmazonDynamoDB _dynamoClient;
    protected  IPocoDynamo _pocoDynamo;

    public BaseService(IConfiguration configuration)
    {
        _configuration = configuration;
        var awsSettings = configuration.GetSection(""AWS"");
        _dynamoClient = SetDynamoClient(awsSettings);
        _pocoDynamo = SetPocoDynamoClient();
    }

    protected IAmazonDynamoDB SetDynamoClient(IConfigurationSection configuration)
    {
        AWSCredentials credentials = new BasicAWSCredentials(configuration[""AccessKey""], configuration[""AccessSecret""]);
        return new AmazonDynamoDBClient(credentials, _region);
    }

    protected IPocoDynamo SetPocoDynamoClient()
    {
        return new PocoDynamo(_dynamoClient);
    }
}
</code></pre>

<p>While unit testing, AWS services can't be mocked due to this. </p>

<p>I want to register all these dependencies in <code>Startup.cs</code> in <code>ConfigureServices()</code></p>

<p>This is what I was trying:</p>

<pre><code>public void ConfigureServices(IServiceCollection services)
{
    AWSCredentials credentials = new BasicAWSCredentials(configuration[""AccessKey""], configuration[""AccessSecret""]);

    services.AddTransient(IAmazonDynamoDB, (a) =&gt;
         {
             return new AmazonDynamoDBClient(credentials, RegionEndpoint.GetBySystemName(""""))
         });
    // here I need to pass the IAmazonDynamoDB to below IOC
    // services.AddSingleton&lt;IPocoDynamo,new PocoDynamo()&gt; ();

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

<p>But this is throwing an error </p>

<blockquote>
  <p>Error CS0119  'IAmazonDynamoDB' is a type, which is not valid in the given context</p>
</blockquote>

<p>How to configure dependencies as required here?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/58133702/how-to-configure-dependencies-in-asp-net-core,"['c#', 'dependency-injection', 'inversion-of-control', 'ioc-container', 'asp.net-core-2.1']",822,True,1,1
PhpStorm: Should I add Xdebug settings to BOTH my php.ini files?,"<p>In setting up Xdebug in PhpStorm, the CLI interpreter shows the php.ini file for the command line PHP stuff at <code>/etc/php/7.2/cli/php.ini</code>. </p>

<p><strong>Question</strong>: Do I need to add xdebug configs to this CLI version as well? </p>

<p>If so, why? Is it possibly for unit testing, etc?</p>

<p>I ask because I know that the php.ini file at: <code>/etc/php/7.2/apache2/php.ini</code> -which <strong><em>does</em></strong> have Xdebug settings <em>(see below)</em> - is the php.ini that handles all my web stuff. Please advise.</p>

<p>Thanks</p>

<h2>My Xdebug Settings</h2>

<pre><code>[xDebug]
; Debug Settings
zend_extension=/usr/lib/php/20170718/xdebug.so
xdebug.remote_enable = On
xdebug.remote_autostart = Off
;xdebug.remote_host = ""localhost""
xdebug.remote_connect_back = On
xdebug.remote_port = 9000
xdebug.idekey = ""PHPSTORM""
</code></pre>
",https://stackoverflow.com/questions/55248944/phpstorm-should-i-add-xdebug-settings-to-both-my-php-ini-files,"['php', 'phpstorm', 'xdebug']",157,False,1,0
(Jasmine)How can i generate and flush a mock error with error code 406 and contains error.error.error as well?,"<p>I am working with an angular application and I am unit testing the application with Jasmine.</p>

<p>What I am doing is testing for HTTP request which should return an error code(status) of 406. I am able to do that but extra I need is upon flushing the error it should also include <code>error.error.error</code> parameter so that I can apply <code>forEach</code> on it.</p>

<p>code to be tested is something like this:</p>

<pre><code>get() {
  this.httpClient.get(this.url);
}

getSomething() {
  this.get().subscribe(res =&gt; {
    // something
  },(error) =&gt; {
    if(error.status == 406) {
      error.error.error.forEach(element =&gt; {
        this.showToastMsg(""Error"", element, ""error"");
    }
    else {
      // do something else
    }
  });
}
</code></pre>

<p>how can I generate the error with <code>error.error.error</code> way.</p>
",https://stackoverflow.com/questions/55036525/jasminehow-can-i-generate-and-flush-a-mock-error-with-error-code-406-and-conta,"['angular', 'http', 'jasmine']",192,False,1,0
Python unit testing on class methods with no input arguments,"<p>Given a class with class methods that contain only <code>self</code> input:</p>

<pre><code>class ABC():
    def __init__(self, input_dict)
        self.variable_0 = input_dict['variable_0']
        self.variable_1 = input_dict['variable_1']
        self.variable_2 = input_dict['variable_2']
        self.variable_3 = input_dict['variable_3']

    def some_operation_0(self):
        return self.variable_0 + self.variable_1

    def some_operation_1(self):
        return self.variable_2 + self.variable_3
</code></pre>

<p><strong>First question</strong>: Is this very bad practice? Should I just refactor <code>some_operation_0(self)</code> to explicitly take the necessary inputs, <code>some_operation_0(self, variable_0, variable_1)</code>? If so, the testing is very straightforward.</p>

<p><strong>Second question</strong>: What is the correct way to setup my unit test on the method <code>some_operation_0(self)</code>? 
Should I setup a fixture in which I initialize <code>input_dict</code>, and then instantiate the class with a mock object?</p>

<pre><code>@pytest.fixture
def generator_inputs():
    f = open('inputs.txt', 'r')
    input_dict = eval(f.read())
    f.close()
    mock_obj = ABC(input_dict)

def test_some_operation_0():
    assert mock_obj.some_operation_0() == some_value
</code></pre>

<p>(I am new to both python and general unit testing...)</p>
",https://stackoverflow.com/questions/59181921/python-unit-testing-on-class-methods-with-no-input-arguments,"['python', 'unit-testing', 'pytest']",908,True,1,1
React-native-modal - Unexpected Token with Jest using TransformIgnorePatterns,"<p>I'm trying to run a test with Jest on a React Native Component.
Using <code>react-native-modal</code>. I'm new on Jest and general unit testing, so I'm not sure how to fix this problem.</p>

<p>I even add:
<code>transformIgnorePatterns</code> property on the setup but the problem remains the same.</p>

<p>My Goal is to test property the Modal component.</p>

<p>Actual test:</p>

<pre><code>import 'react-native';
import React from 'react';
import BottomModalComponent from './BottomModalComponent';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

test('renders BottomModalComponent.js', () =&gt; {
  const tree = renderer.create(&lt;BottomModalComponent isVisible={false} /&gt;).toJSON();
  expect(tree).toMatchSnapshot();
});
</code></pre>

<hr>

<p><strong>.babelrc</strong> setup</p>

<pre><code>// File-relative configuration
{
  ""plugins"": [
    [""@babel/plugin-proposal-class-properties"", { ""loose"": true }],
  ],
  ""presets"": [
    ""module:metro-react-native-babel-preset"",
  ],
  ""retainLines"": true
}

</code></pre>

<p>Dependencies:</p>

<pre><code>  ""dependencies"": {
    ""babel-core"": ""7.0.0-bridge.0"",
    ...
},
  ""devDependencies"": {
    ""@babel/plugin-proposal-class-properties"": ""^7.4.0"",
    ""babel-eslint"": ""8"",
    ""babel-jest"": ""23.6.0"",
    ""babel-preset-react-native"": ""^4.0.1"",
    ""jest"": ""23.6.0"",
    ""jest-react-native"": ""^18.0.0"",
    ""metro-react-native-babel-preset"": ""^0.53.1"",
    ""react-test-renderer"": ""16.6.0-alpha.8af6728""
  },
</code></pre>

<p><strong>babel.config.js</strong></p>

<pre><code>// Project-wide configuration
module.exports = {
  plugins: [
    [""@babel/plugin-proposal-class-properties"", { ""loose"": true }]
  ]
};
</code></pre>

<p>This is how my <strong>package.json</strong> looks like with the Jest setup:</p>

<pre><code>""jest"": {
    ""preset"": ""react-native"",
    ""transformIgnorePatterns"": [
      ""node_modules/(?!(react-native|react-native-modal)/)""
    ]
  },
</code></pre>

<p>This is my <strong>error</strong> when I run <code>npm run test</code></p>

<pre><code>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"".

SyntaxError: /project_name/node_modules/react-native-modal/src/index.js: Unexpected token (470:8)

      468 |       this.props.useNativeDriver &amp;&amp;
      469 |       !this.state.showContent ? (
    &gt; 470 |         &lt;animatable.View /&gt;
          |         ^
      471 |       ) : (
      472 |         children
      473 |       );
</code></pre>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/55579432/react-native-modal-unexpected-token-with-jest-using-transformignorepatterns,"['react-native', 'jestjs', 'babeljs', 'babel-jest']",598,True,1,1
Unit testing &#39;pathlib.Path.is_file&#39; in Python 3.x,"<p>I am new to unit testing in Python and have problems to get my tests running. I want to implement the following test class as shown in here: <a href=""https://www.toptal.com/python/an-introduction-to-mocking-in-python"" rel=""nofollow noreferrer"">https://www.toptal.com/python/an-introduction-to-mocking-in-python</a>, but slightly 
modified. 
Instead of using <code>os.path.isfile</code> I want to use <code>pathlib.Path.is_file</code>.</p>

<p>This is the actual class to test:</p>

<pre><code>import os

from pathlib import Path

class FileUtils:

    @staticmethod
    def isFile(file):
        return Path(file).is_file()

    @staticmethod
    def deleteFile(file):
        if FileUtils.isFile(file):
            os.remove(file)
</code></pre>

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

<pre><code>import mock, unittest

class FileUtilsTest(unittest.TestCase):

    testFilename = ""filename""

    @mock.patch('FileUtils.Path')
    @mock.patch('FileUtils.os')
    def testDeleteFiles(self, osMock, pathMock):

        pathMock.is_file.return_value = False
        FileUtils.deleteFile(self.testFilename)
        self.assertFalse(osMock.remove.called, 'Failed to not remove the file if not present.')

        pathMock.is_file.return_value = True
        FileUtils.deleteFile(self.testFilename)
        osMock.remove.assert_called_with(self.testFilename)
</code></pre>

<p>This will lead to the following error message:</p>

<pre><code>Finding files... done.
Importing test modules ... done.

======================================================================
FAIL: testDeleteFile (FileUtilsTest.FileUtilsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""...\AppData\Local\Continuum\anaconda3\lib\site-packages\mock\mock.py"", line 1305, in patched
    return func(*args, **keywargs)
  File ""...\FileUtilsTest.py"", line 13, in testDeleteFile
    self.assertFalse(osMock.remove.called, 'Failed to not remove the file if not present.')
AssertionError: True is not false : Failed to not remove the file if not present.

----------------------------------------------------------------------
Ran 1 test in 0.003s

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

<p>How can I test the method <code>FileUtils.deleteFile</code> by using <code>@mock.patch</code> decorators?</p>
",https://stackoverflow.com/questions/56023351/unit-testing-pathlib-path-is-file-in-python-3-x,"['python', 'python-3.x', 'unit-testing', 'mocking']",2440,True,1,1
Unit testing Boolean method based on other methods return types,"<p>New to unit testing and am looking for a way to unit test a Boolean method that is validated by two other methods results.  </p>

<pre><code> protected boolean isUpdateNeeded(){ 
 return (method1() &amp;&amp; method2()); 
}
</code></pre>

<p>the other methods look like this for this example. </p>

<pre><code>protected boolean method1() { 
 return false; 
}

protected boolean method2() { 
 return true; 
} 
</code></pre>

<p>But these two methods are/can be Overriden if need be. Idk if that really matter at this point</p>

<p>So my thinking behind the test is this. Find a way to pass true/false to method1 or method2 to meet the required possible outcomes.  </p>

<pre><code>@Test
 public void testCheckToSeeIfUpdateIsNeeded(){ 
   assertTrue('how to check here'); 
   asserFalse('how to check here');
   assertIsNull('was null passed?');  

 }
</code></pre>
",https://stackoverflow.com/questions/57999782/unit-testing-boolean-method-based-on-other-methods-return-types,"['java', 'unit-testing', 'junit']",1575,True,1,2
How to call custom methods of React component while doing unit testing. I am using typescript,"<p>I am using react with typescript. Can anyone tell me how to call the custom methods which is written in component inside unit testing.</p>

<p>I tried <code>shallow</code> and <code>mount</code> but I am not able to call custom methods.</p>

<pre><code>import React  from 'react';
import {
  Theme,
  withStyles,
  createStyles,
} from '@material-ui/core';

export interface IFileUploadProps{}
export interface IFileUploadState {}

const styles = (theme: Theme) =&gt; {
  return createStyles({
    root: {
      paddingTop: theme.spacing(2),
      paddingBottom: theme.spacing(2),
      width: '100%',
      backgroundColor: 'inherit',
    },
    input: {
      display: 'none',
    },
    padding24: {
      paddingLeft: theme.spacing(3),
      paddingRight: theme.spacing(3),
    },
  });
};

class FileUpload extends React.Component&lt;IFileUploadProps, IFileUploadState&gt; {

    validateImage = () =&gt; {
      console.log('validate image');
    }

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

export default withStyles(styles)(FileUpload);
</code></pre>

<p>I need to do something like this.</p>

<pre><code>import React from 'react';
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16'
import FileUpload from './FileUpload';

configure({ adapter: new Adapter() });   
describe('FileUpload', () =&gt; {
  test('should call validateImage method correctly', () =&gt; {
    const wrapper = shallow(&lt;FileUpload &gt;&lt;/FileUpload&gt;);
    wrapper.instance()['validateImage']();
  });
});
</code></pre>

<p>Here I am getting error. </p>

<blockquote>
  <p>TypeError: Cannot read property 'validateImage' of null</p>
</blockquote>

<p><strong>This error occurs when i export file using ""export default withStyles(styles)(FileUpload);"" 
When i use export default FileUpload it is working fine.</strong></p>
",https://stackoverflow.com/questions/58642342/how-to-call-custom-methods-of-react-component-while-doing-unit-testing-i-am-usi,"['reactjs', 'typescript', 'unit-testing', 'jestjs', 'enzyme']",933,True,1,1
How to mock directive on mock component,"<p>I'm unit testing a component which contains <code>clarity</code> tags with <code>clarit directives</code>.</p>

<p>I have mocked out the clarity tags but they have directives <code>clrDgItems</code> which I can't mock with directive class. </p>

<pre><code>&lt;clr-dg-row *clrDgItems=""let item of items$ | async | filter : listFilter.keyword : ['trackingCode', 'title']"" [clrDgItem]=""episode""&gt;
</code></pre>

<p>I could replace <code>clrDgItems</code> with <code>ngFor</code> but the table filter stops working.</p>

<p>Without it the test does not compile :</p>

<blockquote>
  <p>Can't bind to 'clrDgItemsOf' since it isn't a known property of
  'clr-dg-row'</p>
</blockquote>

<p>When I add mockDirective as: I get error </p>

<blockquote>
  <p>Failed: Unexpected value '[object Object]' declared by the module 'DynamicTestModule'</p>
</blockquote>

<pre><code>     function MockDirective(options: any): Directive {
         const metadata: Directive = {
         selector: options.selector,
         inputs: options.inputs,
         outputs: options.outputs
      };
      return new Directive(metadata);
    }

 TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        MockDirective({
          selector: '[clrDgItemsOf]',
        }),
      MockComponent({
      selector: 'clr-dg-row',
      template: '&lt;ng-content&gt;&lt;/ng-content&gt;',
      outputs: ['clrDgItemsOf'],
      inputs: ['clrDgItem']
    }), ...
</code></pre>

<p>Any suggestions?</p>
",https://stackoverflow.com/questions/57099093/how-to-mock-directive-on-mock-component,"['angular', 'unit-testing', 'clarity']",5335,True,1,1
Spring boot test: @Sql annotation Unable to locate sql files placed in src/test/resources,"<p>I didn't want to load the entire Spring Boot configuration for unit-testing my <code>DAO</code> layer, and therefore created a nested configuration class to <strong>suppress default configurations</strong>. But when I try to specify SQL scripts for it to run before tests, its unable to find them.</p>
<p>Here's the code:</p>
<pre><code>package com.test.customer.controller;
..
@RunWith(SpringRunner.class)
@JdbcTest
@Sql({&quot;data.sql&quot;})
public class InterviewInformationControllerTest {

    @Configuration
    static class TestConfiguration{

    }

    @Test
    public void testCustomer() {
        // code
    }

}
</code></pre>
<p>I get the error:</p>
<pre><code>Cannot read SQL script from class path resource [com/test/customer/controller/data.sql]; 
nested exception is java.io.FileNotFoundException: 
class path resource [com/test/customer/controller/data.sql] 
cannot be opened because it does not exist
</code></pre>
<p>I've tried placing the file at both <code>src/main/resources</code> (not preferred) as well as at <code>src/test/resources</code> (which I prefer)</p>
<p>Note: I'm running the Unit test from inside Eclipse by doing <code>Run as -&gt; JUnit test</code>.</p>
<p><strong>Edit</strong>: Added the <code>static</code> keyword to the configuration class</p>
",https://stackoverflow.com/questions/55144040/spring-boot-test-sql-annotation-unable-to-locate-sql-files-placed-in-src-test,"['java', 'spring', 'spring-boot', 'junit', 'spring-boot-test']",13898,True,6,2
How to mock mysql database?,"<p>I want to do unit testing of a few APIs written by myself, which make some queries on a MySQL database. But I learned recently that establishing an actual connection during testing is not a good practice and the test cases for the APIs would modify, delete, or insert into the tables, which I don't want to happen.</p>

<p>I found that there is a node package called mockgoose which does the same thing for MongoDB. Is there something similar for MySQL?</p>
",https://stackoverflow.com/questions/57622027/how-to-mock-mysql-database,"['mysql', 'node.js', 'unit-testing', 'testing']",5420,True,3,1
How to fix &#39;TypeError: Cannot redefine property: origin&#39; in Jasmine,"<p>I have scenario where </p>

<pre><code>if(window.location.origin){
    //list of operations
}else{
    //list of operations
}
</code></pre>

<p>I am trying to assign value to <a href=""https://developer.mozilla.org/en-US/docs/Web/API/Location#Properties"" rel=""nofollow noreferrer"">window.location.origin</a> which is <code>readonly</code> property for unit testing purpose in Jasmine using </p>

<pre><code>Object.defineProperty(window.location, 'origin', {
   value: '',
   writable: true,
}
</code></pre>

<p>but I am getting error <code>TypeError: Cannot redefine property: origin</code></p>

<p>I have tried following solutions which is for <code>jest</code> which suggest to change in <code>jsdom</code> and use <code>reconfigure</code> to change value of testing environment. Is there way to do this in jasmine? I am able to get <code>Env() using jasmine.getEnv()</code> for jasmine but not able to set it.</p>

<p><a href=""https://github.com/facebook/jest/issues/5124"" rel=""nofollow noreferrer"">Unable to change window.location using Object.defineProperty</a></p>

<p><a href=""https://github.com/facebook/jest/issues/6886"" rel=""nofollow noreferrer"">Unable to redefine properties of the window object</a></p>
",https://stackoverflow.com/questions/55371343/how-to-fix-typeerror-cannot-redefine-property-origin-in-jasmine,"['javascript', 'angular', 'unit-testing', 'dom', 'jasmine']",7355,True,3,1
Making the window to a different data type in the React testing library,"<p>I am trying to test a reusable hook for checking the window resize has been triggered or not.</p>
<p>I was using <a href=""https://github.com/enzymejs/enzyme"" rel=""nofollow noreferrer"">Enzyme</a> for my unit testing, since I was not able to find the documentation and support for hooks I am using.</p>
<ol>
<li>@testing-library/react</li>
<li>@testing-library/react-hooks</li>
</ol>
<h3>File <em>hooks.js</em></h3>
<pre><code>import { useState, useEffect } from &quot;react&quot;;

function useWindowSize() {
    const isClient = typeof window === &quot;object&quot;;

    function getSize() {
        return {
            width: isClient ? window.innerWidth : undefined,
            height: isClient ? window.innerHeight : undefined,
        };
    }

    const [windowSize, setWindowSize] = useState(getSize);

    useEffect(() =&gt; {
        if (!isClient) {
            return false;
        }

        function handleResize() {
            setWindowSize(getSize());
        }

        window.addEventListener(&quot;resize&quot;, handleResize);
        return () =&gt; window.removeEventListener(&quot;resize&quot;, handleResize);
    }, []); // Empty array ensures that effect is only run on mount and unmount

    return windowSize;
}

export default {useWindowSize}
</code></pre>
<p>I was able to test the normal flow, but how can I make the window to a different data type, so I can make the code coverage of 100%?</p>
<h3>File <em>hooks.test.js</em></h3>
<pre><code>import { renderHook, act } from &quot;@testing-library/react-hooks&quot;;
import { fireEvent } from &quot;@testing-library/react&quot;;
import hooks from &quot;..&quot;;

const { useWindowSize } = hooks;

describe(&quot;hooks&quot;, () =&gt; {
    it(&quot;should return a new size of window&quot;, () =&gt; {
        const { result } = renderHook(() =&gt; useWindowSize());
        expect(result.current.width).toBe(1024);
        expect(result.current.height).toBe(768);

        act(() =&gt; {
            // Change the viewport to 500 pixels.
            window.innerWidth = 500;
            window.innerHeight = 500;
            // trigger the window resize event
            fireEvent(window, new Event(&quot;resize&quot;));
        });

        expect(result.current.width).toBe(500);
        expect(result.current.height).toBe(500);
    });
    
    // How can I test if window is not an typeof object?
    it(&quot;should exit if its not window&quot;, () =&gt; {
        const { result } = renderHook(() =&gt; useWindowSize());
        act(() =&gt; {
            // Change the window from object 
            window = &quot;&quot;;
            fireEvent(window, new Event(&quot;resize&quot;));
        });
    });
});
</code></pre>
",https://stackoverflow.com/questions/59173156/making-the-window-to-a-different-data-type-in-the-react-testing-library,"['reactjs', 'react-testing-library']",2964,False,3,0
NativeScript Unit Testing keep disconnecting,"<p>Why <strong>tns test</strong> closes blank NativeScript app?</p>

<p>I have initialized a jasmine test from example in Unit Testing NativeScript Docs.</p>

<p>After I run </p>

<p><code>tns test android</code></p>

<p>First App launches and shows correct test pass screen, but after 4-5 seconds just closes and gives following error in shell.</p>

<blockquote>
  <p>DisconnectedClient disconnected from CONNECTED state (transport error)</p>
</blockquote>

<p><em>All dependencies match the latest package versions :)</em></p>

<p><strong>Things I have already tried</strong>:</p>

<ol>
<li>connecting over wi-fi and USB.</li>
<li>two different android mobiles but they closed app after showing successful test screen </li>
</ol>
",https://stackoverflow.com/questions/58428571/nativescript-unit-testing-keep-disconnecting,"['unit-testing', 'nativescript', 'karma-jasmine']",182,False,3,0
org.json.JSONObject.getNumber() throws &quot;NoSuchMethodError&quot; when called using unittest,"<p>While unit testing, I noticed some strang behaviour when calling JSONObject.getNumber() when running unittests. This is the error:<br></p>

<pre><code>java.lang.NoSuchMethodError: 'java.lang.Number org.json.JSONObject.getNumber(java.lang.String)
</code></pre>

<p>This is the code:<br></p>

<pre><code>Number logId;
logId = jsonObject.getNumber(""logId"");
</code></pre>

<p>For my own implementation, I could just use this one:<br></p>

<pre><code>logId = jsonObject.getInt(""logId"");
</code></pre>

<p>But I am really wondering what I was missing when trying to unit test with JSONObject.getNumber(). Why is the getNumber() method missing?</p>

<p><b>Edit 2019-12-20 13:59</b><br>
I am using maven groupID 'org.json', artifactId 'json', version '20190722'. I call the <code>.getNumber()</code> on a custom made <code>new JSONObject().put(stuff).put(stuff)</code></p>
",https://stackoverflow.com/questions/59411008/org-json-jsonobject-getnumber-throws-nosuchmethoderror-when-called-using-uni,"['java', 'json', 'unit-testing', 'junit4']",265,False,0,1
How to test presenter method that create a new object inside it?,"<p>I have this method to validate Unit. I send field values and inside it method I create a new model and then return that model via interface.</p>

<pre><code>public void validate(String unitNumber, Integer unitTypeId, String notes) {
if(!TextUtils.isEmpty(unitNumber)) {
      Unit unit = new Unit();
      unit.setUnitNumber(unitNumber);
      unit.setFlatTypeId(unitTypeId);
      unit.setNotes(notes);
      view.displayUnitValid(unit);
    } else {
      view.displayUnitNotValid();
    }
  }
</code></pre>

<p>Now I want do do unit testing of this method with the following code.</p>

<pre><code>@Test public void shouldValidateSinceUnitNumberIsValid() {
    // Given
    String unitNumber = ""1"";

    // When
    presenter.validate(unitNumber, null, null);

    // Then
    Mockito.verify(view).displayUnitValid(new Unit());
 }
</code></pre>

<p>I am getting the following error message:</p>

<pre><code>Argument(s) are different! Wanted:
view.displayUnitValid(
    com.rwar.domain.customers.Unit@57cf54e1
);
-&gt; at com.rwar.presentation.work_orders.AddUnitPresenterTest.shouldValidateSinceUnitNumberIsValid(AddUnitPresenterTest.java:73)
</code></pre>

<p>Obvisouly there is a problem since I am creating a new Unit instance here:</p>

<pre><code>Mockito.verify(view).displayUnitValid(new Unit());
</code></pre>

<p>And inside <strong>validate()</strong> method I create another instance of Unit.</p>

<p>How I can fix this?</p>
",https://stackoverflow.com/questions/58605219/how-to-test-presenter-method-that-create-a-new-object-inside-it,"['android', 'junit', 'mockito', 'android-testing']",220,True,0,3
Use methods added by Fody in same solution,"<p>I'm using a custom Fody weaver to add new methods to existing classes. Using dnSpy, I can see that the methods are added but, projects (unit testing and benchmarks) in the same solution with direct dependency, don't compile. If I change these to depend on the NuGet package instead, they compile.
Is there a way to make dependent projects use the Fody generated assembly?</p>

<p>I'm using Fody 5.1.1, FodyHelpers 5.1.1 and Visual Studio 2019 16.3.0 Preview 1.0.</p>
",https://stackoverflow.com/questions/57249164/use-methods-added-by-fody-in-same-solution,"['c#', '.net', 'visual-studio', 'fody']",161,True,0,1
how to test function inside if statement jasmin karma angular,"<p>I'm new at unit testing.
i have a component that call a service to display list of students.</p>

<pre><code> getListStudents() {
this.noteService.getStudents({}).subscribe(res =&gt; {
  this.students= res
})}
</code></pre>

<p>then i call this fucntion in ngOnInit()</p>

<pre><code> if(this.currentUser.Type == 'Teacher'){
this.getListStudents()
}
</code></pre>

<p>without the if statement the test is correct but with the if statement it broke</p>

<p>this is my test</p>

<pre><code>  it('should call the service  getStudents', () =&gt; {
component.currentUser={ ""Type"": ""Teacher""}
let mock = [{
  ""ID"": 22,
  ""name"": ""paul""
}]
let service: NoteService = TestBed.get(NoteService);
  spyOn(service, 'getListStudents').and.returnValue(of(mock));
  fixture.detectChanges();
  expect(component.students.length).toBe(1)
 });
</code></pre>

<p>i got error Cannot read property 'Type' of null and when i remove if statement from ngOnInit it work as expected what i'am doing wrong?
Please suggest me a solutions to solve this problem.thank you </p>
",https://stackoverflow.com/questions/55138698/how-to-test-function-inside-if-statement-jasmin-karma-angular,"['angular', 'unit-testing', 'karma-jasmine', 'karma-runner', 'angular7']",6712,True,0,1
Setting up test projects in your solution for a Xamarian app,"<p>I have experience unit testing but I have never unit tested a Xamarian solution.</p>

<p>My question is should I add two unit test projects to my solution?  One would be a MSTest or NUnit test that tests the logic and another project Xamarian.UITest that only tests the UI?  From my browsing on the internet it seems the Xamarian.UITest is only able to test the UI?  Is this true or can you test the logic as well?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/54575648/setting-up-test-projects-in-your-solution-for-a-xamarian-app,"['visual-studio', 'unit-testing', 'xamarin']",39,True,0,1
How to unit test a function with a dependency (angular),"<p>I'm new to unit testing and have some got basics down. However, I'm trying to test a method. This method calls a function which is part of the oidc-client.js. It basically signs a user in.</p>

<blockquote>
  <p>spec file</p>
</blockquote>

<pre><code>
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { AuthCallbackComponent } from './auth-callback.component';
import { RouterTestingModule } from '@angular/router/testing';


fdescribe('AuthCallbackComponent', () =&gt; {
  let component: AuthCallbackComponent;
  let fixture: ComponentFixture&lt;AuthCallbackComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [ AuthCallbackComponent ]
    })
    .compileComponents();
  }));

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

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

</code></pre>

<blockquote>
  <p>component.ts</p>
</blockquote>

<pre><code>import { UserManager,User,UserManagerSettings,WebStorageStateStore} from 'oidc-client';

  manager = new UserManager(this.getClientSettings());


  ngOnInit() {
    this.authService.completeAuthentication();

  }


  completeAuthentication(): Promise&lt;void&gt; {
    return this.manager.signinRedirectCallback().then(user =&gt; {
      this.user = user;
      this.router.navigate(['/']);
      this.setUser.next(this.user.profile);
      this.onLogin.next(true)
    });
  }



  getClientSettings() {
    return {
      authority: environment.authority,
      client_id: environment.client_id,
      redirect_uri: environment.login,
      post_logout_redirect_uri: environment.logout,
      response_type: 'code',
      scope: 'openid profile email phone address',
      filterProtocolClaims: true,
      loadUserInfo: false,
      accessTokenExpiringNotificationTime: 60,
      silentRequestTimeout: 10000,
      includeIdTokenInSilentRenew: true,
      automaticSilentRenew: true,
      silent_redirect_uri: environment.silent_redirect
    };
  }
}
</code></pre>

<p>I'm not sure how I go about testing this. When I run the test I have I just get ' No state in response'. I want the test to pass and maybe some ideas on how to test the completeAuthentication()</p>
",https://stackoverflow.com/questions/56294682/how-to-unit-test-a-function-with-a-dependency-angular,"['javascript', 'angular', 'unit-testing', 'karma-jasmine', 'oidc-client-js']",431,False,0,1
"A User unit test always passes in case of Null, Undefined, True and False","<p>I am unit testing a Nodejs User model with Jest. Here is the code for model:</p>

<pre><code>const jwt = require('jsonwebtoken');
const config = require('config');
const moment = require('moment');
const Joi = require('joi');
const Sql = require('sequelize');
const db = require(""../startup/db"");

const User = db.define('user', {
    id: {type: Sql.INTEGER,
         primaryKey:true,
         min: 1},
    name: {type: Sql.STRING,
           allowNull: false,
           min: 2,
           max: 50,
    },
    email: {type: Sql.STRING,
            isEmail: true
    },      
    cell: {type: Sql.STRING,
            allowNull: false,
            unique:true,  //cell number is universally unique 
            min: 10,
            max: 20,
    },
    cell_country_code: {type: Sql.STRING,
    },
    customer_id: {type: Sql.INTEGER,
                  allowNull: false,
    },
    role: {type: Sql.STRING},
    last_updated_by_id: {type: Sql.INTEGER},
    fort_token: {type: Sql.STRING,
                 allowNull: false,
    },
    createdAt: Sql.DATE,
    updatedAt: Sql.DATE
  }, {
    validate: {async custom_validate() {
      let user = await User.findOne({where:{name :req.body.name, fort_token: session('fort_token')}});
      if (user) return res.status(400).send(""用户重名！"");

    }
  }
});

function validateUser(user) {
    const schema = {
        name: Joi.string()
        .min(2)
        .max(50)
        .required()
        .trim(),
    cell: Joi.string()
        .min(10)
        .max(20)
        .trim()
        .required()
        .error(new Error('该手机号有误！')),
    email: Joi.string()
        .min(5)
        .max(255)
        .email()
        .error(new Error('邮件地址格式不对！'))
        .trim(),
    customer_id: Joi.integer()
        .required(),
    fort_token: Joi.string()
        .required(),
    };

    return Joi.validate(user, schema);
};
</code></pre>

<p>Here is the test case. When a user can have duplicate name if the fort_token is different:</p>

<pre><code>const {User} = require('../../../models/user');
const moment = require('moment');
const jwt = require('jsonwebtoken');
const config = require('config');
const Sql = require(""sequelize"");

describe('User model should be sound', () =&gt; {
    let name = 'john doe';
    let customer_id = 1;
    let cell = '1234567890';
    let fort_token = '12349596874567678906';
    let role = 'admin';
    let expire_datetime =  moment().add(24, 'hours');
    let email = 'home@yahoo.com';

    let payload = () =&gt;{ 
        return {
          customer_id: customer_id,
          name:  name,
          cell: cell,
          email: email,
          expire_datetime: expire_datetime,
          role: role,
          fort_token: fort_token
        }};

     it('should allow duplicate name with different fort token and cell', () =&gt; {
        let user = new User(payload());
        name = user.name;
        cell = user.cell + '1';
        fort_token = user.fort_token + '1';
        let user1 = new User(payload());
        expect(user1).toBeNull; 
   });
</code></pre>

<p>The unit test passes with green. I tried to test with the following:</p>

<pre><code>expect(user1).toBeTruthy;
expect(user1).toBeFalsy;
expect(user1).toBeUndefined;
</code></pre>

<p>To my big surprise, all passes with green. I don't quite get it why the <code>user1</code> object could be all <code>truthy, falsy, Null and Undefined</code>  at the same time! Or should I use <code>toHaveProperty()</code> to test object?</p>
",https://stackoverflow.com/questions/54715819/a-user-unit-test-always-passes-in-case-of-null-undefined-true-and-false,"['node.js', 'express', 'jestjs']",43,False,0,1
Vue.js – Unit Testing multi file components,"<p>As mentioned in the title, I am using multi file components with Vue.js i.e. I've got a separate html, javascript and scss file. Thus my vue file looks like this:</p>
<pre><code>&lt;template src=&quot;./my-component.html&quot;&gt;&lt;/template&gt;
&lt;script src=&quot;./my-component.js&quot;&gt;&lt;/script&gt;
&lt;style src=&quot;./my-component.scss&quot; lang=&quot;scss&quot;&gt;&lt;/style&gt;
</code></pre>
<p>The vue Unit Testing guide</p>
<p><a href=""https://v2.vuejs.org/v2/guide/unit-testing.html"" rel=""nofollow noreferrer"">https://v2.vuejs.org/v2/guide/unit-testing.html</a></p>
<p>only covers single file components.</p>
<p>Most likely I need to invoke webpack to build a single file component in order to be able to test it.</p>
<p>Could anyone point me in the right direction?</p>
",https://stackoverflow.com/questions/59303168/vue-js-unit-testing-multi-file-components,"['unit-testing', 'vue.js']",252,False,0,0
How to stub a Facebook&#39;s SDK access token for unit testing,"<p>I'm trying to perform some unit testing in my application and I've ran into a problem. A simple graph request demands an AccessToken object which can only be claimed by - </p>

<pre><code>AccessToken.getCurrentAccessToken() 
</code></pre>

<p>or getting it in an authentication result.
Both of the options requires a real authentication process with ui which makes it impossible to unit test. is there a way to create my own AccessToken object? I've tried to use reflection with no luck. any other suggestions?</p>
",https://stackoverflow.com/questions/54769510/how-to-stub-a-facebooks-sdk-access-token-for-unit-testing,"['android', 'facebook-sdk-4.x']",691,True,-1,2
Is there any Node.js package that would allow me to mock MySql connection in order to test APIs that need db connection?,"<p>I want to do unit testing of a few APIs written by myself, which make some queries on a <strong>MySQL</strong> database. But I learned recently that establishing an actual connection during testing is not a good practice and the test cases for the APIs would modify the table entries, which I don't want to happen.</p>

<p>I found that there is a node package called <em>mockgoose</em> which does the same thing for <em>MongoDB</em>. Is there something similar for MySQL?</p>
",https://stackoverflow.com/questions/56863274/is-there-any-node-js-package-that-would-allow-me-to-mock-mysql-connection-in-ord,"['mysql', 'node.js', 'unit-testing', 'testing']",54,False,0,0
"Unit test (NUnit, Nsubstitute) ASP Core Service with MongoDB","<p>I got a simple application that calls a MongoDB collection, and it does various things with it.</p>

<p>I want to unit test my service layer using NUnit, Nsubstitute, but I have no idea how to mock a data collection that my service layer consumes.</p>

<p>Here is my current setup:</p>

<p>AutoDB:</p>

<pre><code>public class AutoDb : IAutoDb
{
    private readonly IMongoCollection&lt;Auto&gt; _AutosCollection;

    public AutoDb(IConfiguration config)
    {
        var client = new MongoClient(config.GetConnectionString(""DatabaseConnection""));
        var database = client.GetDatabase(""AutoDb"");

        _AutosCollection = database.GetCollection&lt;Auto&gt;(""Autos"");

        var AutoKey = Builders&lt;Auto&gt;.IndexKeys;
        var indexModel = new CreateIndexModel&lt;Auto&gt;(AutoKey.Ascending(x =&gt; x.Email), new CreateIndexOptions {Unique = true});

        _AutosCollection.Indexes.CreateOne(indexModel);
    }

    public async Task&lt;List&lt;Auto&gt;&gt; GetAll()
    {
        return await _AutosCollection.Find(_ =&gt; true).ToListAsync();
    }

    public async Task&lt;Auto&gt; Get(Guid id)
    {
        return await _AutosCollection.Find&lt;Auto&gt;(o =&gt; o.Id == id).FirstOrDefaultAsync();
    }

    public async Task&lt;Auto&gt; Create(Auto Auto)
    {
        await _AutosCollection.InsertOneAsync(Auto);
        return Auto;
    }

    public async Task Update(Guid id, Auto model)
    {
        await _AutosCollection.ReplaceOneAsync(o =&gt; o.Id == id, model);
    }

    public async Task Remove(Auto model)
    {
        await _AutosCollection.DeleteOneAsync(o =&gt; o.Id == model.Id);
    }

    public async Task Remove(Guid id)
    {
        await _AutosCollection.DeleteOneAsync(o =&gt; o.Id == id);
    }

    public IMongoQueryable&lt;Auto&gt; GetQueryable() =&gt; _AutosCollection.AsQueryable();
}

public interface IAutoDb
{
    Task&lt;List&lt;Auto&gt;&gt; GetAll();

    Task&lt;Auto&gt; Get(Guid id);

    Task&lt;Auto&gt; Create(Auto Auto);

    Task Update(Guid id, Auto model);

    Task Remove(Auto model);

    Task Remove(Guid id);

    IMongoQueryable&lt;Auto&gt; GetQueryable();
}
</code></pre>

<p>My Service Layer</p>

<pre><code>public class AutoService : IAutoService
{
    private readonly IAutoDb _AutoDb;

    public AutoService(IAutoDb AutoDb)
    {
        _AutoDb = AutoDb;
    }

    public async Task&lt;Auto&gt; CreateProfile(AutoModel model)
    {

        var Auto = new Auto
        {
            Id = new Guid(),
            Type = model.Type,
            Name = model.Name,
        };

        try
        {
            await _AutoDb.Create(Auto);

        }
        catch (MongoWriteException mwx)
        {
            Debug.WriteLine(mwx.Message);
            return null;
        }

        return Auto;
    }

    public async Task&lt;Auto&gt; GetAutoById(Guid id)
    {
        var retVal = await _AutoDb.Get(id);

        return retVal;
    }

    public Task&lt;Auto&gt; EditAuto(AutoModel model)
    {
        throw new NotImplementedException();
    }
}

public interface IAutoService
{
    Task&lt;Auto&gt; CreateProfile(AutoModel model);
    Task&lt;Auto&gt; EditAuto(AutoModel model);
    Task&lt;Auto&gt; GetAutoById(Guid id);

}
</code></pre>

<p>My attempt at unit testing the service layer:</p>

<pre><code>public class AutoServiceTests
{
    private IAutoDb _AutoDb;

    [SetUp]
    public void Setup()
    {
        _AutoDb = Substitute.For&lt;IAutoDb&gt;();

        // I don't know how to mock a dataset that contains
        // three auto entities that can be used in all tests
    }

    [Test]
    public async Task CreateAuto()
    {
        var service = new AutoService(_AutoDb);

        var retVal = await service.CreateProfile(new AutoModel
        {
            Id = new Guid(),
            Type = ""Porsche"",
            Name = ""911 Turbo"",
        });

        Assert.IsTrue(retVal is Auto);
    }

    [Test]
    public async Task Get3Autos() {
        var service = new AutoService(_AutoDb);

        // Stopped as I don't have data in the mock db
    }

    [Test]
    public async Task Delete1AutoById() {
        var service = new AutoService(_AutoDb);

        // Stopped as I don't have data in the mock db
    }
}
</code></pre>

<p>How can I create a mockdb collection that can be consumed by all the tests in the class?</p>
",https://stackoverflow.com/questions/55203495/unit-test-nunit-nsubstitute-asp-core-service-with-mongodb,"['c#', '.net-core', 'nunit', 'nsubstitute']",1561,True,0,2
Use Moq to do unit testing for datatable export service,"<p>I have a service to export as csv file which inside videmodel in WPF application:</p>

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

        DataTable tblFiltered = _currentTable.AsEnumerable()
                          .Where(r =&gt; r.Field&lt;string&gt;(""Type"") == ExportGridGroup)
                          .CopyToDataTable();

        StringBuilder sb = new StringBuilder();
        IEnumerable&lt;string&gt; columnNames = tblFiltered.Columns.Cast&lt;DataColumn&gt;().
                                          Select(column =&gt; column.ColumnName);
        sb.AppendLine(string.Join("","", columnNames));

        foreach (DataRow row in tblFiltered.Rows)
        {
            IEnumerable&lt;string&gt; fields = row.ItemArray.Select(field =&gt; ""\"""" + field.ToString() + ""\"""");
            sb.AppendLine(string.Join("","", fields));
        }

        String result = sb.ToString();
        try
        {
            StreamWriter sw = new StreamWriter(""export.csv"");
            sw.WriteLine(result);
            sw.Close();
            Process.Start(""export.csv"");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
</code></pre>

<p>So based on this, i have created a test method for it but haven't finished;</p>

<pre><code> [TestMethod()]
    public void ExportToExcelTest()
    {
        //Step 1: Creating a mock table with columns
        DataTable testtable = new DataTable();
        DataRow mydatarow;
        mydatarow = testtable.NewRow();
        //Step 2: Adding the row 
        mydatarow[""ColumnA""] = ""12345"";
        mydatarow[""ColumnB""] = ""test"";

        testtable.Rows.Add(mydatarow);

        StringBuilder sb = new StringBuilder();
        IEnumerable&lt;string&gt; columnNames = testtable.Columns.Cast&lt;DataColumn&gt;().
                                          Select(column =&gt; column.ColumnName);
        sb.AppendLine(string.Join("","", columnNames));

        foreach (DataRow row in testtable.Rows)
        {
            IEnumerable&lt;string&gt; fields = row.ItemArray.Select(field =&gt; ""\"""" + field.ToString() + ""\"""");
            sb.AppendLine(string.Join("","", fields));
        }

        String result = sb.ToString();
        StreamWriter sw = new StreamWriter(""export.csv"");
        sw.WriteLine(result);
        sw.Close();
        Process.Start(""export.csv"");          
        Assert.Fail();
    }
</code></pre>

<p>I am a bit confused because in the test method, I nearly write the exact same code in the project.....
Can I have some suggestions on how to write this unit test and any detailed references on WPF/C# Unit Testing by using Moq for me to start with?</p>
",https://stackoverflow.com/questions/55226460/use-moq-to-do-unit-testing-for-datatable-export-service,"['c#', 'wpf', 'unit-testing', 'moq']",1394,True,0,1
How to order Tests while building Spring Boot application,"<p>I am building spring boot application with unit testing. I have entities those are dependent on each other, Eg: I have User and Roles. To create User i should need Roles. I am testing roles and user object resources with MockMvc. I created Test class for Each Entity. When i run test UserTest class is executing Before Role Test class. So, all my tests are failing. I need help to run Test classes in an order.</p>
",https://stackoverflow.com/questions/56920861/how-to-order-tests-while-building-spring-boot-application,"['spring-boot', 'spring-data-jpa', 'spring-test', 'spring-mvc-test']",439,False,0,1
unit test the javascript functions in my django application,"<p>I have a Django app, which contains backend logic in <code>views.py</code> and front end logic/user data processing written in javascript and jQuery inside HTML files. Now I wanted to write unit tests, can I use mocha-chai for doing this or any other alternative to do unit testing a JavaScript code in Django.</p>

<p>my directory structure</p>

<pre><code>myapp
---&gt;templates
-----&gt;base.html
-----&gt;home.html
</code></pre>

<p>base.html contains:</p>

<pre><code>&lt;html&gt;
&lt;body&gt;
&lt;h1&gt;WElcome&lt;/h1&gt;
&lt;script&gt;
function myfunc(){
console.log(""welcome"")
//some user logic 
}
&lt;/sctipt&gt;
</code></pre>

<p>which framework to use in order to do write a unit test case for this 'myfunc' inside the Django template</p>
",https://stackoverflow.com/questions/59249703/unit-test-the-javascript-functions-in-my-django-application,"['javascript', 'jquery', 'django', 'mocha.js', 'chai']",1649,True,0,1
@RequestParam javax validation junit REST controller testing,"<p>Is there a way to do spring controller unit testing for javax validations on @RequestParams.</p>

<p>I have a get method in controller which validates the size of the request param with @Size.</p>

<pre><code>@RequestMapping(value = ""/getData"", method = RequestMethod.GET)
    public ResultgetData(

            @Size(min=2, max=3)
             @RequestParam String number)
</code></pre>

<p>Is there a way to mock junit test the size validator? I would like to validate a error returned when the size  is &lt;2 or > 3. </p>

<p>Sample test :</p>

<p>@RunWith(MockitoJUnitRunner.class)
public class MyControllerTest {</p>

<pre><code>private MockMvc mockMvc;

@InjectMocks
private MyController myControllerMock;


@Before
public void initTest() {
    mockMvc = MockMvcBuilders.standaloneSetup(customerInsuranceControllerMock).setControllerAdvice(exceptionHandler).build();
}

@Test
public void getEmptyData() throws Exception{



    mockMvc.perform(MockMvcRequestBuilders.get(
        ""/getData?number={number}""
        , """")
        .andExpect(MockMvcResultMatchers.status().isBadRequest());  // This is failing. It returns a success as javax @Size is not triggered.When a empty string is passed , it should be bad request
</code></pre>

<p>}</p>

<p>I tried spring runner too ,but still seems to fail.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/56738655/requestparam-javax-validation-junit-rest-controller-testing,"['rest', 'mockito', 'junit4']",6292,True,0,2
Where to put the MockK settings.properties file in an Android project?,"<p>We're using MockK for unit testing our Android project. Since we're almost always use <code>mockk(relayed=true)</code> we wanted to set it as default in the <code>settings.properties</code> as <a href=""https://github.com/mockk/mockk#settings-file"" rel=""nofollow noreferrer"">suggested in the docs</a>.</p>

<p>It says: 
""create io/mockk/settings.properties file in resources.""</p>

<p>Ok, so I thought it would be a good idea to put it here: <code>src/main/res/io/mockk/settings.properties</code>. Unfortunately, it does not work. If I remove the explicit <code>relaxed=true</code> in the individual mocks all the tests fail.</p>

<p>So, where do I actually place the settings file?</p>
",https://stackoverflow.com/questions/55648247/where-to-put-the-mockk-settings-properties-file-in-an-android-project,"['android', 'unit-testing', 'mockk']",222,True,0,1
Difference between Router and RouterTestingModule also Http and HttpTestingModule.Can I pass RouterTestingModule where it expects Router,"<p>I am running unit test on Angular app, I try to create instance of Component
 this is the constructor</p>

<pre><code>constructor(private http: HttpClient, private fb: FormBuilder, private router: Router, private spinner: NgxSpinnerService) { }
</code></pre>

<p>so In the unit test I am forced to import formbuilder,router etc. shouldn't httpTestingModule and RouterTestingModule compensate for the above modules??</p>

<p>I am new to unit testing, So, the question might be basic.</p>

<p>This is what I tired 
  let fb :FormBuilder;
  let rt:RouterTestingModule;</p>

<p>so here instead for importing router I imported routerTestingModule, this is not working?</p>

<pre><code> let component: EntitlementCreateComponent = new EntitlementCreateComponent(_httpClient, fb, rt,  NgxSpinnerService);

This is testbed
TestBed.configureTestingModule({
        imports:[HttpClientTestingModule,RouterTestingModule,FormsModule,ReactiveFormsModule],
        declarations: [EntitlementCreateComponent,NGXSpinner],

        schemas: [ CUSTOM_ELEMENTS_SCHEMA]
      })

      fixture = TestBed.createComponent(EntitlementCreateComponent);
</code></pre>
",https://stackoverflow.com/questions/58100423/difference-between-router-and-routertestingmodule-also-http-and-httptestingmodul,"['angular', 'unit-testing', 'karma-jasmine']",100,False,0,0
How to use Jest to mock winston logger instance encapsulated in service class,"<p>I am trying to mock a <em>winston.Logger</em> instance that is encapsulated within a service class created with NestJS. I have included my code below. </p>

<p>I cannot get the mocked logger instance to be triggered from within the service class. Can anyone explain where I am going wrong?</p>

<pre class=""lang-js prettyprint-override""><code>import * as winston from 'winston';

import { loggerOptions } from '../logger/logger.config';
import { LoggingService } from '../logger/logger.service';

const logger: winston.Logger = winston.createLogger(loggerOptions);

// trying to mock createLogger to return a specific logger instance
const winstonMock = jest.mock('winston', () =&gt; (
    {
        format: {
            colorize: jest.fn(),
            combine: jest.fn(),
            label: jest.fn(),
            timestamp: jest.fn(),
            printf: jest.fn()
        },
        createLogger: jest.fn().mockReturnValue(logger),
        transports: {
            Console: jest.fn()
        }
    })
);


describe(""-- Logging Service --"", () =&gt; {
    let loggerMock: winston.Logger;

    test('testing logger log function called...', () =&gt; {        
        const mockCreateLogger = jest.spyOn(winston, 'createLogger');
        const loggingService: LoggingService = LoggingService.Instance;
        loggerMock = mockCreateLogger.mock.instances[0];
        expect(loggingService).toBeInstanceOf(LoggingService)
        expect(loggingService).toBeDefined();
        expect(mockCreateLogger).toHaveBeenCalled()

        // spy on the winston.Logger instance within this test and check
        // that it is called - this is working from within the test method
        const logDebugMock = jest.spyOn(loggerMock, 'log');
        loggerMock.log('debug','test log debug');
        expect(logDebugMock).toHaveBeenCalled();

        // now try and invoke the logger instance indirectly through the service class
        // check that loggerMock is called a second time - this fails, only called once
        // from the preceding lines in this test
        loggingService.debug('debug message');
        expect(logDebugMock).toHaveBeenCalledTimes(2);
    });

   ...
</code></pre>

<p><strong>LoggingService debug method code</strong></p>

<pre><code>public debug(message: string) {
        this.logger.log(
            {
                level: types.LogLevel.DEBUG,
                message: message,
                meta: {
                    context: this.contextName
                }
            }
        );
    }
</code></pre>

<p><strong>Update: 3/09/2019</strong></p>

<p>Refactored my nestjs LoggingService to dependency inject winston logger instance in constructor to facilitate unit testing. This enables me to use <em>jest.spyOn</em> on the winston logger's log method and check that it has been called within the service instance:</p>

<pre class=""lang-js prettyprint-override""><code>// create winstonLoggerInstance here, e.g. in beforeEach()....
const winstonLoggerMock = jest.spyOn(winstonLoggerInstance, 'log');
serviceInstance.debug('debug sent from test');
expect(winstonLoggerMock).toHaveBeenCalled();
</code></pre>
",https://stackoverflow.com/questions/57771616/how-to-use-jest-to-mock-winston-logger-instance-encapsulated-in-service-class,"['typescript', 'jestjs', 'nestjs', 'winston']",18444,True,8,3
"Angular, Subjects Unit Testing","<p>We have recently implemented a message service largely based on <a href=""http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject"" rel=""nofollow noreferrer"">this solution</a> in Angular 7, but we are stucked on the unit testing implementation.</p>

<p>We have this service:</p>

<pre><code>@Injectable()
export class MessageService {
  private subject = new Subject&lt;any&gt;();
  sendMessage(message: MessageInput) {
    this.subject.next(message);
  }
  clearMessage() {
    this.subject.next();
  }
  getMessage(): Observable&lt;any&gt; {
    return this.subject.asObservable();
  }
}
</code></pre>

<p>And we have this implemetation, listening for a message sent by another component:</p>

<pre><code>ngOnInit() {
this.subscription = this.messageService.getMessage().subscribe(
  (message: MessageInput) =&gt; {
    if (message) {
      .....
    }
  }, () =&gt; {
      .....
  }
)};
</code></pre>

<p>We want to unit test our implementation, but we are not able to mock the sending and receiving of the message. We are trying this:</p>

<pre><code>beforeEach(() =&gt; {
  TestBed.configureTestingModule({
    schemas: [NO_ERRORS_SCHEMA],
    declarations: [...],
    providers: [
      ...
      MessageService
    ],
    imports: [...]
  });
  fixture = TestBed.createComponent(...);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('makes ngOnInit expected calls', () =&gt; {
  const messageService: MessageService = fixture.debugElement.injector.get(
    MessageService
  );
  component.ngOnInit();
  expect(component.subscription).toBeDefined();
  const message: MessageInput = {text: TypeMessage...., data: '...'};
  const nextSpy = spyOn(messageService.getMessage(), 'subscribe');
  messageService.sendMessage(message);
  expect(nextSpy).toHaveBeenCalled();
});
</code></pre>

<p>We are a but lost there, could any one please help us? Thanks!</p>
",https://stackoverflow.com/questions/54782733/angular-subjects-unit-testing,"['angular', 'unit-testing', 'jasmine', 'rxjs', 'observable']",6004,True,0,2
Flutter: &#39;package:shared_preferences/shared_preferences.dart&#39;: Failed assertion: line 33 pos 16: &#39;key.startsWith(_prefix)&#39;: is not true,"<p>I am running some unit tests on shared preferences. I was making a helper class so that we don't have to write the same code over and over again.</p>

<p>Whatever I try, I always get the same error over and over.
You will find the class that I am testing, the test class and the stacktrace.</p>

<p>I hope it is something dumb that I forgot.
I tried these resources:</p>

<ul>
<li><a href=""https://pub.dartlang.org/packages/shared_preferences"" rel=""noreferrer"">https://pub.dartlang.org/packages/shared_preferences</a></li>
<li><a href=""https://flutter.dev/docs/cookbook/testing/unit/introduction"" rel=""noreferrer"">unit testing flutter</a></li>
<li><a href=""https://flutter.dev/docs/cookbook/persistence/key-value"" rel=""noreferrer"">https://flutter.dev/docs/cookbook/persistence/key-value</a></li>
</ul>

<p>shared_preferences_helper_test.dart:</p>

<pre><code>import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shoppaworld_client_app/shared_preferences_helper.dart';

// at the moment testing
void main() {

  SharedPreferencesHelper sharedPreferencesHelper;

  setUpAll(() {
    sharedPreferencesHelper = SharedPreferencesHelper();

    const MethodChannel('plugins.flutter.io/shared_preferences')
        .setMockMethodCallHandler((MethodCall methodCall) async {
      if (methodCall.method == 'getAll') {
        return &lt;String, dynamic&gt; {
          'test-string' : 'string-value',
          'test-int' : 420,
          'test-bool' : true
        }; // set initial values here if desired
      }
      return null;
    });

  });

  test('test if the testing works', () async {

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString('test-string-infunction', 'wow');
    var value = sharedPreferences.getString('test-string-infunction');


    print(value);
    expect(value, 'wow');

  });

  group('unit test 1: read shared preferences', () {

    test('shared preferences string', () async {

      String value = await sharedPreferencesHelper.readValueFromKey(""test-string"");

      print(value);
      expect(value, 'string-value');

    });
    test('shared preferences empty', () async {

      var value = await sharedPreferencesHelper.readValueFromKey(""does_not_exist"");

      expect(value, null);

    });

  });


  group('unit test 2: write shared preferences', () {
    test('shared preferences string', () async {
      var originalValue = 'test';
      var value = await sharedPreferencesHelper.writeValueToKey(""test-string"", valueString: originalValue);

      SharedPreferences sharedPreferences = await SharedPreferences.getInstance();


      expect(sharedPreferences.getString('test-string'), originalValue);

    });
    test('shared preferences int', () async {

      var originalValue = 420;
      var value = await sharedPreferencesHelper.writeValueToKey(""test-int"", valueInt: originalValue);

      SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

      expect(sharedPreferences.getInt('test-int'), originalValue);

    });

    test('shared preferences bool', () async {
      var originalValue = true;
      var value = await sharedPreferencesHelper.writeValueToKey(""test-bool"", valueBool: originalValue);
      SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

      expect(sharedPreferences.getBool('test-bool'), originalValue);

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

<p>shared_preferences_helper.dart:</p>

<pre><code>import 'dart:async';

import 'package:shared_preferences/shared_preferences.dart';



// this class is meant to relieve developers from boilerplate code
class SharedPreferencesHelper {

  Future&lt;dynamic&gt; readValueFromKey(String key) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.get(key) ?? null;
  }

  writeValueToKey(String key, {String valueString, bool valueBool, int valueInt}) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    if(valueString != null){
      sharedPreferences.setString(key, valueString);
    }
    if(valueBool != null) {
      sharedPreferences.setBool(key, valueBool);
    }
    if(valueInt != null) {
      sharedPreferences.setInt(key, valueInt);
    }
  }

}
</code></pre>

<p>stacktrace:</p>

<pre><code>Testing started at 12:10 ...
/home/geordy/SoftwareDevelopment/flutter/flutter_linux_v1.2.1-stable/flutter/bin/flutter --no-color test --machine test/shared_preferences_helper_test.dart
dart:core                                                 _AssertionError._throwNew
package:shared_preferences/shared_preferences.dart 33:16  SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                _AsyncAwaitCompleter.completeError
package:shared_preferences/shared_preferences.dart        SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                _asyncThenWrapperHelper
package:shared_preferences/shared_preferences.dart        SharedPreferences.getInstance
test/shared_preferences_helper_test.dart 30:67            main.&lt;fn&gt;

'package:shared_preferences/shared_preferences.dart': Failed assertion: line 33 pos 16: 'key.startsWith(_prefix)': is not true.

dart:core                                                            _AssertionError._throwNew
package:shared_preferences/shared_preferences.dart 33:16             SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                           _AsyncAwaitCompleter.completeError
package:shared_preferences/shared_preferences.dart                   SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                           _asyncThenWrapperHelper
package:shared_preferences/shared_preferences.dart                   SharedPreferences.getInstance
package:shoppaworld_client_app/shared_preferences_helper.dart 20:67  SharedPreferencesHelper.readValueFromKey

'package:shared_preferences/shared_preferences.dart': Failed assertion: line 33 pos 16: 'key.startsWith(_prefix)': is not true.

dart:core                                                            _AssertionError._throwNew
package:shared_preferences/shared_preferences.dart 33:16             SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                           _AsyncAwaitCompleter.completeError
package:shared_preferences/shared_preferences.dart                   SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                           _asyncThenWrapperHelper
package:shared_preferences/shared_preferences.dart                   SharedPreferences.getInstance
package:shoppaworld_client_app/shared_preferences_helper.dart 20:67  SharedPreferencesHelper.readValueFromKey

'package:shared_preferences/shared_preferences.dart': Failed assertion: line 33 pos 16: 'key.startsWith(_prefix)': is not true.

dart:core                                                            _AssertionError._throwNew
package:shared_preferences/shared_preferences.dart 33:16             SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                           _AsyncAwaitCompleter.completeError
package:shared_preferences/shared_preferences.dart                   SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                           _asyncThenWrapperHelper
package:shared_preferences/shared_preferences.dart                   SharedPreferences.getInstance
package:shoppaworld_client_app/shared_preferences_helper.dart 25:67  SharedPreferencesHelper.writeValueToKey

'package:shared_preferences/shared_preferences.dart': Failed assertion: line 33 pos 16: 'key.startsWith(_prefix)': is not true.

dart:core                                                            _AssertionError._throwNew
package:shared_preferences/shared_preferences.dart 33:16             SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                           _AsyncAwaitCompleter.completeError
package:shared_preferences/shared_preferences.dart                   SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                           _asyncThenWrapperHelper
package:shared_preferences/shared_preferences.dart                   SharedPreferences.getInstance
package:shoppaworld_client_app/shared_preferences_helper.dart 25:67  SharedPreferencesHelper.writeValueToKey

'package:shared_preferences/shared_preferences.dart': Failed assertion: line 33 pos 16: 'key.startsWith(_prefix)': is not true.

dart:core                                                            _AssertionError._throwNew
package:shared_preferences/shared_preferences.dart 33:16             SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                           _AsyncAwaitCompleter.completeError
package:shared_preferences/shared_preferences.dart                   SharedPreferences.getInstance
===== asynchronous gap ===========================
dart:async                                                           _asyncThenWrapperHelper
package:shared_preferences/shared_preferences.dart                   SharedPreferences.getInstance
package:shoppaworld_client_app/shared_preferences_helper.dart 25:67  SharedPreferencesHelper.writeValueToKey

'package:shared_preferences/shared_preferences.dart': Failed assertion: line 33 pos 16: 'key.startsWith(_prefix)': is not true.
</code></pre>
",https://stackoverflow.com/questions/55100871/flutter-packageshared-preferences-shared-preferences-dart-failed-assertion,"['unit-testing', 'dart', 'flutter', 'sharedpreferences']",1873,True,5,1
Test service method that has @PreAuthorize with JUnit,"<p>In Spring Boot 1.4.1, I want to do unit testing (not integration testing) on a service method that has restricted access with @PreAuthorize.</p>

<p>The problem is the @PreAuthorize doesn't seem to be checked when launching the test solo from Eclipse (haven't try with mvn test yet).</p>

<p>Then, if I miraculously manage to run the test correctly, I will try to work with the StudyService interface, not the impl.</p>

<p>Here is my test class :</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class TestMethodSecurity {

    private static final Long STUDY_ID = 1L;

    @Mock
    private StudyRepository studyRepository;

    @InjectMocks
    private StudyServiceImpl studyService;


    @Before
    public void setup() {
        given(studyRepository.findOne(STUDY_ID)).willReturn(ModelsUtil.createStudy());
    }


    @Test
    public void findByIdWithoutAccessRightTest() {
        Study study = studyService.findById(STUDY_ID);
    }
}
</code></pre>

<p>This is the service :</p>

<pre><code>@Service
public class StudyServiceImpl implements StudyService {


    @Autowired
    private StudyRepository studyRepository;


    @Override
    @PreAuthorize(""hasAnyRole('DOES NOT EVENT CHECK SYNTAX"")
    public Study findById(final Long id) {
        return studyRepository.findOne(id);
    }

}
</code></pre>

<p>The test succeed, which is a fail.</p>
",https://stackoverflow.com/questions/54424892/test-service-method-that-has-preauthorize-with-junit,"['java', 'spring', 'spring-boot', 'junit', 'spring-security']",5240,True,5,3
ngx-translate instant function is not a function thrown: Unit testing,"<p>I'm fairly new for unit testing and Angular, and i'm trying to write some unit tests for my project.</p>

<p>The error i'm getting is;</p>

<pre><code>Uncaught TypeError: _this.translate.instant is not a function thrown
Expected null to be truthy.
</code></pre>

<p>The imports of the component.spec file includes</p>

<pre><code>beforeEach(async(() =&gt; {
TestBed.configureTestingModule({
  imports:[
    ClarityModule,
    RouterTestingModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (http: HttpClient) =&gt; new TranslateHttpLoader(http, 'assets/i18n/', '.json'),
        deps: [HttpClient]
      }
    }),
    HttpClientModule
  ],
  declarations: [
    HeaderComponent,
    LanguageSelectorComponent
  ],
  providers: [
    { provide: Store, useClass: TestStore },
    { provide: TranslateService, useClass: TranslateServiceStub },
    { provide: NGXLogger, useClass: NGXLoggerMock }
  ]
})
.compileComponents();
}));
</code></pre>

<p>I understand that <code>TranslateServiceStub</code> does not include a 'instant' function. Is this the cause of this error? if so, how can i mock translate.instant function?</p>

<p>Or is there any way to load the translations file in the spec file before instant method gets called?</p>

<p>Any suggestion would be greatly helpful. Thanks a lot!</p>
",https://stackoverflow.com/questions/57112046/ngx-translate-instant-function-is-not-a-function-thrown-unit-testing,"['angular', 'typescript', 'unit-testing', 'karma-jasmine', 'ngx-translate']",9262,True,2,1
Vue packages version mismatch,"<p>I'm trying to add unit testing to an existing vue project via jest, but when I attempt to run my first test I get an error that says </p>

<blockquote>
  <p>Vue packages version mismatch:</p>
</blockquote>

<pre><code>- vue@2.5.16
- vue-template-compiler@2.6.6

This may cause things to work incorrectly. Make sure to use the same version for both.
If you are using vue-loader@&gt;=10.0, simply update vue-template-compiler.
If you are using vue-loader@&lt;10.0 or vueify, re-installing vue-loader/vueify should bump vue-template-compiler to the latest.
</code></pre>

<p>But looking at my packages, my current vue version <strong>is</strong> 2.6.6 not 2.5.16. I have no idea where it's seeing this 2.5.16 version. I don't have vue installed globally, only @vue/cli@3.4.0. Any help would be appreciated. Below you can find my package.json that contains my jest configuration.</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>{
  ""version"": ""1.0.0"",
  ""name"": ""asp.net"",
  ""private"": true,
  ""dependencies"": {
    ""@babel/core"": ""^7.4.0"",
    ""@tinymce/tinymce-vue"": ""^1.1.0"",
    ""@types/bootstrap"": ""^3.3.40"",
    ""@types/jest"": ""^24.0.11"",
    ""@types/jquery"": ""^2.0.51"",
    ""@types/jquery.validation"": ""^1.16.5"",
    ""@types/jqueryui"": ""^1.12.6"",
    ""@types/kendo-ui"": ""^2018.3.0"",
    ""@types/knockout"": ""^3.4.60"",
    ""@types/moment"": ""^2.13.0"",
    ""axios"": ""^0.18.0"",
    ""axios-cache-adapter"": ""^2.1.1"",
    ""browser-detect"": ""^0.2.28"",
    ""es6-promise"": ""^4.2.5"",
    ""file-saver"": ""^1.3.8"",
    ""knockout"": ""^3.4.2"",
    ""moment-timezone"": ""^0.5.23"",
    ""query-string"": ""^6.2.0"",
    ""tinymce-vue"": ""^1.0.0"",
    ""url-search-params-polyfill"": ""^5.0.0"",
    ""vee-validate"": ""^2.1.3"",
    ""vue"": ""^2.6.6"",
    ""vue-class-component"": ""^6.3.2"",
    ""vue-multiselect"": ""^2.1.3"",
    ""vue-notification"": ""^1.3.13"",
    ""vue-property-decorator"": ""^7.2.0"",
    ""vue-router"": ""^3.0.2"",
    ""vuejs-datepicker"": ""^1.5.4"",
    ""vuex"": ""^3.0.1"",
    ""vuex-persistedstate"": ""^2.5.4""
  },
  ""scripts"": {
    ""dev"": ""webpack --mode development --watch --hot"",
    ""test"": ""npm run test:unit"",
    ""test:unit"": ""jest"",
    ""build"": ""webpack --mode production"",
    ""output"": ""webpack --profile --json &gt; stats.json""
  },
  ""devDependencies"": {
    ""@types/file-saver"": ""^1.3.1"",
    ""@vue/test-utils"": ""^1.0.0-beta.29"",
    ""babel-core"": ""^6.26.3"",
    ""babel-jest"": ""^24.7.1"",
    ""babel-loader"": ""^8.0.4"",
    ""babel-polyfill"": ""^6.26.0"",
    ""babel-preset-env"": ""^1.7.0"",
    ""babel-preset-stage-3"": ""^6.24.1"",
    ""css-loader"": ""^1.0.1"",
    ""hard-source-webpack-plugin"": ""^0.13.1"",
    ""jest"": ""^23.4.2"",
    ""node-sass"": ""^4.10.0"",
    ""printd"": ""^1.0.1"",
    ""sass-loader"": ""^7.1.0"",
    ""ts-jest"": ""^23.10.5"",
    ""ts-loader"": ""^4.5.0"",
    ""typescript"": ""^3.2.1"",
    ""uglifyjs-webpack-plugin"": ""^2.0.1"",
    ""vue-jest"": ""^3.0.4"",
    ""vue-loader"": ""^15.4.2"",
    ""vue-template-compiler"": ""^2.6.6"",
    ""webpack"": ""^4.28.4"",
    ""webpack-bundle-analyzer"": ""^3.0.3"",
    ""webpack-cli"": ""^3.1.2"",
    ""webpack-hot-middleware"": ""^2.24.3""
  },
  ""jest"": {
    ""moduleFileExtensions"": [
      ""js"",
      ""ts"",
      ""json"",
      ""vue""
    ],
    ""moduleDirectories"": [
      ""."",
      ""&lt;rootDir&gt;/Scripts"",
      ""&lt;rootDir&gt;/Scripts/VueModules"",
      ""&lt;rootDir&gt;/Scripts/VueModules/SharedComponents"",
      ""&lt;rootDir&gt;/Scripts/VueModules/Candidates/"",
      ""node_modules""
    ],
    ""moduleNameMapper"": {
      ""^@candidates$"": ""&lt;rootDir&gt;/Scripts/VueModules/Candidates"",
      ""^@shared$"": ""&lt;rootDir&gt;/Scripts/VueModules/SharedComponents"",
      ""^@app$"": ""&lt;rootDir&gt;/Scripts/VueModules"",
      ""\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$"": ""&lt;rootDir&gt;/Scripts/VueModules/__mocks__/fileMock.js"",
      ""\\.(css|less|scss|sass)$"": ""&lt;rootDir&gt;/Scripts/VueModules/__mocks__/styleMock.js""
    },
    ""transform"": {
      "".*\\.(vue)$"": ""vue-jest"",
      ""^.+\\.tsx?$"": ""ts-jest""
    },
    ""transformIgnorePatterns"": [
      ""node_modules/(?!vue)""
    ],
    ""testURL"": ""http://localhost/"",
    ""testRegex"": ""(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$""
  }
}</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/55906997/vue-packages-version-mismatch,"['vue.js', 'jestjs']",8813,True,2,4
What To Unit Test,"<p>I'm a bit confused how much I should dedicate on Unit Tests.</p>

<p>Say I have a simple function like:</p>

<pre><code>appendRepeats(StringBuilder strB, char c, int repeats)
</code></pre>

<p>[This function will append char c repeats number of times to strB.
e.g.:</p>

<pre><code>strB = ""hello""
c = ""h""
repeats = 5
// result
strB = ""hellohhhhh""
</code></pre>

<p>]</p>

<p>For unit testing this function, I feel there's already so many possibilities:</p>

<ul>
<li>AppendRepeats_ZeroRepeats_DontAppend</li>
<li>AppendRepeats_NegativeRepeats_DontAppend</li>
<li>AppendRepeats_PositiveRepeats_Append</li>
<li>AppendRepeats_NullStrBZeroRepeats_DontAppend</li>
<li>AppendRepeats_NullStrBNegativeRepeats_DontAppend</li>
<li>AppendRepeats_NullStrBPositiveRepeats_Append</li>
<li>AppendRepeats_EmptyStrBZeroRepeats_DontAppend</li>
<li>AppendRepeats_EmptyStrBNegativeRepeats_DontAppend</li>
<li>AppendRepeats_EmptyStrBPositiveRepeats_Append</li>
<li>etc. etc.
strB can be null or empty or have value.
c can be null or have value
repeats can be negative or positive or zero</li>
</ul>

<p>That seems already 3 * 2 * 3 = 18 test methods. Could be a lot more on other functions if those functions also need to test for special characters, Integer.MIN_VALUE, Integer.MAX_VALUE, etc. etc.
What should be my line of stopping?
Should I assume for the purpose of my own program:
strB can only be empty or have value
c has value
repeats can only be empty or positive</p>

<p>Sorry for the bother. Just genuinely confused how paranoid I should go with unit testing in general. Should I stay within the bounds of my assumptions or is that bad practice and should I have a method for each potential case in which case, the number of unit test methods would scale exponentially quite quick.</p>
",https://stackoverflow.com/questions/56807388/what-to-unit-test,"['java', 'unit-testing', 'testing', 'junit']",184,True,3,4
"Why is 1 000 000 not equal to 1000000.toString(&quot;N&quot;, new CultureInfo(&quot;fr-FR&quot;))","<p>I writing some unit tests around string conversions and currency.</p>

<p>I'm testing that the string is returned in the format that I expect it, given the CultureInfo the method is passed.</p>

<pre><code> public string GetOverspendAmount(double _amount, CultureInfo cultureInfo)
 {
    return amount.ToString(""N"", cultureInfo);
 }
</code></pre>

<p>I'm unit testing this bit of code with the following call -</p>

<pre><code>double amount = 1000000;
CultureInfo ci = new CultureInfo(""fr-FR"", false);

GetOverspendAmount(amount, ci).Should().Be(""1 000 000"");
</code></pre>

<p>but the test fails. The expected and actual look identical but when put into an ascii converter the following results are shown</p>

<pre><code>Expected - 1 000 000
49 32 48 48 48 32 48 48 48

Actual - 1 000 000
049 194 160 048 048 048 194 160 048 048 048
</code></pre>

<p>They're not normal spaces, but I'd like to know what they are, and why they aren't just normal spaces?</p>
",https://stackoverflow.com/questions/57807549/why-is-1-000-000-not-equal-to-1000000-tostringn-new-cultureinfofr-fr,"['c#', 'unit-testing', 'formatting', 'tostring', 'cultureinfo']",89,True,2,1
How to mock custom UserServiceDetails in SpringSecurity Bean for unit-testing?,"<p>I have <code>Spring Boot</code> application with basic auth enabled. <code>UserServiceDetails</code> consumed from DB. For the unit-testing purpose, I want to mock it, so the data will be consumed from elsewhere.</p>

<p>How can I do it?</p>

<p>My question is not how to mock <code>UserServiceDetails</code> itself but how to mock the way that I can use it to test Controllers with basic auth.</p>

<p>The below is my <code>SpringSecurity</code> config:</p>

<pre><code>@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            ""/"",
            ""/csrf"",
            ""/swagger-resources"",
            ""/swagger-resources/**"",
            ""/configuration/ui"",
            ""/configuration/security"",
            ""/swagger-ui.html"",
            ""/webjars/**""
    };

    @Autowired
    @Qualifier(""customUserDetailsService"")
    private UserDetailsService userDetailsService;

    private final static Integer bCryptEncryptionLevel = 8;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder(bCryptEncryptionLevel);
    }

    public SecurityConfig() {
        super();
    }

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder.authenticationProvider(authenticationProvider());
        authManagerBuilder.userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
        return authenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                    .antMatchers(AUTH_WHITELIST).permitAll()
                    // allow default swagger docket
                    .regexMatchers(""\\A/v2/api-docs\\Z"").permitAll()
                    // require auth for any other swagger docket
                    .regexMatchers(""\\A/v2/api-docs?.*\\Z"").authenticated()
                    .antMatchers(""/**"").authenticated()
                .and()
                .httpBasic()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
</code></pre>

<p>To summarize, how can I mock <code>UserServiceDetails</code> into <code>SpringSecurity</code> config, so I can unit-test controllers into my <code>Spring Boot</code> app?</p>
",https://stackoverflow.com/questions/58353403/how-to-mock-custom-userservicedetails-in-springsecurity-bean-for-unit-testing,"['java', 'spring-boot', 'unit-testing', 'spring-security']",235,False,2,1
Unit test pass string argument any string value except null or empty,"<p>I am unit testing controller logic.  I have a controller action which takes a string parameter like so:</p>

<pre><code>public async Task&lt;IActionResult&gt; Get(string searchCriterion)
{
    if (string.IsNullOrEmpty(searchCriterion))
    {
        // Log modelstate errors
        return BadRequest(""Hello"");
    }

    // etc...
}
</code></pre>

<p>Please note the guard which checks for <code>string.IsNullOrEmpty(searchCriterion)</code>.</p>

<p>In my unit tests I like to use <code>It.IsAny&lt;string&gt;()</code>:</p>

<pre><code>// Act
var result = await controller.GetSearchNetworkAsync(It.IsAny&lt;string&gt;());
</code></pre>

<p>The guard means I cannot use this because <code>It.IsAny&lt;string&gt;()</code> means that the test string could indeed by null ot empty.</p>

<p><strong>My question is: can I pass the argument, in my unit test, that corresponds to ""any string value except null or empty""?</strong></p>

<p><strong>Edit</strong></p>

<p>Please find the full unit test...</p>

<pre><code>    [Fact]
    public async Task GetSearchNetworkAsync_ReturnsOkWithNetworkListViewModelCollection_Rn()
    {
        // Arrange
        var mockRepo = new Mock&lt;IUserRepository&gt;();
        mockRepo.Setup(repo =&gt; repo.GetUserAndNetworkAsync(It.IsAny&lt;string&gt;()))
             .ReturnsAsync(GetOwnUserProfile());
        mockRepo.Setup(repo =&gt; repo.SearchBirdersToFollowAsync(It.IsAny&lt;ApplicationUser&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;IEnumerable&lt;string&gt;&gt;()))
            .ReturnsAsync(GetListOfApplicationUsers(3));

        var mockUnitOfWork = new Mock&lt;IUnitOfWork&gt;();

        var controller = new UserController(_mapper, mockUnitOfWork.Object, _logger.Object, mockRepo.Object);

        controller.ControllerContext = new ControllerContext()
        {
            HttpContext = new DefaultHttpContext() { User = GetTestClaimsPrincipal() }
        };

        // Act
        //var result = await controller.GetSearchNetworkAsync(It.IsAny&lt;string&gt;());
        var result = await controller.GetSearchNetworkAsync(It.Is&lt;string&gt;(str =&gt; !string.IsNullOrEmpty(str)));

        // Assert
        var objectResult = result as ObjectResult;
        Assert.NotNull(objectResult);
        Assert.IsType&lt;OkObjectResult&gt;(result);
        Assert.True(objectResult is OkObjectResult);
        Assert.Equal(StatusCodes.Status200OK, objectResult.StatusCode);
        Assert.IsType&lt;List&lt;NetworkUserViewModel&gt;&gt;(objectResult.Value);

        var model = objectResult.Value as List&lt;NetworkUserViewModel&gt;;
        Assert.Equal(3, model.Count);
    }
</code></pre>
",https://stackoverflow.com/questions/58126004/unit-test-pass-string-argument-any-string-value-except-null-or-empty,"['c#', '.net-core', 'xunit.net']",4495,True,2,2
How to test Vuex module using Mocha and Chai,"<p>I'm currently using Nuxt and I would like to do unit testing in my vuex modules. </p>

<p>I'm using vuex modules and here's my index.js</p>

<p><strong>store/index.js</strong></p>

<pre><code>import Vuex from 'vuex';

import * as user from ""~/store/modules/users"";

const createStore = () =&gt; {
  return new Vuex.Store({
    state: {},
    mutations: {},
    modules: {
      user
    }
  });
};

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

<p>and here's the vuex for users (I made it very simple by mutating the count only but I'm doing api requests here)</p>

<p><strong>store/modules/user.js</strong></p>

<pre><code>export const state = {
  count: 0
}

export const mutations = {
  INCREMENT(state, user) {
    state.count += 1;
  }
}

export const actions = {
  incrementCount({commit}) {
    commit('INCREMENT');
  }
}

export const getters = {
  count(state) {
    return state.count;
  }
}
</code></pre>

<p>I would like to use Mocha and Chai, for testing state, actions, mutations, and getters for each vuex modules.</p>

<p>Can anyone give a sample for doing a unit test for this?</p>
",https://stackoverflow.com/questions/54742902/how-to-test-vuex-module-using-mocha-and-chai,"['vue.js', 'mocha.js', 'vuex', 'nuxt.js', 'vuex-modules']",931,False,2,0
Warning: Can&#39;t call setState on a component that is not yet mounted,"<p>I am getting this warning when I tried to change the setstate input value while unit testing(jest)</p>

<p>Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to <code>this.state</code> directly or define a <code>state = {};</code> class property with the desired state in the Login component.
My code is:</p>

<pre><code>this.onChangeEvent = this.onChangeEvent.bind(this);

this.state = { email: '' }

componentDidMount() { this.onChangeEvent(); }

componentWillUnmount() { }

onChangeEvent(event) {     
    this.setState({ email: e.target.value });     
}
</code></pre>

<p>I couldn't find right solution for this warning. Can someone help me to resolve this warning?</p>
",https://stackoverflow.com/questions/58123828/warning-cant-call-setstate-on-a-component-that-is-not-yet-mounted,"['javascript', 'reactjs', 'jestjs', 'setstate']",5059,True,1,2
"Using jest-express, how to unit test that a middleware is being called for a given request?","<p>I've started using <a href=""https://github.com/jameswlane/jest-express"" rel=""nofollow noreferrer""><em><strong>jest-express</strong></em></a> to mock some other express-related things but am not seeing how to test the following. Here's my setup:</p>
<p><strong>./router.js</strong></p>
<pre class=""lang-js prettyprint-override""><code>import express from &quot;express&quot;;

const router = express.Router();
const subRouter = express.Router();
const middlewareA = (req, res) =&gt; res.send(&quot;Made it to A!&quot;);
const middlewareB = (req, res) =&gt; res.send(&quot;Made it to B!&quot;);

subRouter.use(&quot;/a&quot;, middlewareA);
subRouter.use(&quot;/b&quot;, middlewareB);
router.use(&quot;/world&quot;, subRouter);

export default router;
</code></pre>
<p><strong>./server.js</strong></p>
<pre class=""lang-js prettyprint-override""><code>import express from &quot;express&quot;;
import router from &quot;./router&quot;;

const app = express();
app.use(&quot;/hello&quot;, router);
app.use(&quot;*&quot;, (req, res) =&gt; res.send(&quot;No router used&quot;));
app.listen(3000);
</code></pre>
<p>I would like to write a unit test similar to the following.</p>
<pre class=""lang-js prettyprint-override""><code>it(`should use &quot;middlewareA&quot; for a request to &quot;/hello/world/a&quot;`, () =&gt; {
  // ???
})
</code></pre>
<p>I'm still new to unit testing express (and Jest for that matter). I assume I would need to mock <code>middlewareA</code>, but how do I mock making a request to <code>&quot;/hello/world/a&quot;</code> through the express application to see if the mock <code>middlewareA</code> was called?</p>
<p>Or am I approaching this test wrong?</p>
",https://stackoverflow.com/questions/54836180/using-jest-express-how-to-unit-test-that-a-middleware-is-being-called-for-a-giv,"['unit-testing', 'express', 'jestjs']",447,False,4,0
How to unit test azure functions blob storage trigger option?,"<p>I have an azure function which is triggered when a zip file is uploaded to an azure blob storage container. I unzip the file in memory and process the contents and add/update the result into a database. While for the db part I can use the in memory db option. Somehow am not too sure how to simulate the blob trigger for  unit testing this azure function. </p>

<p>All the official samples and some blogs mostly talk about Http triggers(mocking httprequest) and queue triggers (using IAsynCollection). </p>

<pre><code>[FunctionName(""AzureBlobTrigger"")]
        public void Run([BlobTrigger(""logprocessing/{name}"", Connection = ""AzureWebJobsStorage"")]Stream blobStream, string name, ILogger log)
        {
            log.LogInformation($""C# Blob trigger function Processed blob\n Name:{name} \n Size: {blobStream.Length} Bytes"");
            //processing logic
        }
</code></pre>
",https://stackoverflow.com/questions/57777066/how-to-unit-test-azure-functions-blob-storage-trigger-option,"['azure', 'azure-functions', 'azure-blob-storage']",4176,True,4,1
Unit Test : Observer onChanged should be called twice instead of once,"<p>Why do I get different results when unit testing my ViewModel?</p>

<p>I got two tests. When I launch each test individually that's ok but when I launch all tests in a row I got an error.
It's a ViewModel that change state each time I got a return from an 
API. I expect to get <code>android.arch.lifecycle.Observer.onChanged</code> called two times but it's just called once for the second test.
Unit test works fine when I replace <code>verify(view, times(2)).onChanged(arg.capture())</code> with <code>verify(view, atLeastOnce()).onChanged(arg.capture())</code> at the first test.</p>

<p>UserViewModel :</p>

<pre><code>class UserViewModel(
        private val leApi: LeApi
): ViewModel() {
    private val _states = MutableLiveData&lt;ViewModelState&gt;()
    val states: LiveData&lt;ViewModelState&gt;
        get() = _states

    fun getCurrentUser() {
        _states.value = LoadingState
        leApi.getCurrentUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        { user -&gt; _states.value = UserConnected(user) },
                        { t -&gt; _states.value = FailedState(t) }
                )
        }
    }
}
</code></pre>

<p>UserViewModelTest :</p>

<pre><code>@RunWith(MockitoJUnitRunner::class)
class UserViewModelTest {

    lateinit var userViewModel: UserViewModel

    @Mock
    lateinit var view: Observer&lt;ViewModelState&gt;

    @Mock
    lateinit var leApi: LeApi

    @get:Rule
    val rule = InstantTaskExecutorRule()

    @Before
    fun setUp() {
        RxAndroidPlugins.setInitMainThreadSchedulerHandler { Schedulers.trampoline() }
        userViewModel = UserViewModel(leApi)
        userViewModel.states.observeForever(view)
    }

    @Test
    fun testGetCurrentUser() {
        val user = Mockito.mock(User::class.java)
        `when`(leApi.getCurrentUser()).thenReturn(Single.just(user))
        userViewModel.getCurrentUser()

        val arg = ArgumentCaptor.forClass(ViewModelState::class.java)
        verify(view, times(2)).onChanged(arg.capture())

        val values = arg.allValues

        assertEquals(2, values.size)
        assertEquals(LoadingState, values[0])
        assertEquals(UserConnected(user), values[1])
    }

    @Test
    fun testGetCurrentUserFailed() {
        val error = Throwable(""Got error"")
        `when`(leApi.getCurrentUser()).thenReturn(Single.error(error))
        userViewModel.getCurrentUser()

        val arg = ArgumentCaptor.forClass(ViewModelState::class.java)
        verify(view, times(2)).onChanged(arg.capture()) // Error occurred here. That's the 70th line from stack trace.

        val values = arg.allValues
        assertEquals(2, values.size)
        assertEquals(LoadingState, values[0])
        assertEquals(FailedState(error), values[1])
    }
}
</code></pre>

<p>Expected :
All tests passed.</p>

<p>Actual :</p>

<pre><code>org.mockito.exceptions.verification.TooLittleActualInvocations: 
view.onChanged(&lt;Capturing argument&gt;);
Wanted 2 times:
-&gt; at com.dev.titi.toto.mvvm.UserViewModelTest.testGetCurrentUserFailed(UserViewModelTest.kt:70)
But was 1 time:
-&gt; at android.arch.lifecycle.LiveData.considerNotify(LiveData.java:109)
</code></pre>
",https://stackoverflow.com/questions/55874840/unit-test-observer-onchanged-should-be-called-twice-instead-of-once,"['android', 'unit-testing', 'mockito', 'android-viewmodel', 'rx-kotlin']",4377,True,4,1
How to mock NATS microservices?,"<p>I want to test microservices. Microservices communicate via NATS. I see several test levels for it:
Unit testing - one container format;
Integration testing - several container formats;
e2e via GUI.</p>

<p>I can't find a solution for the first test level. How can I isolate  a container format that communicates with others via NATS protocol? I tried doing it based on <a href=""https://www.npmjs.com/package/mountebank"" rel=""nofollow noreferrer"">mountebank</a> via TCP, but that doesn't seem to be right.</p>

<p>How do you test your microservices in NATS? Does it make any sense to do it via TCP?</p>
",https://stackoverflow.com/questions/58964556/how-to-mock-nats-microservices,"['node.js', 'testing', 'automated-tests', 'nats.io']",605,False,4,0
How to test function calling multiple other functions?,"<p>I am writing an ExpressJS Middleware that modifies request object a bit and checks if user has access to that specific page. I have a problem with unit-testing it. I've written separate tests for every method except one: <code>handler</code>. How can I test <code>handler</code> function? Should I test it? Or should I just ignore it with <code>istanbul ignore next</code> as I've got every other function covered? Or maybe I should somehow rewrite my <code>handler</code> function to make it testable? </p>

<pre><code>class Example {

constructor(request, response, next, userAccountService) {
    this.req = request;
    this.res = response;
    this.next = next;
    this.userAccountService = userAccountService;
}

removeTokenFromQuery() {
    delete this.req.query.token;
}

isValidRequest() {
    if (!this.req.secure) {
        return false;
    }

    if (typeof this.req.query.token !== 'undefined') {
        return false;
    }

    if (typeof this.req.query.unsupportedQueryParam !== 'undefined') {
        return false;
    }

    return true;
}

isPageAccessibleForUser() {
    return this.userAccountService.hasAccess('example');
}

async handler() {
    this.removeTokenFromQuery();

    if (!this.isValidRequest()) {
        throw new Error('Invalid request');
    }

    if (!this.isPageAccessibleForUser()) {
        this.res.statusCode(500);
        this.res.end();
        return;
    }

    this.next();
}

}
</code></pre>

<p>Then it's called as Express middleware:</p>

<pre><code>this.app.use((res, req, next) =&gt; {
    const exampleObj = new Example(res, req, next, userAccServ);
    exampleObj.handler();
});
</code></pre>
",https://stackoverflow.com/questions/56792024/how-to-test-function-calling-multiple-other-functions,"['javascript', 'unit-testing', 'express', 'mocha.js']",704,True,1,1
How to install FSharp.xUnit?,"<p>I've installed Visual Studio 2017 and included the test package and the F# package. I'm trying to run a simple test using xUnit but it says xUnit is not found.</p>

<pre><code>module HelloWorldTest

open FsUnit.xUnit
open Xunit

open System.Diagnostics

[&lt;Fact&gt;]
let ``Say Hello`` () =
    Assert.True(true)
</code></pre>

<p>Error</p>

<pre><code>The namespace or module 'FsUnit' is not defined.
</code></pre>

<p>I tried installing the package with <code>dotnet</code> but that produces an error.</p>

<pre><code>&gt; dotnet add package FSharp.xUnit 
  Writing C:\Temp\tmp8DAB.tmp
info : Adding PackageReference for package 'FSharp.xUnit' into project  'C:\Users\mjohn\workspace\fsharp\hello-world\HelloWorld.fsproj'.
log  : Restoring packages for C:\Users\mjohn\workspace\fsharp\hello-world\HelloWorld.fsproj
...
error: Unable to find package FSharp.Core. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages
error: Unable to find package FsUnit.xUnit. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages
error: Unable to find package xunit. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages
error: Unable to find package xunit.runner.visualstudio. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages
error: Unable to find package FSharp.xUnit. No packages exist with this id in source(s): Microsoft Visual Studio Offline Packages
error: Unable to find package Microsoft.NET.Test.Sdk with version (&gt;= 16.0.0)
error:   - Found 1 version(s) in Microsoft Visual Studio Offline Packages [ Nearest version: 15.9.0]
error: Package 'FSharp.xUnit' is incompatible with 'all' frameworks in project 'C:\Users\mjohn\workspace\fsharp\hello-world\HelloWorld.fsproj'.
</code></pre>

<p>So how can I install xUnit for F#? This guide from MS unfortunately is lacking any of this information.
<a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-fsharp-with-dotnet-test"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-fsharp-with-dotnet-test</a></p>

<p><strong>EDIT:</strong></p>

<p>After adding the NuGet package source</p>

<pre><code>&gt; dotnet add package FsUnit.xUnit
  Writing C:\Temp\tmp5BA6.tmp
info : Adding PackageReference for package 'FsUnit.xUnit' into project 'C:\Users\mjohn\workspace\fsharp\hello-world\HelloWorld.fsproj'.
log  : Restoring packages for C:\Users\mjohn\workspace\fsharp\hello-world\HelloWorld.fsproj
...
info :   CACHE https://api.nuget.org/v3-flatcontainer/fsunit.xunit/index.json
info : Package 'FsUnit.xUnit' is compatible with all the specified frameworks in project 'C:\Users\mjohn\workspace\fsharp\hello-world\HelloWorld.fsproj'.
info : PackageReference for package 'FsUnit.xUnit' version '3.4.0' updated in file 'C:\Users\mjohn\workspace\fsharp\hello-world\HelloWorld.fsproj'.
</code></pre>
",https://stackoverflow.com/questions/55005343/how-to-install-fsharp-xunit,"['f#', 'xunit']",283,False,1,0
How to use Core Data for main app and unit tests?,"<p>When I try to use Core Data with <code>NSInMemoryStoreType</code> for unit testing I always get this error:</p>

<pre><code>Failed to find a unique match for an NSEntityDescription to a managed object subclass
</code></pre>

<p>This is my object to create the core data stack:</p>

<pre><code>public enum StoreType {
    case sqLite
    case binary
    case inMemory
    .................
}

    public final class CoreDataStack {
        var storeType: StoreType!
        public init(storeType: StoreType) {
            self.storeType = storeType
        }

        lazy var persistentContainer: NSPersistentContainer = {
            let container = NSPersistentContainer(name: ""Transaction"")
            container.loadPersistentStores(completionHandler: { (description, error) in
                if let error = error {
                    fatalError(""Unresolved error \(error), \(error.localizedDescription)"")
                } else {
                    description.type = self.storeType.type

                }
            })

            return container
        }()

        public var context: NSManagedObjectContext {
            return persistentContainer.viewContext
        }

        public func reset() {
            for store in persistentContainer.persistentStoreCoordinator.persistentStores {
                guard let url = store.url else { return }

                try! persistentContainer.persistentStoreCoordinator.remove(store)
                try! FileManager.default.removeItem(at: url)
            }
        }
    }
</code></pre>

<p>And this is how I am using it inside my unit test project:</p>

<pre><code>class MyTests: XCTestCase {

    var context: NSManagedObjectContext!
    var stack: CoreDataStack!

    override func setUp() {
        stack = CoreDataStack(storeType: .inMemory)
        context = stack.context
    }

    override func tearDown() {
        stack.reset()
        context = nil
    }
}
</code></pre>

<p>From what I read <a href=""https://stackoverflow.com/questions/51851485/multiple-nsentitydescriptions-claim-nsmanagedobject-subclass"">here</a> which seems to be the same issue that I have, I have to cleanup everything after every test, which I (think) I am doing.   </p>

<p>Am I not cleaning up correctly ? Is there another way to do this ?</p>
",https://stackoverflow.com/questions/55088704/how-to-use-core-data-for-main-app-and-unit-tests,"['ios', 'swift', 'unit-testing', 'core-data']",989,True,1,2
Test dependencies and testing get and setter together,"<p>I'm quite fresh on Unit Testing and TDD, my doubts are the moment are around the following piece of test I'm running:</p>

<pre><code>class TypeTest extends TestCase
{
private $typeNameForTests = ""staff"";

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

public function testMake()
{
    $type = Type::make($this-&gt;typeNameForTests);

    $this-&gt;assertTrue(
        $type instanceof Type,
        ""make() should return an instance of "" . Type::class
    ); 

    return $type;
}

/**
*   @depends testMake
*/
public function testToString($type)
{
    $this-&gt;asserTrue(
        $type-&gt;__toString() == 'staff',
        ""make() parameter should be set as the type name""
    );
}

/**
* @depends testMake
*/
public function testSetAndGetParent($type)
{
    $parent = $this-&gt;createMock(Type::class);

    $type-&gt;setParent($parent);

    $parent === $type-&gt;getParent();
}

}
</code></pre>

<p>Is it ok the way I am concatenating the two first tests?
Asserting the return of a method is necessary and makes sense on this case?</p>

<p>Does the test dependency (testToString) makes sense there?</p>

<p>And how about testing Get and Set in the same test? </p>

<p>I appreciate any input, as I feel like I may be overthinking some principles...</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/54571204/test-dependencies-and-testing-get-and-setter-together,"['php', 'unit-testing', 'phpunit', 'tdd']",70,True,1,1
Upload iOS app from Xcode to Browserstack,"<p>The problem is that customer has bug on his device – iPad 4 mini, but I don't have this device and on simulator everything works correctly.</p>

<p>My colleagues suggest BrowserStack but I've never worked with that and have some questions:</p>

<ol>
<li>Does BrowserStack use real devices or simulations?</li>
<li>Is that possible to upload build from Xcode to BrowserStack?</li>
</ol>

<p><strong>Update:</strong> I've found how to upload app on their's server but it seems only for unit testing and it's not possible to launch that app manually...</p>

<pre><code>curl -u ""personaldata"" -X POST ""https://api-cloud.browserstack.com/app-automate/upload"" -F ""file=@/path/to/app/file/Application-debug.ipa""
</code></pre>
",https://stackoverflow.com/questions/55758846/upload-ios-app-from-xcode-to-browserstack,"['ios', 'xcode', 'browserstack']",967,True,1,1
Unit Testing - Controller not picking up value from mocked IConfiguration in ASP.NET Core Web API Project,"<p>I am trying to Unit Test my Login Action in ASP.NET Core Web API with mock services, all the mocking works fine but when I try to Mock my <code>IConfiguration</code> file the controller does not pick up the value from it.</p>

<p>Here's my Unit testing code that calls my controller action:</p>

<pre><code>[Fact]
public async Task SignInTest()
{
    // Arrange
    var requestVM = new CustomerSignInRequestVM
    {
        EmailPhone = ""03026993900"",
        RegNum = ""Abc123""
    };

    var config = new Mock&lt;IConfiguration&gt;();
    //HERE I AM SETTING ALL MY CONFIGURATION VALUES TO RETURN SOME FAKE VALUES

    //config.Setup(cf =&gt; cf.GetSection(""Jwt:Encryptionkey"").Value).Returns(""01 02 03"");    
    config.Setup(x =&gt; x.GetSection(""Jwt:Encryptionkey"").Value).Returns(""abc"");
    config.Setup(x =&gt; x.GetSection(""Jwt:Issuer"").Value).Returns(""test.com"");
    config.Setup(x =&gt; x.GetSection(""Jwt:ExpiryTimeInMinutes"").Value).Returns(""Jwt:ExpiryTimeInMinutes"");   

    //THIS MOCKING WORK FINE IN CONTROLLER ACTION
    var customerApplication = new Mock&lt;ICustomerApplication&gt;();
    customerApplication.Setup(app =&gt; app.GetCustomer(It.IsAny&lt;SignIn&gt;())).ReturnsAsync(GetCustomerMockData);

    var claimApplication = new Mock&lt;IClaimApplication&gt;();
    claimApplication.Setup(app =&gt; app.GetListByRole(It.IsAny&lt;ApplicationRole&gt;())).ReturnsAsync(new List&lt;ApplicationClaim&gt; { new ApplicationClaim { Active = true, ClaimCode = ""AUC_GA"", ClaimLabel = ""Auction.GetAll"" } });

    //I'm also injecting my IConfiguration object here in my controller setup

    var controller = new CustomerController(customerApplication.Object, null, claimApplication.Object, null, null, config.Object, null);

    // Act
    var response = await controller.SignIn(requestVM, new CancellationToken());
    var okObjectResult = response as OkObjectResult;

    // Assert
    Assert.Equal(200, okObjectResult.StatusCode);
}
</code></pre>

<p>but when I try to retrieve values from <strong>injected</strong> <code>IConfiguration</code> service inside my controller action like this:</p>

<p><code>var Issuer = Configuration[""Jwt:Issuer""],</code></p>

<p>this returns <code>null</code> to me, I am not sure what I am doing wrong here.</p>
",https://stackoverflow.com/questions/55418563/unit-testing-controller-not-picking-up-value-from-mocked-iconfiguration-in-asp,"['c#', 'unit-testing', 'asp.net-core', 'asp.net-core-webapi']",390,True,1,1
Unit test android application with rxjava,"<p>I recently jumped in Android Unit testing and I'm still struggling in writing my unit tests.
I'm trying to test my Presenter, specifically a method that returns a list of repositories from Github Api, 
but I keep getting a Null Pointer Exception and I don't understand why.</p>

<p>RepositoriesPresenter method I want to unit test: </p>

<pre><code>public void presenterLoadRepos(boolean onlineRequired, String owner) {
    // Clear old data on view
    view.clearRepos();

    //recovering access token data from Shared Preferences
    String accessTokenString = repository.getAccessTokenString();
    String accessTokenTypeString = repository.getAccessTokenType();

    if(onlineRequired){
        Disposable disposable = repository.loadRemoteRepos(owner, accessTokenString, accessTokenTypeString, PER_PAGE_VALUE)  //this is line 188
                .subscribeOn(ioScheduler) //this is line 189
                .observeOn(uiScheduler)
                .subscribe(this::handleReturnedData, this::handleError, () -&gt; view.stopLoadingIndicator());
        disposeBag.add(disposable);
    }else {
        Disposable disposable = repository.loadLocalRepos(owner, accessTokenString, accessTokenTypeString, PER_PAGE_VALUE)
                .subscribeOn(ioScheduler)
                .observeOn(uiScheduler)
                .subscribe(this::handleReturnedData, this::handleError, () -&gt; view.stopLoadingIndicator());
        disposeBag.add(disposable);
    }

}
</code></pre>

<p>Whole RepositoriesPresenter class:</p>

<pre><code>public class RepositoriesPresenter implements RepositoriesContract.Presenter, LifecycleObserver {

private static final String TAG = RepositoriesPresenter.class.getSimpleName();


private GitHubChallengeRepository repository;

private RepositoriesContract.View view;

private Scheduler ioScheduler;
private Scheduler uiScheduler;

private CompositeDisposable disposeBag;

@Inject
public RepositoriesPresenter(GitHubChallengeRepository repository, RepositoriesContract.View view,
                             @RunOn(IO) Scheduler ioScheduler, @RunOn(UI) Scheduler uiScheduler) {
    this.repository = repository;
    this.view = view;
    this.ioScheduler = ioScheduler;
    this.uiScheduler = uiScheduler;

    // Initialize this presenter as a lifecycle-aware when a view is a lifecycle owner.
    if (view instanceof LifecycleOwner) {
        ((LifecycleOwner) view).getLifecycle().addObserver(this);
    }

    disposeBag = new CompositeDisposable();
}

@Override @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void onAttach() {
    presenterLoadRepos(false, view.getOwner());
}

@Override @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void onDetach() {
    // Clean up any no-longer-use resources here
    disposeBag.clear();
}


@Override
public void checkRepoPerUser(String owner) {

    //recovering access token data from Shared Preferences;
    String accessTokenString = repository.getAccessTokenString();
    String accessTokenTypeString = repository.getAccessTokenType();

    //Asking for a list of repositories with 1 repository per page.
    //This let us know how many repositories we found and also to deal with error response code
    Disposable disposable = repository.checkReposPerUser(owner, accessTokenString, accessTokenTypeString, ""1"")
            .subscribeOn(ioScheduler)
            .observeOn(uiScheduler)
            .subscribe(this::handleReturnedHeaderData, this::handleHeaderError);
    disposeBag.add(disposable);
}

@VisibleForTesting
private void handleReturnedHeaderData(Response&lt;List&lt;Headers&gt;&gt; response) {
    //getting value 'Link' from response headers in order to count the repositories
    String link = response.headers().get(""Link"");
    String message = response.message();

    //checking GitHub API requests limit
    String limit = response.headers().get(""X-RateLimit-Limit"");
    Log.d(TAG, ""Limit requests: "" + limit);
    String limitRemaining = response.headers().get(""X-RateLimit-Remaining"");
    Log.d(TAG, ""Limit requests remaining: "" + limitRemaining);

    //getting http response code
    int code = response.code();

    switch (code){
        case 404:
            if(message.equalsIgnoreCase(""not found"")){ //User not exists
                view.showUserNotFoundMessage();
            }else{
                view.showErrorMessage(message);
            }
            break;
        case 403:
            //GitHub API requests limit reached
            //Instead of showing an error, we start the login process,
            // store another access token in shared Preferences and resend the same request that failed before
            view.startLogin();
            break;
        case 200:
            if(link == null){ //Link value is not present into the header, it means there's 0 or 1 repo
                Log.d(TAG, ""Total repos for current user is 0 or 1."");
                //get the repository
                searchRepo(view.getOwner()); //Starting looking for data
            }else if( link != null){
                //get last page number: considering that we requested all the repos paginated with
                //only 1 repo per page, the last page number is equal to the total number of repos
                String totalRepoString = link.substring(link.lastIndexOf(""&amp;page="") + 6, link.lastIndexOf(""&gt;""));
                Log.d(TAG, ""Total repos for current user are "" + totalRepoString);

                // TODO once we know how many repositories we have, we can decide how many calls to do (total repositories/100 rounded up )

                //get the repositories
                searchRepo(view.getOwner()); //Starting 3 looking for data
            }
            break;
        default:
            searchRepo(view.getOwner()); //Starting 3 looking for data
            break;
    }
}

private void handleHeaderError(Throwable error) {
    Log.e(TAG, error.getMessage(), error);
    view.showErrorMessage(error.getLocalizedMessage());
}

@Override public void searchRepo(final String owner) {

    view.showProgressBarIfHidden();

    //recovering access token data from Shared Preferences
    String accessTokenString = repository.getAccessTokenString();
    String accessTokenTypeString = repository.getAccessTokenType();

    // Load new one and populate it into view
    Disposable disposable = repository.loadRemoteRepos(owner, accessTokenString, accessTokenTypeString, ""100"")
            .flatMap(Observable::fromIterable)
            .filter(repo -&gt; repo.getName() != null)
            .toList()
            .toObservable()
            .subscribeOn(ioScheduler)
            .observeOn(uiScheduler)
            .subscribe(repos -&gt; {
                if (repos.isEmpty()) {
                    // Clear old data from recycler view
                    view.clearRepos();
                    // Show notification
                    view.showEmptySearchResult();
                } else {
                    // Update recycler view items
                    view.showRepos(repos);

                }
            });

    disposeBag.add(disposable);

}

public void presenterLoadRepos(boolean onlineRequired, String owner) {
    // Clear old data on view
    view.clearRepos();

    //recovering access token data from Shared Preferences
    String accessTokenString = repository.getAccessTokenString();
    String accessTokenTypeString = repository.getAccessTokenType();

    if(onlineRequired){
        Disposable disposable = repository.loadRemoteRepos(owner, accessTokenString, accessTokenTypeString, ""100"")
                .subscribeOn(ioScheduler)
                .observeOn(uiScheduler)
                .subscribe(this::handleReturnedData, this::handleError, () -&gt; view.stopLoadingIndicator());
        disposeBag.add(disposable);
    }else {
        // Load new repositories and paginate them with 100 (GitHub API max) repositories par page.
        Disposable disposable = repository.loadLocalRepos(owner, accessTokenString, accessTokenTypeString, ""100"")
                .subscribeOn(ioScheduler)
                .observeOn(uiScheduler)
                .subscribe(this::handleReturnedData, this::handleError, () -&gt; view.stopLoadingIndicator());
        disposeBag.add(disposable);
    }

}

/**
 * Updates view after loading data is completed successfully.
 */
private void handleReturnedData(List&lt;Repo&gt; list) {
    view.stopLoadingIndicator();
    if (list != null &amp;&amp; !list.isEmpty()) {
        view.showRepos(list);
    } else {
        view.showNoDataMessage();
    }
}

/**
 * Updates view if there is an error after loading data from repository.
 */
private void handleError(Throwable error) {
    if(error.getMessage().equalsIgnoreCase(""http 403 forbidden"")){
        view.startLogin();
    }else {
        view.stopLoadingIndicator();
        view.showErrorMessage(error.getLocalizedMessage());
    }
}

@Override public void getRepo(int repoId) {
    Disposable disposable = repository.getRepo(repoId)
            .filter(repo -&gt; repo != null)
            .subscribeOn(ioScheduler)
            .observeOn(uiScheduler)
            .subscribe(repo -&gt; view.showRepositoryDetail(repo));
    disposeBag.add(disposable);
}
}
</code></pre>

<p>RepositoriesPresenterTest:</p>

<pre><code>import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
//other imports omitted

@RunWith(MockitoJUnitRunner.class)
public class RepositoriesPresenterTest {
    private static final Repo REPO1 = new Repo();
    private static final Repo REPO2 = new Repo();
    private static final Repo REPO3 = new Repo();
    private static final List&lt;Repo&gt; NO_REPOS = Collections.emptyList();
    private static final List&lt;Repo&gt; THREE_REPOS = Arrays.asList(REPO1, REPO2, REPO3);
    public static final String OWNER = ""owner"";
    public static final String ACCESS_TOKEN_STRING = ""access_token_string"";
    public static final String ACCESS_TOKEN_TYPE = ""access_token_type"";
    public static final String PER_PAGE_VALUE = ""per_page_value"";

    @Mock private GitHubChallengeRepository repositoryMock;

    @Mock private RepositoriesContract.View viewMock;

    private TestScheduler testScheduler;

    private RepositoriesPresenter SUT;  //System Under Test

    @Before public void setUp() {
        MockitoAnnotations.initMocks(this);
        testScheduler = new TestScheduler();
        SUT = new RepositoriesPresenter(repositoryMock, viewMock, testScheduler, testScheduler);
    }

    @Test public void repoPresenter_reposReturned_showReposOnViewExpected() {
        // Given
        given(repositoryMock.loadRemoteRepos(  //this is line 128
            OWNER,
            ACCESS_TOKEN_STRING,
            ACCESS_TOKEN_TYPE,
        PER_PAGE_VALUE)).willReturn(Observable.just(THREE_REPOS));

        // When
        SUT.presenterLoadRepos(true, OWNER);  //this is line 135
        testScheduler.triggerActions();

        // Then
        then(viewMock).should().showRepos(THREE_REPOS);
        then(viewMock).should(atLeastOnce()).stopLoadingIndicator();
    }
} 
</code></pre>

<p>This is what I get when I run the test:</p>

<pre><code>java.lang.NullPointerException
at link.mgiannone.githubchallenge.ui.repositories.RepositoriesPresenter.presenterLoadRepos(RepositoriesPresenter.java:189)
at link.mgiannone.githubchallenge.ui.repositories.RepositoriesPresenterTest.repoPresenter_reposReturned_showReposOnViewExpected(RepositoriesPresenterTest.java:138)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.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.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)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

[MockitoHint] RepositoriesPresenterTest.repoPresenter_reposReturned_showReposOnViewExpected (see javadoc for MockitoHint):
[MockitoHint] 1. Unused... -&gt; at link.mgiannone.githubchallenge.ui.repositories.RepositoriesPresenterTest.repoPresenter_reposReturned_showReposOnViewExpected(RepositoriesPresenterTest.java:131)
[MockitoHint]  ...args ok? -&gt; at link.mgiannone.githubchallenge.ui.repositories.RepositoriesPresenter.presenterLoadRepos(RepositoriesPresenter.java:188)


Process finished with exit code 255
</code></pre>

<p>from the stacktrace it seems I'm not using an argument, what am I doing wrong?</p>
",https://stackoverflow.com/questions/54020865/unit-test-android-application-with-rxjava,"['android', 'junit', 'mockito']",548,True,1,2
"Import bootstrap error: Unexpected token, test-utils, working in one test but not another","<p>I'm new to unit testing with jest in vue. </p>

<p>I have added the plugin unit test from here: <a href=""https://www.npmjs.com/package/@vue/cli-plugin-unit-jest"" rel=""nofollow noreferrer"">https://www.npmjs.com/package/@vue/cli-plugin-unit-jest</a></p>

<p>It have created a test folder with another folder called unit where I have placed 2 files: Footer.spec.js and Main.spec.js. It also created a jest.config.js file.</p>

<p>Footer.spec.js</p>

<pre><code>import '../../src/plugins/fontawesome'
import { mount } from '@vue/test-utils'
import Footer from '../../src/components/Footer/Footer.vue'
import BootstrapVue from 'bootstrap-vue'
import { createLocalVue } from '@vue/test-utils'

describe('Footer', () =&gt; {
  const localVue = createLocalVue()
  localVue.use(BootstrapVue)
  const wrapper = mount(Footer, {localVue})

  it('has a FooterPhoneNumber', () =&gt; {
    expect(wrapper.html()).toContain('some HTML')
  })

  it('has a FooterEmail', () =&gt; {
    expect(wrapper.html()).toContain('some HTML')
  })
})
</code></pre>

<p>Main.spec.js</p>

<pre><code>import '../../src/plugins/fontawesome'
import { mount } from '@vue/test-utils'
import Main from '../../src/components/Main.vue'
import BootstrapVueMain from 'bootstrap-vue'
import { createLocalVueMain } from '@vue/test-utils'

describe('Main', () =&gt; {
  const localVueMain = createLocalVueMain()
  localVueMain.use(BootstrapVueMain)
  const wrapper = mount(Main, {localVueMain})

  it('the modal for browser not compatible', () =&gt; {
    expect(wrapper.html()).toContain('some HTML')
  })
})
</code></pre>

<p>From the jest.config.js</p>

<pre><code> transformIgnorePatterns: [
   '/node_modules/(?!(bootstrap|bootstrap-vue)/)',
   '/node_modules/',
 ],
</code></pre>

<p>I'm getting an error because of 2 imports:</p>

<pre><code>     import 'bootstrap/dist/css/bootstrap.css'
     | ^
  18 | import 'bootstrap-vue/dist/bootstrap-vue.css'
</code></pre>

<p>The Footer.spec.js pass the test but the Main.spec.js dosen't.</p>

<p>Any suggestions on how to fix it?</p>
",https://stackoverflow.com/questions/57003909/import-bootstrap-error-unexpected-token-test-utils-working-in-one-test-but-no,"['vue.js', 'jestjs', 'vue-test-utils']",294,False,1,1
Periodic work not reach running state when unit testing WorkManager,"<p>I created a <code>PeriodicWorkRequest</code> from my <code>SyncDatabaseWorker</code>, which like below:</p>

<pre><code>class SyncDatabaseWorker(ctx: Context, params: WorkerParameters) : RxWorker(ctx, params) {

    private val dataManager: DataManager = App.getDataManager()

    override fun createWork(): Single&lt;Result&gt; {
        return Single.create { emitter -&gt;

            dataManager.loadStoresFromServer()
                    .subscribe(object : SingleObserver&lt;List&lt;Store&gt;&gt; {
                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onSuccess(storeList: List&lt;Store&gt;) {
                            if (!storeList.isEmpty()) {
                                emitter.onSuccess(Result.success())
                            } else {
                                emitter.onSuccess(Result.retry())
                            }
                        }

                        override fun onError(e: Throwable) {
                            emitter.onSuccess(Result.failure())
                        }
                    })
        }
    }

    companion object {
        fun prepareSyncDBWorker(): PeriodicWorkRequest {
            val constraints = Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build()

            val myWorkBuilder = PeriodicWorkRequest.Builder(SyncDatabaseWorker::class.java, 7, TimeUnit.DAYS)
                    .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1, TimeUnit.DAYS) // Backoff retry after 1 day
                    .setConstraints(constraints)

            return myWorkBuilder.build()
        }
    }
}
</code></pre>

<p>Then I write unit test base on <a href=""https://developer.android.com/topic/libraries/architecture/workmanager/how-to/testing#periodic-work"" rel=""nofollow noreferrer"">Google's guide</a> like this:</p>

<pre><code>@RunWith(AndroidJUnit4::class)
class SyncDatabaseWorkerTest {
    private lateinit var context: Context

    @Before
    fun setup() {
        context = InstrumentationRegistry.getInstrumentation().targetContext

        val config = Configuration.Builder()
                .setMinimumLoggingLevel(Log.DEBUG)
                .setExecutor(SynchronousExecutor())
                .build()

        // Initialize WorkManager for instrumentation tests.
        WorkManagerTestInitHelper.initializeTestWorkManager(context, config)
    }

    @Test
    @Throws(Exception::class)
    fun testPeriodicWork_WithConstrains() {
        // Create request
        val request = SyncDatabaseWorker.prepareSyncDBWorker()

        val workManager = WorkManager.getInstance(context)
        val testDriver = WorkManagerTestInitHelper.getTestDriver(context)

        // Enqueue and wait for result.
        workManager.enqueue(request).result.get()

        // Check work request is enqueued
        var workInfo = workManager.getWorkInfoById(request.id).get()
        assertThat(workInfo.state, `is`(WorkInfo.State.ENQUEUED))

        // Tells the testing framework the period delay &amp; all constrains is met
        testDriver!!.setPeriodDelayMet(request.id)
        testDriver.setAllConstraintsMet(request.id)

        // Check work request is running
        workInfo = workManager.getWorkInfoById(request.id).get()
        assertThat(workInfo.state, `is`(WorkInfo.State.RUNNING))
    }
}
</code></pre>

<p>It's always in state <code>ENQUEUED</code>, even when <strong>period delay &amp; all constrains is met</strong>.</p>

<pre><code>Expected: is &lt;RUNNING&gt;
but: was &lt;ENQUEUED&gt;
</code></pre>

<p>When I debugged the test &amp; find out that the <code>createWork(): Single&lt;Result&gt;</code> method is also triggered, but why the state is not <code>RUNNING</code>?</p>

<p>May be I'm wrong about the approach, but the documents about unit testing WorkManager is very few now, and I don't know the right way to do it.</p>
",https://stackoverflow.com/questions/57099887/periodic-work-not-reach-running-state-when-unit-testing-workmanager,"['java', 'android', 'unit-testing', 'android-testing', 'android-workmanager']",832,True,1,2
How to specify folder for which I want to include files for code coverage in angular?,"<p>I am using jasmine and karma for unit testing. Istanbul   reporter.</p>

<p>I want to specify which folder is to be considered for code coverage. 
I want to exclude everything else.</p>

<p>Right now I am totally clueless how the configuration works.
the core folder is the only folder I want to consider for code coverage.
(had to paste screenshot because firewall doesnt let me upload images)</p>

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

<p>karma.config:</p>

<pre><code>module.exports = function (config) {
  config.set({
    basePath: '',
    files:['mockData.js', 'mockLocalization.js'],
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      //require('karma-phantomjs-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma'),
      require('karma-scss-preprocessor'),
       require('karma-sonarqube-reporter'),
       require('karma-junit-reporter'),

    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    angularCli: {
      environment: 'dev'
    },
    coverageIstanbulReporter: {

      reports: [ 'html', 'lcov', 'cobertura' ],
      fixWebpackSourcePaths: true,

    },

    junitReporter:{
      useBrowserName: false, 
      outputDir: 'report',
      // will be resolved to basePath (in the same way as files/exclude patterns)
      outputFile: 'karma-report.xml'
    },

    coverageReporter: {
      includeAllSources: false,
      dir: 'coverage',

      reporters: [
        { type: 'html', subdir: 'html' }
      ]
    },

    reporters: ['progress', 'kjhtml','coverage-istanbul'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],    //make sure it is chromeHeadless while running the pipeline otherwise it will fail.
    singleRun: true,
    browserDisconnectTimeout: 20000,
    browserDisconnectTolerance: 3,
    browserNoActivityTimeout: 120000,
    flags: [
      '--disable-web-security',
      '--disable-gpu',
      '--no-sandbox'
    ]
  });
};
</code></pre>

<p><strong>Reporter:</strong></p>

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

<p><strong>EDIT:</strong></p>

<pre><code>const context = require.context('./core', true, /\.spec\.ts$/);
context.keys().map(context);
</code></pre>

<p><a href=""https://i.stack.imgur.com/7aY8X.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/7aY8X.png"" alt=""enter image description here""></a>
LOOKS GOOD!</p>

<p><strong>BUT</strong></p>

<pre><code>const context = require.context('./core', true, /\.spec\.ts$/);
context.keys().map(context);
const context2 = require.context('./modules', true, /\.spec\.ts$/);
context2.keys().map(context2);
</code></pre>

<p>Gives:</p>

<p><a href=""https://i.stack.imgur.com/40MWh.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/40MWh.png"" alt=""enter image description here""></a>
WHY IS IT INCLUDING ASSETS FOLDER ALL OF A SUDDEN??</p>
",https://stackoverflow.com/questions/56952573/how-to-specify-folder-for-which-i-want-to-include-files-for-code-coverage-in-ang,"['javascript', 'angular', 'jasmine', 'karma-jasmine', 'istanbul']",5457,True,1,3
Unit test function that is opening and reading a file,"<p>I am working on learning go with a simple program that is doing some file reading and am working on adding unit testing to my program. I have ran into an issue/question while doing this. I want to unit test the function below and my question is that the function takes a name of the file which is then opened and processed. During testing I do not want to actually pass it a real file. I am wondering is this something I can somehow mock so that I can just pass it a ""fake"" file and have it process that instead? Thanks!    </p>

<pre><code>func openAndReadFile(fileName string) [][]string {
    file, err := os.Open(fileName)
    if err != nil {
        fmt.Printf(""Failed to read file: %s"", fileName)
    }
    r := csv.NewReader(file)
    lines, err := r.ReadAll()
    if err != nil {
        log.Fatal(err)
    }
    return lines
}
</code></pre>
",https://stackoverflow.com/questions/56397240/unit-test-function-that-is-opening-and-reading-a-file,"['unit-testing', 'go']",14234,True,12,3
How to write unit test for Ebean in play framework,"<p>I have an application based on play framework scala version 2.11.1. 
There are couple of methods for which I want to add unit tests. These methods have direct calls to database through Ebean.</p>

<p>I tried with this <a href=""https://ebean.io/docs/setup/testing"" rel=""noreferrer"">link</a> to use mocki-ebean in order to mock these calls. But the import was unsuccessful </p>

<p>I tried with powermock as well. but it requires to setup in-memory ebean server for mock calls. But that is also deprecated to setup in-memory server for unit testing.</p>

<p>Any idea what could be the next direction?</p>
",https://stackoverflow.com/questions/55106265/how-to-write-unit-test-for-ebean-in-play-framework,"['unit-testing', 'playframework', 'ebean']",303,False,6,0
How to do Unit Testing in Kotlin/Native Multiplatform?,"<p>I have follow the tutorial of <a href=""https://kotlinlang.org/docs/tutorials/native/mpp-ios-android.html"" rel=""noreferrer"">https://kotlinlang.org/docs/tutorials/native/mpp-ios-android.html</a> and I wanted to Unit testing the commonTest I created in the SharedModule.</p>

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

<p>Things I tried:</p>

<p>I had tried using kotlin.test in the common file. I research online that you can use JUnit5 but when I imported in the dependencies in the commonTest, I can't access the library of the kotlin.test. Now I had successfully implemented the kotlin.test in the commonTest but how do I run it?</p>

<p>I tried gradlew commonTest.kt but it doesn't work. Please help thanks!</p>

<p>My SharedModule gradle codes:</p>

<pre><code>    apply plugin: 'kotlin-multiplatform'

kotlin {
    targets {
        final def iOSTarget = System.getenv('SDK_NAME')?.startsWith(""iphoneos"") \
                              ? presets.iosArm64 : presets.iosX64

        fromPreset(iOSTarget, 'iOS') {
            binaries {
                framework('SharedCode')
            }
        }

        fromPreset(presets.jvm, 'android')
    }

    sourceSets {
        commonMain.dependencies {
            api 'org.jetbrains.kotlin:kotlin-stdlib-common'
            api 'org.jetbrains.kotlin:kotlin-stdlib'
            //implementation(""com.ionspin.kotlin:bignum:0.0.8"")

            //Testing
            //implementation ""org.jetbrains.kotlinx:kotlinx-coroutines-core-common:$coroutines_version""
            //implementation ""org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serialization_version""
/*
            implementation ""io.ktor:ktor-client-core:$ktor_version""
            implementation ""io.ktor:ktor-client-json:$ktor_version""
            implementation ""io.ktor:ktor-client-logging:$ktor_version""*/

        }

        commonTest.dependencies{
            //implementation (""org.junit.jupiter:junit-jupiter-api:5.2.0"")
            //implementation (""org.junit.jupiter:junit-jupiter-engine:5.0.3"")
            //implementation 'junit:junit:4.12'
            implementation 'org.jetbrains.kotlin:kotlin-test-junit5:1.3.31'
            implementation 'org.jetbrains.kotlin:kotlin-test:1.3.31'
            //implementation ""io.mockk:mockk-common:1.9.3""
            //implementation 'io.kotlintest:kotlintest-runner-junit5:3.3.0'

            //Testing
            //implementation ""org.jetbrains.kotlin:kotlin-test-common""
            //implementation ""org.jetbrains.kotlin:kotlin-test-annotations-common""

            //implementation ""org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version""
            implementation ""io.mockk:mockk:1.8.13.kotlin13""
            implementation ""io.mockk:mockk-common:1.8.13.kotlin13""
            implementation 'org.amshove.kluent:kluent:1.42'
        }

        androidMain.dependencies {
            api 'org.jetbrains.kotlin:kotlin-stdlib'
        }
    }
}

// workaround for https://youtrack.jetbrains.com/issue/KT-27170
configurations {
    compileClasspath
}

task packForXCode(type: Sync) {
    final File frameworkDir = new File(buildDir, ""xcode-frameworks"")
    final String mode = project.findProperty(""XCODE_CONFIGURATION"")?.toUpperCase() ?: 'DEBUG'
    final def framework = kotlin.targets.iOS.binaries.getFramework(""SharedCode"", mode)

    inputs.property ""mode"", mode
    dependsOn framework.linkTask

    from { framework.outputFile.parentFile }
    into frameworkDir

    doLast {
        new File(frameworkDir, 'gradlew').with {
            text = ""#!/bin/bash\nexport 'JAVA_HOME=${System.getProperty(""java.home"")}'\ncd '${rootProject.rootDir}'\n./gradlew \$@\n""
            setExecutable(true)
        }
    }
}
tasks.build.dependsOn packForXCode
</code></pre>
",https://stackoverflow.com/questions/56267942/how-to-do-unit-testing-in-kotlin-native-multiplatform,"['android', 'kotlin', 'kotlin-multiplatform']",5061,True,11,1
Unit test code inside of CompletableFuture runAsync,"<p>There is a code written by someone who had called completable future to do an activity that is a call and forget i.e. output is not looked after (no <code>get()</code> call). </p>

<pre><code>CompletableFuture.runAsync(() -&gt; {
            List&lt;ActivityListTO&gt; activities = auditCount(requestType, oldLimit, rule, newLimit);
            few mores lines here. 
...
, executor);
</code></pre>

<p>I was unit testing this but unable to execute the code inside of async.<br>
I cannot static mock it as I need to execute the code inside it. I tried passing the thread pool instance in my testcase but it did not go.</p>

<p>Could you provide me some hints on how can I unit test the code inside async?</p>
",https://stackoverflow.com/questions/57585581/unit-test-code-inside-of-completablefuture-runasync,"['java', 'unit-testing', 'asynchronous', 'junit4', 'completable-future']",6145,False,6,0
TDD Swift Unit testing a function with no inputs,"<p>I'm playing with Unit testing in Swift. I can mock and test most of my functions. However I'm struggling with this one (it's for a quiz):</p>

<pre><code>public func getQuestionSetStats() -&gt; (numberOfQs: Int, answered: Int, totalCorrect: Int, totalWrong: Int)? {
    guard questionSet != nil &amp;&amp; questionSet!.count &gt; 0 else {return nil}
    let number = questionSet!.count
    let answered = questionSet!.filter{ $0.answerGiven != nil &amp;&amp; $0.answerGiven ?? 0 &gt;= 0 }.count
    let correct = Array ( zip(questionSet!.map{ Int( $0.question.solution) }, questionSet!.map{ $0.answerGiven }) )
    let correctAnswers = correct.filter{ $0.0 == ( ($0.1 ?? 10) + 1)}.count
    let wrong = number - correctAnswers
    return (numberOfQs: number, answered: answered, totalCorrect: correctAnswers, totalWrong: wrong)
}
</code></pre>

<p>This basically returns the state of my quiz manager for display by some view controller. </p>

<p>Since the vars are very much caught up in the state of the quiz manager I don't know how to unit test this function without setting up a whole state for the function - what is the best approach to do this.</p>
",https://stackoverflow.com/questions/56404333/tdd-swift-unit-testing-a-function-with-no-inputs,['swift'],32,False,0,0
serverless-offline basic example no routes listed or available,"<p>I'm following this basic example (<a href=""https://medium.com/hackernoon/tdd-means-zen-along-with-serverless-means-nirvana-a39a76ee8e63"" rel=""nofollow noreferrer"">https://medium.com/hackernoon/tdd-means-zen-along-with-serverless-means-nirvana-a39a76ee8e63</a>) to setup serverless-offline for unit testing a serverless project.</p>

<p>Unfortunately, I can't get the initial run of serverless-offline to work correctly.  After running ""serverless offline start"", the console output does not display a GET method and a request to localhost:3000 only returns ""Cannot GET /"".</p>

<p>Any ideas what I'm missing here?  Thanks in advance.</p>

<p>My serverless.yml:</p>

<pre><code>
provider:
  name: aws
  runtime: nodejs10.x
functions:
  hello:
    handler: handler.hello
    events:
      - http:
        path: ''
        method: get
plugins:
  - serverless-offline
  - serverless-mocha-plugin
</code></pre>

<p>My package.json:</p>

<pre><code>  ""name"": ""my-api"",
  ""version"": ""1.0.0"",
  ""description"": """",
  ""main"": ""handler.js"",
  ""scripts"": {
    ""test"": ""echo \""Error: no test specified\"" &amp;&amp; exit 1""
  },
  ""keywords"": [],
  ""author"": """",
  ""license"": ""ISC"",
  ""dependencies"": {
    ""mongodb"": ""^3.3.3""
  },
  ""devDependencies"": {
    ""serverless-mocha-plugin"": ""^1.11.0"",
    ""serverless-offline"": ""^5.12.0""
  }
}
</code></pre>

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

<pre><code>
module.exports.hello = async event =&gt; {
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'Go Serverless v1.0! Your function executed successfully!',
        input: event
      },
      null,
      2
    )
  };
};
</code></pre>

<p>Console output:</p>

<pre><code>$ sls offline start
Serverless: Load command interactiveCli
Serverless: Load command config
Serverless: Load command config:credentials
Serverless: Load command config:tabcompletion
Serverless: Load command config:tabcompletion:install
Serverless: Load command config:tabcompletion:uninstall
Serverless: Load command create
Serverless: Load command install
Serverless: Load command package
Serverless: Load command deploy
Serverless: Load command deploy:function
Serverless: Load command deploy:list
Serverless: Load command deploy:list:functions
Serverless: Load command invoke
Serverless: Load command invoke
Serverless: Load command invoke:local
Serverless: Load command info
Serverless: Load command logs
Serverless: Load command metrics
Serverless: Load command print
Serverless: Load command remove
Serverless: Load command rollback
Serverless: Load command rollback:function
Serverless: Load command slstats
Serverless: Load command plugin
Serverless: Load command plugin
Serverless: Load command plugin:install
Serverless: Load command plugin
Serverless: Load command plugin:uninstall
Serverless: Load command plugin
Serverless: Load command plugin:list
Serverless: Load command plugin
Serverless: Load command plugin:search
Serverless: Load command config
Serverless: Load command config:credentials
Serverless: Load command rollback
Serverless: Load command rollback:function
Serverless: Load command offline
Serverless: Load command offline:start
Serverless: Load command create
Serverless: Load command create:test
Serverless: Load command create:function
Serverless: Load command invoke
Serverless: Load command invoke:test
Serverless: Load command login
Serverless: Load command logout
Serverless: Load command generate-event
Serverless: Load command test
Serverless: Load command dashboard
Serverless: Invoke offline:start
Serverless: Starting Offline: dev/us-east-1.
[offline] options: { apiKey: 'XXXXXXXXXXXXXXXXXX',
  cacheInvalidationRegex: /node_modules/,
  corsAllowOrigin: [ '*' ],
  corsAllowCredentials: true,
  corsAllowHeaders: [ 'accept', 'content-type', 'x-api-key', 'authorization' ],
  corsExposedHeaders: [ 'WWW-Authenticate', 'Server-Authorization' ],
`  
  disableCookieValidation: false,
  enforceSecureCookies: false,
  exec: '',
  hideStackTraces: false,
  host: 'localhost',
  httpsProtocol: '',
  location: '.',
  noAuth: false,
  noEnvironment: false,
  noTimeout: false,

  port: 3000,
  prefix: '/',
  preserveTrailingSlash: false,
  printOutput: false,
  providedRuntime: '',
  showDuration: false,
  stage: 'dev',
  region: 'us-east-1',
  resourceRoutes: false,
  skipCacheInvalidation: false,
  useSeparateProcesses: false,
  websocketPort: 3001,
  corsConfig:
   { credentials: true,
     exposedHeaders: [ 'WWW-Authenticate', 'Server-Authorization' ],
     headers: [ 'accept', 'content-type', 'x-api-key', 'authorization' ],
     origin: [ '*' ] } }
[offline] funOptions {
  ""funName"": ""hello"",
  ""funTimeout"": 30000,
  ""handlerName"": ""hello"",
  ""handlerPath"": ""/Users/rocky/Documents/Projects/garmin/sls-troubleshooting/my-api/ha
ndler"",
  ""runtime"": ""nodejs10.x""
}

[offline] hello runtime nodejs10.x
Serverless: Routes for hello:
[offline] Response Content-Type  application/json
Serverless: POST /{apiVersion}/functions/my-api-dev-hello/invocations

Serverless: Offline [HTTP] listening on http://localhost:3000
Serverless: Enter ""rp"" to replay the last request
</code></pre>
",https://stackoverflow.com/questions/58668987/serverless-offline-basic-example-no-routes-listed-or-available,"['aws-lambda', 'serverless-framework', 'serverless-offline']",3970,True,0,1
RxJava android mvp unit test NullPointerException,"<p>I am new to Unit Testing in mvp, I want to make a verrry basic test to the presenter, which is responsible for making login, I just want to assert on</p>

<pre><code>view.onLoginSuccess();
</code></pre>

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

<pre><code>public LoginPresenter(LoginViewContract loginView,
                      LoginModelContract loginModel,
                      CurrentUserLoginModelContract currentUserLoginModel,
                      CompositeDisposable subscriptions) {

    this.subscriptions = subscriptions;

    this.loginView = loginView;

    this.loginModel = loginModel;

    this.currentUserLoginModel = currentUserLoginModel;
}

@Override
public void loginPres(LoginRequest loginRequest) {
    loginModel.loginUser(loginRequest)
        .subscribeOn(Schedulers.computation())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new SingleObserver&lt;LoginResponse&gt;() {

            @Override
            public void onSubscribe(Disposable d) {
                subscriptions.add(d);
            }

            @Override
            public void onSuccess(LoginResponse loginResponse) {
            //  do something with the response
                loginView.loginSuccessMessage(token, true);
            }

            @Override
            public void onError(Throwable e) {
                loginView.loginFailedErrorMessage();
                Timber.e(e, ""Error while trying to login"");
            }
        });
}
</code></pre>

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

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class LoginPresenterTest {

@Mock
LoginViewContract view;
@Mock
LoginModelContract model;
@Mock
CurrentUserLoginModelContract localModel;

LoginPresenter SUT;

@Before
public void setUp() throws Exception {
    compositeDisposable = new CompositeDisposable();
    SUT = new LoginPresenter(view, model, localModel, compositeDisposable);
}

@Test
public void name() {
    LoginResponse singleResponse = new LoginResponse();

    TestScheduler testScheduler = new TestScheduler();

    when(model.loginUser(any()))
            .thenReturn(Single.just(new LoginResponse()));

    SUT.loginPres(any());
}
</code></pre>

<p>It just gives me NullPointerException, I think that Knowing how to test the success will help me test everything else, I have read about the TestScheduler, I tried it but did not help, I think I am doing something wrong, thanks in advance.</p>
",https://stackoverflow.com/questions/57223218/rxjava-android-mvp-unit-test-nullpointerexception,"['java', 'android', 'unit-testing', 'rx-java']",796,True,3,2
How to mock completable of RxKotlin using MockK(Mock Framework),"<p>For unit testing in kotlin android, I have been using the mocking framework MockK. Have used RxKotlin. I have used Completable observable to notify the ViewModel about the status of API. Based on the completable, the status will be updated to success or failure in ViewModel. My question is how to mock the completable observable of RxKotlin using MockK and check the status in the unit test function based on the mocked completable.</p>

<p><strong>Snippet</strong></p>

<pre><code>val testObserver = TestObserver&lt;T&gt;()

every {
 mocked api call
} return completable

testobserver.assertComplete()
</code></pre>

<p><strong>unknown</strong></p>

<p>How to subscribe the testobserver with the completable return mock function call</p>
",https://stackoverflow.com/questions/55262210/how-to-mock-completable-of-rxkotlin-using-mockkmock-framework,"['android', 'unit-testing', 'rx-java2', 'mockk', 'rx-kotlin2']",1132,False,3,0
Write unit Testcase for ViewModel in kotlin,"<p>I am using Junit &amp; Mockito 4 for unit testing of viewModel.</p>

<p>ViewModel class</p>

<pre><code>class MainViewModel(app: Application, private val githubRepo: GithubRepository) :
    BaseViewModel(app) {


    private val _trendingLiveData by lazy { MutableLiveData&lt;Event&lt;DataState&lt;List&lt;TrendingResponse&gt;&gt;&gt;&gt;() }
    val trendingLiveData: LiveData&lt;Event&lt;DataState&lt;List&lt;TrendingResponse&gt;&gt;&gt;&gt; by lazy { _trendingLiveData }

    var loadingState = MutableLiveData&lt;Boolean&gt;()


    fun getTrendingData(language: String?, since: String?) {
        launch {
            loadingState.postValue(true)
            when (val result = githubRepo.getTrendingListAsync(language, since).awaitAndGet()) {
                is Result.Success -&gt; {
                    loadingState.postValue(false)
                    result.body?.let {
                        Event(DataState.Success(it))
                    }.run(_trendingLiveData::postValue)
                }

                is Result.Failure -&gt; {
                    loadingState.postValue(false)
                }
            }
        }
    }

}
</code></pre>

<p>Api EndPoinit</p>

<pre><code>interface GithubRepository {

    fun getTrendingListAsync(
        language: String?,
        since: String?
    ): Deferred&lt;Response&lt;List&lt;TrendingResponse&gt;&gt;&gt;
}
</code></pre>

<p>ViewModel Test class</p>

<pre><code>@RunWith(JUnit4::class)
class MainViewModelTest {

    @Rule
    @JvmField
    val instantTaskExecutorRule = InstantTaskExecutorRule()

    @Mock
    lateinit var repo: GithubRepository

    @Mock
    lateinit var githubApi: GithubApi

    @Mock
    lateinit var application: TrendingApp
    lateinit var viewModel: MainViewModel

    @Mock
    lateinit var dataObserver: Observer&lt;Event&lt;DataState&lt;List&lt;TrendingResponse&gt;&gt;&gt;&gt;

    @Mock
    lateinit var loadingObserver: Observer&lt;Boolean&gt;

    private val threadContext = newSingleThreadContext(""UI thread"")
    private val trendingList : List&lt;TrendingResponse&gt; = listOf()


    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
        Dispatchers.setMain(threadContext)
        viewModel = MainViewModel(application, repo)
    }


    @Test
    fun test_TrendingRepo_whenSuccess() {

        //Assemble
        Mockito.`when`(githubApi.getTrendingListAsync(""java"", ""daily""))
            .thenAnswer{ return@thenAnswer trendingList.toDeferred() }

        //Act
        viewModel.trendingLiveData.observeForever(dataObserver)
        viewModel.loadingState.observeForever(loadingObserver)
        viewModel.getTrendingData(""java"", ""daily"")

        Thread.sleep(1000)

        //Verify
        verify(loadingObserver).onChanged(true)
        //verify(dataObserver).onChanged(trendingList)
        verify(loadingObserver).onChanged(false)


    }


    @After
    fun tearDown() {
        Dispatchers.resetMain()
        threadContext.close()
    }
}
</code></pre>

<p>Problem is that my livedata is wrapped around <code>Event&lt;DataState&lt;List&lt;TrendingResponse&gt;&gt;</code>, due to which I am not able to get what should be dataObserver and how should I verify that dataObserver in the test class. </p>

<p>Event os open class that is to handle event like SingleLiveData</p>

<p>DataState is sealed class that contain SUCCESS &amp; FAILED data class</p>

<p>I have written test case livedata is like <code>LiveData&lt;List&lt;Response&gt;</code> or something like that. </p>
",https://stackoverflow.com/questions/58225940/write-unit-testcase-for-viewmodel-in-kotlin,"['android', 'unit-testing', 'android-livedata', 'android-viewmodel', 'mockito-kotlin']",2132,False,3,1
how to use mockito and junit to test my spring boot rest api?,"<p>I'm new in unit testing and cannot figure out how to  test the RESTFul API with Spring using Mockito and Junit, first of all i have preapared the class in which i created two method with <strong>@Before</strong> and <strong>@Test</strong>, when i turned in debugging mode it tells me that hasSize collection return 0 not 4.</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
public class EmployeControllerTest {
    private MockMvc mockMvc;
    @InjectMocks
    private EmployeController employeController ; 
    @Mock
    private EmployeService employeService ;

    @Before
    public void setUp() throws Exception{
        MockitoAnnotations.initMocks(this);
        mockMvc=MockMvcBuilders.standaloneSetup(employeController).build();
    }
    @Test
    public void testgetAllEmployee() throws Exception{
        List&lt;Employe&gt; employes= Arrays.asList(
                new Employe(""Hamza"", ""Khadhri"", ""hamza1007"", ""123"")
                ,new Employe(""Oussema"", ""smi"", ""oussama"", ""1234"") );
        when(employeService.findAll()).thenReturn(employes);
        mockMvc.perform(get(""/employe/dto""))
        .andExpect(status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath(""$"", hasSize(4)))
         .andExpect(jsonPath(""$[0].nom"", is(""Hamza"")))
         .andExpect(jsonPath(""$[0].prenom"", is(""Khadhri"")))
         .andExpect(jsonPath(""$[0].login"", is(""hamza1007"")))
         .andExpect(jsonPath(""$[0].mp"", is(""123"")))
         .andExpect(jsonPath(""$[1].nom"", is(""Oussema"")))
         .andExpect(jsonPath(""$[1].prenom"", is(""smi"")))
         .andExpect(jsonPath(""$[1].login"", is(""oussama"")))
         .andExpect(jsonPath(""$[1].mp"", is(""1234"")));

        verify(employeService,times(1)).findAll();
        verifyNoMoreInteractions(employeService);
    }
}
</code></pre>

<p>here is the EmployeController :</p>

<pre><code>    @CrossOrigin(origins = ""*"", allowedHeaders = ""*"")
    @RestController
    @RequestMapping(""/employe"")
    public class EmployeController {
        @Autowired
        private EmployeService employeService;

        @Autowired
        private ModelMapper modelMapper;

        @GetMapping(""/dto"")
        public List&lt;EmployeDTO&gt; getEmployeDTOList(){
            try {
                    List&lt;Employe&gt; listemp=employeService.findAllEmployeActive();
                    return listemp.stream()
                        .map(emp -&gt;convertToDto(emp))
                        .collect(Collectors.toList());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

        private EmployeDTO convertToDto(Employe emp) {
            EmployeDTO empDto = modelMapper.map(emp, EmployeDTO.class);

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

<p>when I turn in debugging mode, it tells me that there is <code>NullPointerException</code>.</p>

<p>How to use properly <code>mockito</code> and <code>junit</code> to succeed the test?</p>
",https://stackoverflow.com/questions/54536188/how-to-use-mockito-and-junit-to-test-my-spring-boot-rest-api,"['spring-boot', 'junit', 'mockito', 'hamcrest']",2587,True,0,2
"Unit Testing of Remote API calls, How it works with JSON Objects","<p>In my web api, I have a method that call a service that return a deserialized  JSON object. I can't find a way for unit testing that is working for me.
the following is the code from the controller:</p>

<pre><code>     [RequireHttps]
     [Route(""api/GetItem/{id}"")]
     public class GetItemController : ControllerBase
    {
     private static HttpClient client = new HttpClient();
     private Item item = new Item();

     [RequireHttps]
     [Route(""api/GetItem/{id}"")]
     public Item GetItem(string name, string password)
     {
        string url = ""https://localhost:5001/"";


       string uri = url + ""api/item/"" + name+ ""/"" +  password ""/""  ;
       client.DefaultRequestHeaders.Accept.Add(new 
       MediaTypeWithQualityHeaderValue(""application/json""));
       HttpResponseMessage Res = client.GetAsync(uri).Result;              

            if (Res.IsSuccessStatusCode)
            {

                var MemResponse = Res.Content.ReadAsStringAsync().Result;

                member = JsonConvert.DeserializeObject&lt;Item&gt; 
                (MemResponse);

            }

            return Ok(item);
        }
    }
</code></pre>

<p>The unit test I wrote suppose to check the wrong user name and password, but when running the test it just gray out and never runs </p>

<pre><code>  [TestMethod]
   public void GetItemWithWrongPassword()
   {      
    var username = ""Hellow"";
    var pass = ""There"";
    var controller = new GetItemController();
    var response = controller.GetItem(username, pass);
    var s = response.ToString();
    Assert.AreEqual(s, ""System.Web.Http.Results.NotFoundResult"");
}
</code></pre>

<p>what I'm doing wrong?
Later on I want to test if the connection to the remote API.</p>
",https://stackoverflow.com/questions/54750391/unit-testing-of-remote-api-calls-how-it-works-with-json-objects,"['json', 'unit-testing', 'asp.net-web-api', 'controller', 'nunit']",141,False,0,1
Junit Testing @getmappings with h2 in memory database,"<p>I'm having issues unit testing the DbRequest controller.  I have one unit test working, but I'm unable to achieve a unit test for the DBRequest controller GET mappings which does a database lookup using hibernate. I' have an H2 in memory database created for the junit tests.
I've tried a variety of different setups, and nothing seems to work correctly.</p>

<p>Edited the below, I'm getting a NullPointer,</p>

<pre><code>java.lang.NullPointerException
    at com.lmig.informaticaservice.api.DBcontroltest.saveTest(DBcontroltest.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
</code></pre>

<p>Here is the edited test.</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest

@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class DBcontroltest {



@Autowired
DbRequest dbRequest;


    @Autowired
    ConnectionRequestRepository connectionRequestRepository;

    private MockMvc mockMvc;
    // @Autowired
   //private TestEntityManager entityManager;



     @Test
    public void saveTest() throws Exception {
         ConnectionRequest connectionRequest = new ConnectionRequest((long) 1, ""test"");
         connectionRequestRepository.save(connectionRequest);


         System.out.println(connectionRequestRepository.findAll().toString());

         mockMvc.perform(get(""/api/selectDB/{connectionId}"" ,1))
                 .andExpect(status().isOk());


    }

}


Typical JPA repository 

    package com.test.models;

    import org.springframework.data.jpa.repository.JpaRepository;

    public interface ConnectionRequestRepository extends JpaRepository&lt;ConnectionRequest, Long&gt; {

    }
</code></pre>

<p>Here is my controller.</p>

<pre><code>package com.test.api;

import com.models.ConnectionRequest;
import com.test.models.ConnectionRequestRepository;

import java.util.List;

import javax.validation.Valid;

import lombok.Data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Data
@RestController
@RequestMapping(""/api/"")
public class DbRequest {

    @Autowired
    private ConnectionRequestRepository connectionRequestRepository;
    private ConnectionRequest connectionRequest;

    @GetMapping(""/selectDB"")
    public List&lt;ConnectionRequest&gt; getAllRequests() {
        return connectionRequestRepository.findAll();
    }

    @GetMapping(""/selectDB/{connectionId}"")
    public ResponseEntity&lt;ConnectionRequest&gt; getRequestById(@PathVariable(""connectionId"") Long connectionId) throws Exception {
        ConnectionRequest connectionRequest = connectionRequestRepository.findById(connectionId)
            .orElseThrow(() -&gt; new Exception(""Connection Request "" + connectionId + "" not found""));
        return ResponseEntity.ok().body(connectionRequest);
    }
}
</code></pre>

<p>Here is the model for the database.</p>

<pre><code>package com.testing.models;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@Data
@Entity
@Table(name = ""connrequest"", schema = ""testschema"")
@AllArgsConstructor
@NoArgsConstructor
@EntityListeners(AuditingEntityListener.class)
public class ConnectionRequest {

    @Id
    @Column(name = ""connection_id"", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long connectionId;

    @Column(name = ""requestor"", nullable = false)
    private String requestor;
}
</code></pre>
",https://stackoverflow.com/questions/59033907/junit-testing-getmappings-with-h2-in-memory-database,"['java', 'spring-boot', 'junit']",456,False,0,1
MessagingCenter callback fails to register,"<p>I'm making an app with xamarin.forms and I have an issue with unit testing part. The problem is that when the test case runs isolated it passes, but when I run all the tests it fails.</p>
<pre><code>using EmpresaPersonal.Modelos;
using EmpresaPersonal.ModelosVisuales;
using EmpresaPersonal.Services;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xunit;

namespace EmpresaPersonal.Test
{
    public class PruebasVMEditarContacto
    {
        [Fact]
        public async Task GuardarContactoSeteaCorrectamenteAsync()
        {
            // Preparamos el editor y los eventos
            var store = new MockDataStore();
            var mockNavegacion = ServiciosFalsos.MockIrAtras();
            var editor = new MVEditarContacto(store, mockNavegacion.Object)
            {
            // Initializer setters...
            };

            bool llamado = false;
            MessagingCenter.Subscribe&lt;MVEditarContacto, string&gt;(this, MVEditarContacto.EventoContactoCreado, async (s, idContacto) =&gt; // This line throws a NullReferenceException
            {
                var contacto = await store.GetItemAsync(idContacto);
                // Algunos chequeos van por acá
                Assert.NotNull(contacto);
                Assert.Equal(editor.Nombre.Valor, contacto.Nombre);
                Assert.Equal(editor.Empresa.Valor, contacto.Empresa);
                Assert.Equal(editor.TelefonoPrincipal.Valor, contacto.TelefonoPrincipal);
                Assert.Equal(editor.TelefonoSecundario.Valor, contacto.TelefonoSecundario);
                llamado = true;
            });
            editor.GuardarContacto.Execute(null);
            await editor.EsperarCompletarAsync();
            Assert.True(llamado, &quot;El evento no fue llamado.&quot;);
            mockNavegacion.Verify(m =&gt; m.AtrasAsync());
        }
    }
}
</code></pre>
<p>I don't use anything than MessagingCenter.Send` from the model instantiated in this chunk. I have to say that I have another test for a model that subscribes to this model, to the same event in it's constructor (the model is the subscriber).</p>
<p>Any ideas?</p>
",https://stackoverflow.com/questions/58210179/messagingcenter-callback-fails-to-register,"['c#', 'xamarin', 'xamarin.forms']",219,True,0,1
How to correctly remove NUnit3TestAdapter from csproj project file,"<p>I changed the unit testing of a C# test project from NUnit to xUnit. I already removed the NUnit nuget package. But when I look into the csproj file there still the NUnit3TestAdapter is there:</p>

<pre><code>&lt;Import Project=""..\..\..\..\packages\NUnit3TestAdapter.3.10.0\build\net35\NUnit3TestAdapter.props"" Condition=""Exists('..\..\..\..\packages\NUnit3TestAdapter.3.10.0\build\net35\NUnit3TestAdapter.props')"" /&gt;
...
&lt;Error Condition=""!Exists('..\..\..\..\packages\NUnit3TestAdapter.3.10.0\build\net35\NUnit3TestAdapter.props')"" Text=""$([System.String]::Format('$(ErrorText)', '..\..\..\..\packages\NUnit3TestAdapter.3.10.0\build\net35\NUnit3TestAdapter.props'))"" /&gt;
</code></pre>

<p>I dont see this in the nuget package manager.</p>

<p>So my question: How to remove this correctly? Should I edit the file manually or is there a way to remove it with VS2017?</p>

<p><strong>Edit:</strong> I removed these two lines manually from csproj file. It seems fine.</p>
",https://stackoverflow.com/questions/57605380/how-to-correctly-remove-nunit3testadapter-from-csproj-project-file,"['c#', 'nunit', 'csproj']",208,True,0,1
"How to avoid vtable-lookups in production, and still be able to mock extensively in unit-tests?","<p>In languages such as C# I often let my classes depend on interfaces instead of concrete classes, even when there is only one 'real' implementation. This is to make unit-testing easier (by creating mocks).</p>

<p>When programming in C++ I want maximum performance, and still use TDD and mocking. Is there a way of achieving both? That is, to be able to mock when testing, and still have direct concrete calls in production code?</p>

<p>How can this be achieved in C++?</p>
",https://stackoverflow.com/questions/58851328/how-to-avoid-vtable-lookups-in-production-and-still-be-able-to-mock-extensively,"['c++', 'performance', 'unit-testing', 'mocking', 'vtable']",234,False,0,1
Write a unit test in mocha for the given method using mocks/stubs,"<p>I am pretty new to unit testing in node.js. </p>

<p>I have a function which looks something like this. I need to write a unit test for the function. </p>

<pre class=""lang-js prettyprint-override""><code>async refreshToken(req, res) {
    const token = req.body.token || req.query.token;
    const options = {method: 'POST', url: ''};
    let resp;
    try {
      resp = await request(options);
    } catch (e) {
      console.error(e);
    }
    if (resp) {
      const grant = {
        another_token: {
          token: resp.another_token,
        },
        expires_in: resp.expires_in
      }
      res.end(JSON.stringify(grant));
    } else {
      res.status(400).end(""not authorized"");
    }
  }
</code></pre>

<p>I am planning to use mocha framework with sinon and chai.</p>

<p>I tried a test using mocha, but could not figure out how to assert if the request(options) is called at least once.</p>

<pre class=""lang-js prettyprint-override""><code>describe('refreshToken', () =&gt; {
    it('should take token from body', async () =&gt; {
      const req = {
        body: {
          token: ""123""
        }
      }
      await auth.refreshToken(req, res);
      request.should.have.been.calledOnceWithExactly(options);
    })
</code></pre>

<p>I get:</p>

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

<p>I am having difficulty how to make this work with mock/stub.</p>
",https://stackoverflow.com/questions/57479631/write-a-unit-test-in-mocha-for-the-given-method-using-mocks-stubs,"['node.js', 'request', 'mocha.js', 'sinon']",532,False,0,1
How can I use mock to return None for parse known args?,"<p>Below I have a function that returns the two dates based on command line input. How can I use mock to make it so that I can perform unit testing on the else statement?   </p>

<pre><code># time from of pull
def time_frame():
    """"""
    checks for optional user input for start and end date of data pull
    creates start and end date for query
    :return: start and end date
    """"""
    # get the dates
    args, leftovers = get_the_args()

    if args.start_dt is not None and args.end_dt is not None:

        return args.start_dt, args.end_dt

    else:

        # get today
        the_today_start_date, the_today_end_date = get_dates_from_today()

        return the_today_start_date, the_today_end_date
</code></pre>

<p>I have tried using <code>mock_get_the_args.return_value = mock.Mock(return_value=None), mock.Mock()</code> to make it so that the args output of the <code>get_the_args()</code> function returns None when this section of my unit test runs? What do I need to change my mock.Mock() thats represents the <code>args</code> variable for this to work?</p>

<p>Below is the unit test so far:</p>

<pre><code># the time frame
@mock.patch('src.toolkit.get_dates_from_today')
@mock.patch('src.toolkit.get_the_args')
def test_time_frame(mock_get_the_args, mock_get_dates_from_today):
    # set some dates
    start_date = '2019-01-01'
    end_date = '2019-01-01'
    # mocking
    mock_get_the_args.return_value = mock.Mock(), mock.Mock()
    mock_get_dates_from_today.return_value = mock.Mock(), mock.Mock()

    start_date, end_date = time_frame() 
    mock_get_the_args.assert_called_once()

    mock_get_the_args.return_value = mock.Mock(return_value=None), mock.Mock()
    start_date, end_date = time_frame() 
    mock_get_dates_from_today.assert_called_once()
</code></pre>
",https://stackoverflow.com/questions/55271638/how-can-i-use-mock-to-return-none-for-parse-known-args,"['python-3.x', 'unit-testing', 'mocking', 'argparse', 'python-unittest']",938,True,0,1
Test Switch Case - Unit testing,"<p>I am new to unit testing and I ran into the this case.
I am using JEST and Enzyme - REACT JS</p>

<p>I am familiar calling clicks and onChange events  but not sure how to set up a test for the following:</p>

<pre><code>updateUser = (e) =&gt; {
  var tempUser = this.state.user;

  switch(e.target.id){
     case ""firstName"":
           tempUser.FirstName = e.target.value;
           break;
     case ""lastName"":
           tempUser.LastName = e.target.value;
           break;
     case ""email"":
           tempUser.Email = e.target.value;
           break;
      case ""userName"":
           tempUser.Username = e.target.value;
           break;
      default:
           break;
    }

this.setState({
    user: tempUser,
   })
}
</code></pre>

<p>So I tried to apply the same set up I have been using to test updateUser - not sure if its the correct approach.</p>

<pre><code>describe(' Test', () =&gt; {
let wrapper;

 beforeEach(() =&gt; wrapper = shallow(&lt;Component {...baseProps} /&gt;));

it('UpdateUser method', () =&gt; {
 wrapper.instance().updateUser = jest.fn();
 wrapper.setState({
   user:{
         tempUser :{
            FirstName: """",
            LastName:"""",
            Email:"""",
            Username:"""",
          },
      },
  }),
wrapper.update();
expect(wrapper.instance().updateUser).toBeDefined();
expect(wrapper.state().user).toEqual({}); 
})
</code></pre>

<p>Thanks for the help - hope to learn how to test switch cases and get this test to pass.</p>
",https://stackoverflow.com/questions/54927861/test-switch-case-unit-testing,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",10942,True,0,2
Where is the ufprt located,"<p>I recently started working with unit testing, specially integration test. I am working on a afterAll function that deletes the test that was created during the process. I need the ufprt because it's giving me a 400 status code, I am using Umbraco, I am new to it as well. Here is my afterAll function.
NOTE: there is an specified ufprt there, but it's not the one I am supposed to use. I am working in Visual Studio, using Protractor with Jasmine.</p>

<pre><code>afterAll(function () {
    const HttpClient = require(""protractor-http-client"").HttpClient;
    const http = new HttpClient(browser.params.server);
    var post = http.post(""/login"", ""login=&amp;loginModel.Password=infox2016&amp;loginModel.Username=unittestmember1@infox.de&amp;ufprt=A281647162F7381054DAACAE0536261EB29527977AF7313C526A081FFC2DDB2A0F62993C7FBC9759ED43AC448BAF0611667A521E6BD247C6D23535438FDC94209A9F028E01028B9F58B20205EB39701D81DA06E360441239F0FF57F287B231D4426EED4713957FBEDC2B9C31D8DD88D6B3E89B12B58B1C688BD42B7340CE7F89E7330B48F051A5BCE86C2110BDAE14061BFB02250CADF837B46D7F77D2E7DACA"", {
        ""Content-Type"": ""application/x-www-form-urlencoded""
    });
    browser.wait(post.then(function (response) {
        response = http.delete(""api/CampaignConfiguration/"" + browser.params.id);
        console.log(browser.params.id);
        browser.wait(response.then(function (deleteResponse) {
            expect(deleteResponse.statusCode).toBe(200);
        }));
    }));
});
</code></pre>
",https://stackoverflow.com/questions/58518376/where-is-the-ufprt-located,"['unit-testing', 'protractor', 'integration-testing', 'umbraco']",86,False,-1,1
What is the point of mocking the method of an external library when unit testing?,"<p>What is the point of mocking the method of an external library when unit testing?</p>

<p>Let's say that I have a function that uses XYZ library to get the current user using a given authorization token, and then if it finds the user, it returns a valid AWS policy:</p>

<pre><code>export const getUser = async token =&gt; {
  const user = await XYZ.getUser(token)
  return {
    // valid policy
    context: user,
  }
}
</code></pre>

<p>If an invalid token is given, the <code>getUser</code> should throw an error.</p>

<ul>
<li>What is the point of testing this function if the <code>XYZ.getUser</code> is already well tested? </li>
<li>Why mock the <code>getUser</code> instead of using the real one?</li>
</ul>
",https://stackoverflow.com/questions/56678063/what-is-the-point-of-mocking-the-method-of-an-external-library-when-unit-testing,"['javascript', 'node.js', 'unit-testing', 'testing']",313,False,0,2
Why are my GNURadio unit tests passing when they should fail?,"<p>When setting up unit testing in GNURadio (Version 3.8, running on Python 3.6.8), the <code>assertFloatTuplesAlmostEqual</code> method seems to give wrong results.</p>

<p>I'm working through the GNURadio OutOfTreeModules tutorial, focusing now on unit testing. In the unit test, I provide a vector of expected and actual results. (The code I am testing is known to be working correctly). The test uses the instruction <code>self.assertFloatTuplesAlmostEqual(expected_result, result_data, 6)</code> . The assert statement seems to check only the first item in the vector; if I make the expected value of any other item in the vector different than the actual, the test passes. I cannot find any documentation on the assertFloatTuplesAlmostEqual method. Here is the code for the unit test:</p>

<pre><code>from gnuradio import blocks
import howto1_swig as howto1

class qa_cube_ff(gr_unittest.TestCase):

    def setUp(self):
        self.tb = gr.top_block()



    def test_001_cube_ff(self):
        print(""test 001 STARTING"")
        src_data = (-3, 4, -5.5 )
        print(src_data)
#        expected_result = (-27, 60, 166.375)    // these would be the correct answers
# below, only the first expected result is correct; the other 2 are intentionally wrong
        expected_result = (-27, 60, 100.375)
        src = blocks.vector_source_f(src_data)
        sqr = howto1.cube_ff()
        dst = blocks.vector_sink_f()
        self.tb.connect(src, sqr)
        self.tb.connect(sqr, dst)
        self.tb.run()
        result_data = dst.data()
        print(""EXPECTED"")
        print(expected_result)
        print(""RESULT"")
        print(result_data)
        self.assertFloatTuplesAlmostEqual(expected_result, result_data, 6)

    def tearDown(self):
        self.tb = None


if __name__ == '__main__':
    gr_unittest.run(qa_cube_ff) 
</code></pre>

<p>Here is where I try to run the test. Note that I have put in print statements to show the expected and actual results of running the code. The assetFloatTuplesAmostEqual code tests only the first item in the vector; if the expected and actual values of the first element don't match, the test fails (as it should). Wrong values for any other element pass the test- </p>

<pre><code>odroid@odroid:~/projects/grc_module/gr-howto1/build$ ctest -VV -R cube
UpdateCTestConfiguration  from :/home/odroid/projects/grc_module/gr-howto1/build/DartConfiguration.tcl
UpdateCTestConfiguration  from :/home/odroid/projects/grc_module/gr-howto1/build/DartConfiguration.tcl
Test project /home/odroid/projects/grc_module/gr-howto1/build
Constructing a list of tests
Done constructing a list of tests
Updating test list for fixtures
Added 0 tests to meet fixture requirements
Checking test dependency graph...
Checking test dependency graph end
test 1
    Start 1: qa_cube_ff

1: Test command: /bin/sh ""/home/odroid/projects/grc_module/gr-howto1/build/python/qa_cube_ff_test.sh""
1: Test timeout computed to be: 9.99988e+06
1: .
1: ----------------------------------------------------------------------
1: Ran 1 test in 0.003s
1: 
1: OK
1: test 001 STARTING
1: (-3, 4, -5.5)
1: EXPECTED
1: (-27, 60, 100.375)
1: RESULT
1: (-27.0, 64.0, -166.375)
1/1 Test #1: qa_cube_ff .......................   Passed    1.98 sec

The following tests passed:
    qa_cube_ff

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   1.99 sec
</code></pre>

<p>Here the first element is correct (-3 cubed). The other two are wrong.</p>

<p>Why? 
A related question: Can anyone advise me where to find documentation for the gr_unittest methods??</p>
",https://stackoverflow.com/questions/58666060/why-are-my-gnuradio-unit-tests-passing-when-they-should-fail,"['unit-testing', 'gnuradio']",284,False,1,1
Where is the ufprt located,"<p>I recently started working with unit testing, specially integration test. I am working on a afterAll function that deletes the test that was created during the process. I need the ufprt because it's giving me a 400 status code, I am using Umbraco, I am new to it as well. Here is my afterAll function.
NOTE: there is an specified ufprt there, but it's not the one I am supposed to use. I am working in Visual Studio, using Protractor with Jasmine.</p>

<pre><code>afterAll(function () {
    const HttpClient = require(""protractor-http-client"").HttpClient;
    const http = new HttpClient(browser.params.server);
    var post = http.post(""/login"", ""login=&amp;loginModel.Password=infox2016&amp;loginModel.Username=unittestmember1@infox.de&amp;ufprt=A281647162F7381054DAACAE0536261EB29527977AF7313C526A081FFC2DDB2A0F62993C7FBC9759ED43AC448BAF0611667A521E6BD247C6D23535438FDC94209A9F028E01028B9F58B20205EB39701D81DA06E360441239F0FF57F287B231D4426EED4713957FBEDC2B9C31D8DD88D6B3E89B12B58B1C688BD42B7340CE7F89E7330B48F051A5BCE86C2110BDAE14061BFB02250CADF837B46D7F77D2E7DACA"", {
        ""Content-Type"": ""application/x-www-form-urlencoded""
    });
    browser.wait(post.then(function (response) {
        response = http.delete(""api/CampaignConfiguration/"" + browser.params.id);
        console.log(browser.params.id);
        browser.wait(response.then(function (deleteResponse) {
            expect(deleteResponse.statusCode).toBe(200);
        }));
    }));
});
</code></pre>
",https://stackoverflow.com/questions/58518376/where-is-the-ufprt-located,"['unit-testing', 'protractor', 'integration-testing', 'umbraco']",86,False,-1,1
Practical uses for the option to pass `Supplier` as a message supplier in JUnit 5,"<p>The <a href=""https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/Assertions.html"" rel=""noreferrer""><code>Assertions</code></a> class in JUnit 5 allows for passing an <a href=""https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html"" rel=""noreferrer""><code>Supplier&lt;String&gt;</code></a> as a <code>messageSupplier</code>, an object that provides the text of a message to report when the test fails.</p>

<p>For example, <a href=""https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/Assertions.html#assertEquals(char,char,java.util.function.Supplier)"" rel=""noreferrer""><code>assertEquals</code></a>:</p>

<pre class=""lang-java prettyprint-override""><code>public static void assertEquals​( char expected,
                                 char actual,
                                 Supplier&lt;String&gt; messageSupplier )
</code></pre>

<p>I am wondering what the <strong>practical use of such a supplier</strong> might be, specifically in the context of unit testing. </p>

<p>I can imagine perhaps localizing the strings, though that seems a bit strange to localize when the audience is the members of a development project. </p>

<p>➥ Are there any other practical uses of passing such a message supplier rather than <a href=""https://en.wikipedia.org/wiki/Hard_coding"" rel=""noreferrer"">hard-coding</a> message string?</p>
",https://stackoverflow.com/questions/54777916/practical-uses-for-the-option-to-pass-supplier-as-a-message-supplier-in-junit,"['junit', 'message', 'junit5', 'junit-jupiter', 'supplier']",1854,True,5,2
Method in base class does not exist during unit testing with mocha of Vue component,"<p>When I have a component in Vue that extends from a base class, it works in run time in the browser, as expected. But when unit testing with mocha, the method on the base class disappears. In the simple example below this results in the error <code>TypeError: this.methodInBaseClass is not a function</code>. But in runtime it works, then the message <code>Some other data</code> is shown, as I would expect.</p>

<p>What is going wrong? And more importantly, how to fix it?</p>

<p>Consider this simple Vue component:</p>

<pre><code>&lt;template&gt;
    &lt;div&gt;{{ myData }}&lt;/div&gt;
&lt;/template&gt;

&lt;script lang=""ts""&gt;
import { Component, Prop, Vue } from 'vue-property-decorator';
import BaseClass from '@/components/BaseClass.vue';

@Component
export default class HelloWorld extends BaseClass {
    @Prop() private msg!: string;

    private created(): void {
        this.methodInBaseClass();
    }
}
&lt;/script&gt;
</code></pre>

<p>and the base class</p>

<pre><code>&lt;script lang=""ts""&gt;
import { Component, Prop, Vue } from 'vue-property-decorator';
export default class BaseClass extends Vue {
    protected myData: string = 'Some data';

    protected methodInBaseClass(): void {
        this.myData = 'Some other data';
    }
}
&lt;/script&gt;
</code></pre>

<p>and the unit test</p>

<pre><code>import { expect } from 'chai';
import { shallowMount } from '@vue/test-utils';
import HelloWorld from '@/components/HelloWorld.vue';

describe('HelloWorld.vue', () =&gt; {
    it('Data is mutated', () =&gt; {
        const wrapper = shallowMount(HelloWorld);
        expect(wrapper.html()).to.include('Some other data');
    });
});
</code></pre>
",https://stackoverflow.com/questions/55429318/method-in-base-class-does-not-exist-during-unit-testing-with-mocha-of-vue-compon,"['typescript', 'unit-testing', 'inheritance', 'vue.js', 'mocha.js']",638,True,2,2
Enum.Parse throws InvalidCastException,"<p>I have this line of C# code:</p>

<pre><code>var __allFlags = Enum.Parse(enumType, allFlags);
</code></pre>

<p>It is throwing an <code>InvalidCastException</code> and I can't figure out why - if I set a breakpoint and run <code>Enum.Parse(enumType, allFlags)</code> in the watch window, I get the expected result and not an error.</p>

<p><code>enumType</code> is set to <code>typeof(PixelColor)</code> where <code>PixelColor</code> is an enum I am using for unit testing purposes, and <code>allFlags</code> is set to the string <code>""Red""</code> which is one of the  possible values of <code>PixelColor</code>.</p>

<p>edit: here is my unit test:</p>

<pre><code>[TestMethod]
public void IsFlagSetStringTest()
{
    Assert.IsTrue(EnumHelper.IsFlagSet(typeof(PixelColor), ""Red"", ""Red""));
    Assert.IsFalse(EnumHelper.IsFlagSet(typeof(PixelColor), ""Red"", ""Green""));
    Assert.IsTrue(EnumHelper.IsFlagSet(typeof(PixelColor), ""White"", ""Red""));
    Assert.IsTrue(EnumHelper.IsFlagSet(typeof(PixelColor), ""White"", ""Red, Green""));
    Assert.IsFalse(EnumHelper.IsFlagSet(typeof(PixelColor), ""Red"", ""Red, Green""));
}
</code></pre>

<p>and here is the method being tested:</p>

<pre><code>/// &lt;summary&gt;
/// Determines whether a single flag value is specified on an enumeration.
/// &lt;/summary&gt;
/// &lt;param name=""enumType""&gt;The enumeration &lt;see cref=""Type""/&gt;.&lt;/param&gt;
/// &lt;param name=""allFlags""&gt;The string value containing all flags.&lt;/param&gt;
/// &lt;param name=""singleFlag""&gt;The single string value to check.&lt;/param&gt;
/// &lt;returns&gt;A &lt;see cref=""System.Boolean""/&gt; indicating that a single flag value is specified for an enumeration.&lt;/returns&gt;
public static bool IsFlagSet(Type enumType, string allFlags, string singleFlag)
{
    // retrieve the flags enumeration value
    var __allFlags = Enum.Parse(enumType, allFlags);
    // retrieve the single flag value
    var __singleFlag = Enum.Parse(enumType, singleFlag);

    // perform bit-wise comparison to see if the single flag is specified
    return (((int)__allFlags &amp; (int)__singleFlag) == (int)__singleFlag);
}
</code></pre>

<p>and just in case, here is the enum used for testing:</p>

<pre><code>/// &lt;summary&gt;
/// A simple flags enum to use for testing.
/// &lt;/summary&gt;
[Flags]
private enum PixelColor
{
    Black = 0,
    Red = 1,
    Green = 2,
    Blue = 4,
    White = Red | Green | Blue
}
</code></pre>
",https://stackoverflow.com/questions/57117690/enum-parse-throws-invalidcastexception,"['c#', 'enums']",286,True,5,1
Can&#39;t get where query to do eager loading of one-to-many association,"<p>I am using Grails v3.3.9.</p>

<p>I cannot get queries to eagerly load one-to-many association.  Tried all sorts of ways.</p>

<p>This is posted relative to trying to use this in unit testing (fails on app at runtime as well).</p>

<p>Scenario: I have two domain classes, one called 'OrgRoleInstance' which has <code>Collection&lt;Site&gt;</code> sites, and <code>static hasMany =[sites:Site]</code>, and the other called 'Site' which has a <code>static belongsTo = [org:OrgRoleInstance]</code>.</p>

<p>This is birdirectional one-to-many from orgs to sites.</p>

<p>I create a new unit test using the new DomainUnitTest trait.  In the test setup I create three orgs and add one site each, then I add one last site to the 3rd org (org ""C"").  Setup works fine and all instances are persisted.</p>

<p>In the where query test, I look for an Org that has 2 sites (which is org ""C"").</p>

<p>When I run the test in debug, the where query returns an array of size 1 containing org ""C"", so the test in the where clause can see that sites collection is not null - so far so good.</p>

<p>I also do a direct Site.get(4) to get the last site.  I do an assert check to check that the sites.org ref is same instance returned from the where query.  This is true and passes.</p>

<p>However when you look at the orgs[0] entry the sites collection is null.  That simple println fails with accessing null sites property returned from the query.</p>

<pre><code>class OrgRoleInstanceSpec extends Specification implements DomainUnitTest&lt;OrgRoleInstance&gt; {


    def setup() {
        OrgRoleInstance

        List&lt;OrgRoleInstance&gt; orgs = []
        [""A"",""B"",""C""].each {
            OrgRoleInstance org = new OrgRoleInstance(name:it, role:OrgRoleInstance.OrgRoleType.Customer)
            org.addToSites(new Site( name: ""$it's Head Office"", status:""open"", org:org))
            orgs &lt;&lt; org

        }
        orgs[2].addToSites (new Site( name: ""${orgs[2].name}'s Branch Office"", status:""open"", org:orgs[2]))
        OrgRoleInstance.saveAll(orgs)
        assert OrgRoleInstance.count() == 3
        println ""# of sites : "" + Site.count()
        assert Site.count() == 4
        assert Site.get(2).org.id == orgs[1].id
    }


    void ""where query and individual get "" () {
        given :

        def orgs = OrgRoleInstance.where {
            sites.size() == 2
        }.list(fetch:[sites:""eager""])

             def org = OrgRoleInstance.get(2)
            List orgSites = org.sites

            def branch = Site.get(4)

            assert branch.org.is (orgs[0]) //assert is true

            println orgs[0].sites[1].name  //orgs[0].sites is null !


        expect:
        orgs.size() == 1

    }

}
</code></pre>

<p>I have tried this withCriteria, with basic <code>findAll(fetch:[sites:""eager"")</code> etc.</p>

<p>However I try this I cannot get query to return eager populated collection of sites.</p>

<p>I want to do that in the queries rather than by mapping clause in OrgeRoleInstance domain class </p>

<h2>Update/observations</h2>

<p>I enabled SQL logging and started the grails console.  I then typed the following script (using my bootstrap data).</p>

<p>Manually typed console script </p>

<pre><code>import com.softwood.domain.*

def orgs = OrgRoleInstance.where {
 id == 4
 sites{}
 }.list() /* (fetch:[sites:""eager""]) */

println orgs[0].sites
</code></pre>

<p>which when run outputs the following - which basically does seem to run eager selection - and I get the orgs.sites result with populated entries using an inner join:</p>

<pre><code>groovy&gt; import com.softwood.domain.* 
groovy&gt; def orgs = OrgRoleInstance.where { 
groovy&gt;  id == 4 
groovy&gt;  sites{} 
groovy&gt;  }.list() /* (fetch:[sites:""eager""]) */ 
groovy&gt; println orgs[0].sites 

2019-01-23 14:02:00.923 DEBUG --- [      Thread-18] org.hibernate.SQL                        : 
    select
        this_.id as id1_16_1_,
        this_.version as version2_16_1_,
        this_.role as role3_16_1_,
        this_.name as name4_16_1_,
        sites_alia1_.id as id1_21_0_,
        sites_alia1_.version as version2_21_0_,
        sites_alia1_.org_id as org_id3_21_0_,
        sites_alia1_.name as name4_21_0_,
        sites_alia1_.status as status5_21_0_ 
    from
        org_role_instance this_ 
    inner join
        site sites_alia1_ 
            on this_.id=sites_alia1_.org_id 
    where
        this_.id=?
2019-01-23 14:02:00.923 TRACE --- [      Thread-18] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [4]
2019-01-23 14:02:00.923 DEBUG --- [      Thread-18] org.hibernate.SQL                        : 
    select
        sites0_.org_id as org_id3_21_0_,
        sites0_.id as id1_21_0_,
        sites0_.id as id1_21_1_,
        sites0_.version as version2_21_1_,
        sites0_.org_id as org_id3_21_1_,
        sites0_.name as name4_21_1_,
        sites0_.status as status5_21_1_ 
    from
        site sites0_ 
    where
        sites0_.org_id=?
2019-01-23 14:02:00.923 TRACE --- [      Thread-18] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [4]
[Site:(name : 1 Barkley Square) belonging to org: com.softwood.domain.OrgRoleInstance : 4, Site:(name : 10 South Close) belonging to org: com.softwood.domain.OrgRoleInstance : 4]
</code></pre>

<p>So why doesn't this work in unit testing?</p>

<h2>Another update</h2>

<p>I went back to grails console and managed to get this criteria query to work. Point 1 - you have to have imported <code>org.hibernate.FetchMode</code>, then the fetchMode function at root level in withCriteria closure will work now.  Lastly just do empty closure on the collection to force the eager query.</p>

<pre><code>import com.softwood.domain.*
import org.hibernate.FetchMode

def orgs = OrgRoleInstance.withCriteria {
            fetchMode (""sites"", FetchMode.SELECT)


            sites{}
        }

println orgs[0].sites
</code></pre>

<p>However this does not work in a unit test.  The same query in unit test like this </p>

<pre><code>void ""criteria query "" () {
    given:

    OrgRoleInstance org

    org = OrgRoleInstance.withCriteria (uniqueResult: true) {
        fetchMode (""sites"", FetchMode.SELECT)

        sites{}
    }

    expect:
    org.id == 3
    org.sites.size() == 2

}
</code></pre>

<p>fails with this error </p>

<pre><code>groovy.lang.MissingMethodException: No signature of method: grails.gorm.CriteriaBuilder.fetchMode() is applicable for argument types: (java.lang.String, org.hibernate.FetchMode) values: [sites, SELECT]
</code></pre>

<p>I suspect therefore that unit testing criteriaQueries or where queries using the new grails <code>DomainUnitTest&lt;T&gt;</code> trait doesn't support join/eager queries etc.</p>

<p>It maybe that you're forced to integration tests with real DB to test queries across tables. If anyone can state categorically state that the new unit testing traits don't work for join/eager queries that might help me.</p>
",https://stackoverflow.com/questions/54325664/cant-get-where-query-to-do-eager-loading-of-one-to-many-association,"['unit-testing', 'grails', 'eager-loading']",392,False,1,1
Mock a method from another class called from a mocked method,"<p>We are creating unit tests for an application and ran into a problem creating certain tests.</p>

<p>We are unit testing the following Handle() method of the class ActivateCommandHandler:</p>

<pre><code>    public class ActivateCommand : IRequest&lt;HttpResponseMessage&gt;
    {
        public string Controller { get; set; }

        public ActivateCommand(string controllername)
        {
            this.Controller = controllername;
        }
    }

    public class ActivateCommandHandler : CommandHandler&lt;ActivateCommand, HttpResponseMessage&gt;
    {
        protected readonly ICommandsGateway _commandsGateway;
        protected readonly EndpointSettings _endpoints;
        protected readonly IUserProfile _userprofile;

        public ActivateCommandHandler(IMediator mediator, ICommandsGateway commandsGateway, IOptions&lt;EndpointSettings&gt; endpoints, IValidationContext validationContext, IUserProfile currentUser) : base(mediator, validationContext, currentUser)
        {
            _commandsGateway = commandsGateway;
            _endpoints = endpoints.Value;
            _userprofile = currentUser;
        }


        public override async Task&lt;HttpResponseMessage&gt; Handle(ActivateCommand command, CancellationToken cancellationToken)
        {
            if (_endpoints.EndpointExists(command.Controller))
            {
                // Check whether the second server controller is deactivated
                string peercontroller = _endpoints.GetPeerController(command.Controller);

                if (!string.IsNullOrEmpty(peercontroller))
                {
                    BaseRedundancySwitchStatus controllerStatus = await _commandsGateway.GetRedundancySwitchStatus(_endpoints.GetEndpointAddress(peercontroller));

                    if ((controllerStatus.CurrentState == ""Activated"") || (controllerStatus.CurrentState == ""ActivatedWithWarning"") || (controllerStatus.CurrentState == ""Activating""))
                    {
                        var resp = new HttpResponseMessage(HttpStatusCode.Conflict)
                        {
                            Content = new StringContent($""{peercontroller},{controllerStatus.CurrentState}"")
                        };

                        return resp;
                    }
                }

                var result = await _commandsGateway.PostActivateCommand(_endpoints.GetEndpointAddress(command.Controller));

                return result;
            }
            else
            {
                throw new InvalidControllerNameException($""ERROR: The controller {command.Controller} does not exist as an endpoint on this Control Center!"");
            }
        }
    }
</code></pre>

<p>For this the following were mocked: _endpoints, command and _commandsGateway (interface). This works great for unit testing the parameter validation. But we now want to test the behaviour when the peercontroller status is set to a specific value.</p>

<p>To do this we are trying to mock out the function _commandsGateway.GetRedundancySwitchStatus(). The following is the actual test implementation. We mock the _commandsGateway.GetRedundancySwitchStatus() function to return the expected BaseRedundancySwitchStatus with CurrentState set to ""Activated"". After that we call the handler of the actual function to be tested and check whether we get the expected error.</p>

<pre><code>[Fact]
        public async void ShouldHaveErrors_PeerControllerStateActivated()
        {
            var command = new ActivateCommand(""Server Controller Slave1"");

            BaseRedundancySwitchStatus result = new BaseRedundancySwitchStatus()
            {
                CurrentState = ""Activated""
            };

            _commandsGateway
                .Setup(s =&gt; s.GetRedundancySwitchStatus(""Server Controller Slave1""))
                .ReturnsAsync(result);

            HttpResponseMessage res = await _handler.Handle(command, CancellationToken.None);

            Assert.True(res.StatusCode == System.Net.HttpStatusCode.Conflict);
        }
</code></pre>

<p>Debugging the code, when I step through the code in the Handle() method where _commandsGateway.GetRedundancySwitchStatus is called, I can see that _endpoints.GetEndpointAddress(command.Controller) (which is the parameter) is called and the correct value is returned. After this the debugger steps to the next line without any indication of having executed the mock GetRedundancySwitchStatus() function. Inspecting the controllerStatus variable the value is null. I would expect the value to be the BaseRedundancySwitchStatus object which is supposed to be returned by the mocked GetRedundancySwitchStatus() function.</p>

<p>Where are we going wrong?</p>
",https://stackoverflow.com/questions/58913416/mock-a-method-from-another-class-called-from-a-mocked-method,"['c#', 'unit-testing', '.net-core', 'moq']",74,False,0,0
How can I spy on TouchableNativeFeedback onPress in React Native with @testing-library/react-native?,"<p>Help me please...</p>

<p>I have a React Native custom Button component that receives an onPress prop and passes that onPress to a TouchableNativeFeedback. I make a unit testing with @testing-library/react-native. I try to spy on onPress, to check if it is triggered when the TouchableNativeFeedback is touched. Somehow the spy function is not called when I simulate press event on the Button. Is there any mistake in my implementation?</p>

<p>FI: This behavior only occurs in TouchableNativeFeedback, but working perfectly with Button</p>

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

<p>Button.js
<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 Button = ({onPress, label}) =&gt; (
  &lt;TouchableNativeFeedback onPress={onPress} testID=""button""&gt;
    &lt;View style={someStyling}&gt;
      &lt;Text&gt;{label}&lt;/Text&gt;
    &lt;/View&gt;
  &lt;/TouchableNativeFeedback&gt;
)

export default Button</code></pre>
</div>
</div>
</p>

<p>Button.test.js
<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(""Fire onPress props when button pressed"", () =&gt; {
    const mockFn = jest.fn();

    const { getByTestId } = render(&lt;Button onPress={mockFn} /&gt;);
    const button = getByTestId(""button"");
    
    fireEvent.press(button);
    
    expect(mockFn).toHaveBeenCalled();
  });</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/58521876/how-can-i-spy-on-touchablenativefeedback-onpress-in-react-native-with-testing-l,"['unit-testing', 'react-native']",934,False,5,2
"Jasmine unit testing, how do I trigger the click event of ngx-modal-dialog","<p>I am working on an angular application and i am Unit testing the application using Jasmine.</p>

<p>The application uses <code>ngx-modal-dialog</code>(<a href=""https://www.npmjs.com/package/ngx-modal-dialog"" rel=""nofollow noreferrer"">enter link description here</a>) plugin for Pop-up Dialog Box such as a a confirmation box as a dynamic component.</p>

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

<p>What i want is to trigger the click event for the confirm or cancel, whatever the user chooses.</p>

<p>The code for the Pop-up Dialog box is as below:</p>

<pre><code>export class SomeComponent {

constructor(private modalService: ModalDialogService) {}
cancleEditConfirmDialog() {
   this.modalService.openDialog(this.viewRef, {
   title: 'Discard Changes ',
   childComponent: SimpleModalComponent,
   data: {
     text: 'Changes will not be saved. Do you want to proceed?'
   },
   settings: {
     closeButtonClass: 'close theme-icon-close'
   },
   actionButtons: [
     {
       text: 'Discard',
       buttonClass: 'btn btn-success',
       onAction: () =&gt; new Promise((resolve: any) =&gt; {
         // invoke delete
         // do something such as discard changes
         resolve()
       })
     },
     {
       text: 'Cancel',
       buttonClass: 'btn btn-danger',
       onAction: () =&gt; new Promise((resolve: any) =&gt; {
         // cancel and close popup
         setTimeout(() =&gt; {
           resolve();
         }, 20);
       })
     }
   ]
 });
}
}
</code></pre>

<blockquote>
  <p>how do i trigger the <code>onAction: =&gt; ()</code> in the click event for discard button
  and for cancel button.</p>
</blockquote>

<p><a href=""https://i.stack.imgur.com/e46xC.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/e46xC.png"" alt=""enter image description here""></a>
<a href=""https://i.stack.imgur.com/UJQSS.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/UJQSS.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/54939326/jasmine-unit-testing-how-do-i-trigger-the-click-event-of-ngx-modal-dialog,"['javascript', 'angular', 'unit-testing', 'jasmine', 'jasmine-jquery']",7373,True,2,1
avoiding global variables in routes for labstack/echo,"<p>I am using the <a href=""https://echo.labstack.com/"" rel=""nofollow noreferrer"">labstack/echo</a> webserver and <a href=""https://github.com/appleboy/gofight"" rel=""nofollow noreferrer"">gofight</a> for unit testing. In learning go would like to know if there is a go idiom for accessing state outside of the (embedded) echo structure. For example:</p>

<pre><code>type WebPlusDB struct {
    web *echo.Echo
    db  *databaseInterface
}

func NewEngine() *echo.Echo {
    e := echo.New()
    e.GET(""/hello"", route_hello)
    return e    
}

func NewWebPlusDb() {
    e := NewEngine()
    db := database.New()   
    return WebPlusDB{e,db}
}

// for use in unit tests
func NewFakeEngine() *WebPlusDB {
    e := NewEngine()
    db := fakeDatabase.New()   
    return WebPlusDB{e,db}
}    

func route_hello(c echo.Context) error {
    log.Printf(""Hello world\n"")

    // how do I access WebPlusDB.db from here?

    return c.String(http.StatusOK, ""hello world"")
}
</code></pre>

<p>Then in the test code I use:</p>

<pre><code>import (
    ""github.com/labstack/echo""
    ""github.com/appleboy/gofight""
    ""github.com/stretchr/testify/assert""
    ""testing""
)

func TestHelloWorld(t *testing.T) {
    r := gofight.New()

    r.GET(""/hello"").
          Run(NewFakeEngine(), func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
        assert.Equal(t, http.StatusOK, r.Code)
        assert.Equal(t, ""hello world"", r.Body.String())
        // test database access
    })

}
</code></pre>

<p>The <em>easiest</em> solution is to have to use a global variable instead of embedding echo in ""WebPlusDB"" and adding the state there. I would like better encapsulation. I think I should be using something like the WebPlusDB structure not an echo.Echo plus global state. This perhaps doesn't matter so much for unit testing but in the greater scheme of doing things right in go (in this case avoiding globals) I would like to know.</p>

<p>Is there a solution or is this a weakness in the design of echo?
It has extension points for middleware but a database backend is not really <a href=""https://echo.labstack.com/middleware"" rel=""nofollow noreferrer"">middleware as defined here</a>. </p>

<p>Note: I am using a database here to illustrate the common case but It could be anything (I am actually using <a href=""https://godoc.org/github.com/streadway/amqp"" rel=""nofollow noreferrer"">amqp</a>)</p>

<p>It looks like you can extend the <a href=""https://echo.labstack.com/guide/context"" rel=""nofollow noreferrer"">context</a> interface but where is it created? This looks like it uses a kind of <em>downcast</em>:</p>

<pre><code>e.GET(""/"", func(c echo.Context) error {
    cc := c.(*CustomContext)
}
</code></pre>

<p>I think (perhaps incorrectly) that this is only allowed on interface and echo.Context.Echo() returns a type not an interface.</p>
",https://stackoverflow.com/questions/56583560/avoiding-global-variables-in-routes-for-labstack-echo,"['go', 'go-echo']",1342,True,0,1
Can&#39;t create a simple SQL Test,"<p>I'm trying to get just basic unit testing on an SQL database through a Visual Studio project.</p>

<p>The first thing I tried was just creating a simple .Net Core Unit Testing library. </p>

<p>Then I added an SQL Test, and it couldn't link to the SqlDatabaseTestClass`.  Looking around, this is a fairly ubiquitous issue, but I found an obscure comment at the bottom of <a href=""https://developercommunity.visualstudio.com/content/problem/29842/database-unit-test-project-does-not-build-in-visua.html"" rel=""nofollow noreferrer"">https://developercommunity.visualstudio.com/content/problem/29842/database-unit-test-project-does-not-build-in-visua.html</a> that said that it's probably a linking issue.  </p>

<p>So I created a .Net Framework Unit Test project.  Now that has no option to add an SQL Test.  </p>

<p>So I found an article that says that I should try creating an SQLDatabase <a href=""https://www.codeguru.com/csharp/.net/net_data/create-sql-server-database-unit-tests-using-visual-studio.html"" rel=""nofollow noreferrer"">https://www.codeguru.com/csharp/.net/net_data/create-sql-server-database-unit-tests-using-visual-studio.html</a> </p>

<p>But then I got an error that <code>The server version or database compatibility level is not supported.</code> <a href=""https://stackoverflow.com/questions/43397277/import-database-in-vs-2015-sql-server-database-project"">Import Database in VS 2015 SQL Server Database Project</a>  </p>

<p>The solution to that was to go to the SQL Server Object Explorer and right click on the DB and create an SQL project by right clicking on the Database.  And that worked!  Finally I have a project with database tables.</p>

<p>But now when I right click on a stored procedure, I don't get the option to create a unit test.</p>
",https://stackoverflow.com/questions/54353892/cant-create-a-simple-sql-test,"['sql', 'unit-testing', 'visual-studio-2017']",314,True,0,1
npm failed with error code: 1 in azure devops testing pipeline,"<p><strong>reference:</strong></p>

<p><a href=""https://medium.com/@flu.lund/automated-angular-unit-testing-on-visual-studio-team-services-22c03497265c"" rel=""nofollow noreferrer"">https://medium.com/@flu.lund/automated-angular-unit-testing-on-visual-studio-team-services-22c03497265c</a></p>

<p>I have refer above blog link and followed step to Automated Angular Unit Testing and publish test Result.</p>

<p>as per blog guideline i have followed below step.</p>

<p><strong>step 1</strong></p>

<p>Installed below packages.</p>

<ol>
<li>npm install phantomjs-prebuilt --save-dev</li>
<li>npm install karma-phantomjs-launcher --save-dev</li>
<li>npm install karma-junit-reporter --save-dev</li>
</ol>

<p><strong>step 2</strong></p>

<p>Then i have added some configuration in karma.conf.js</p>

<ol>
<li>require('karma-coverage-istanbul-reporter'), // &lt;- Add plugin</li>
<li>require('karma-junit-reporter'), // &lt;- Add plugin</li>
<li>browsers: ['Chrome', 'PhantomJS'], // &lt;- Add browser</li>
</ol>

<p><strong>step 3</strong></p>

<p>Then i added script in package.json</p>

<pre><code>""scripts"": {
    ...
    ""test-single-headless"": ""ng test --single-run=true --browsers=PhantomJS --reporters=progress,junit"",
    ...
  },
</code></pre>

<p><strong>step 4</strong></p>

<p>I added below three line in polyfills.ts file</p>

<pre><code>import 'core-js/es6/object';
import 'core-js/es6/string';
import 'core-js/es6/array';
</code></pre>

<p><strong>step 5</strong></p>

<p>Added pipeline task you can see in below screenshot.</p>

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

<p><strong>step 6</strong></p>

<p>after setup all configure all thing as par blog guideline finally i run build.</p>

<p><strong>getting issue is</strong></p>

<p>Then i go to the result log it work form first task to build task result getting success.</p>

<p>when result's come to the "" Run test "" task.</p>

<p>It will show one Error in ""Run test task log "". which i have attached below screenshot.</p>

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

<p>Please check my step and help me in this issue.
i'm facing this issue since last few days.</p>
",https://stackoverflow.com/questions/57690632/npm-failed-with-error-code-1-in-azure-devops-testing-pipeline,"['unit-testing', 'azure-devops']",12896,True,0,1
Failed to convert value of type [java.lang.String] to required type [boolean],"<p>In a nutshell, Spring auto wiring failed on one field of my Java class.</p>

<p>I have a class which has a field set by Spring auto wiring. This field is of boolean type (not Boolean!). However, when unit testing it, I got an error saying,</p>

<pre><code>Caused by: org.springframework.beans.TypeMismatchException: Failed to convert value of type [java.lang.String] to required type [boolean]; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [${enable.pipe}] at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:77)
</code></pre>

<p>The code is here,</p>

<pre><code>@Value(""${enable.pipe}"")
private boolean isPipeEnabled;
</code></pre>

<p>This class runs well when loaded in a container, but failed and reports the error when running in a unit test. I've tried but failed to find a way to dump the value wired into.</p>
",https://stackoverflow.com/questions/54352255/failed-to-convert-value-of-type-java-lang-string-to-required-type-boolean,"['java', 'spring']",3594,False,2,0
Getting following error in karma jasmine unit test case. Expected undefined to be truthy,"<p>Am new to angular unit testing i had written spec file for a component and
Getting following error in karma jasmine unit test case. <strong>Expected undefined to be truthy</strong>. please find the error snapshoot</p>

<p><strong>Ts file:</strong> </p>

<pre><code>import {Component, Inject, OnInit} from ""@angular/core"";
import {MAT_DIALOG_DATA, MatDialogRef} from ""@angular/material"";
import {DataService} from ""../../../services/data.service"";

@Component({
  selector: 'admin-dialog',
  templateUrl: './admin-dialog.component.html',
  styleUrls: ['./admin-dialog.component.scss']
})

export class AdminDialogComponent implements OnInit {
  public accessHasSelected : any ='';
  public errorObj : any = {};
  public checkBoxSelected : boolean;
  public adminObj: any = {
    active:true,
    firstName:"""",
    lastName:"""",
   // emailId:"""",
    access:[]
  };

  /***
   *
   * @param dialogRef
   * @param data
   * @param fromGroup
   * @param dataService
   */
  constructor(
    public dialogRef: MatDialogRef&lt;AdminDialogComponent&gt;,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private dataService: DataService) {

    if (this.data.isNew){
      this.newAdmin();
    }
    else {
      this.editAdmin(this.data.adminObj);
    }


  }

  /*
  * This method will get called while loading new admin modal.
  * */
  newAdmin() {
    this.dataService.getAllAdminAccess().subscribe(
      response =&gt; {
        //component related success actions
        this.adminObj.access = response.access;
      },
      error =&gt; {
        //component related error actions
      });
  }
  /***
   * This method will get called while loading edit existing admin modal.
   * @param response
   */
  editAdmin(response){
    console.log(response);
    this.dataService.getAdminDetails(response.emailId).subscribe(
      response =&gt; {
        //component related success actions
        this.adminObj = response;
      },
      error =&gt; {
        //component related errorcurrent-workspace actions
      });
  }
  /**
   * This method will run will save is clicked.
   * */
  saveAdmin(){
    this.checkBoxSelected = true;
    this.accessHasSelected = this.adminObj.access.filter(t=&gt;{
      if(this.checkBoxSelected){
        if(t.selected){this.checkBoxSelected = false;}
        else if(t.access !== null){
          t.access.filter(x=&gt;{
            if(x.selected) {this.checkBoxSelected = false;}
          })
        }
      }
    });
    if(!this.checkBoxSelected) {
      this.dataService.saveAdmin(this.adminObj, this.data.isNew).subscribe(
        response =&gt; {
          //component related success actions
          this.dialogRef.addPanelClass('close-modal');
          setTimeout(() =&gt; {
            this.dialogRef.close({
              data: response
            });
          }, 500);
        },
        error =&gt; {
          this.errorObj = {};
          //component related error actions
          for (var v in error.error.errors) {
            this.errorObj[error.error.errors[v].field] = error.error.errors[v].messageId;
          }
        });
    }else{
        this.errorObj.access = ""requiredAccessError"";
      }
  }

  /**
   *
   */
  ngOnInit() {

  }

  onModalCancel(): void {
    this.dialogRef.addPanelClass('close-modal');
    setTimeout(()=&gt;{
      this.dialogRef.close();
    },500);
  }
}
</code></pre>

<p><strong>Spec file</strong></p>

<pre><code>import { AdminDialogComponent } from ""./admin-dialog.component"";
import { TestBed, ComponentFixture,async,inject  } from '@angular/core/testing';
import { FormsModule } from ""@angular/forms"";
import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing';
import {TranslateModule,TranslateService} from ""@ngx-translate/core"";
import {NO_ERRORS_SCHEMA} from ""@angular/core"";
import {MAT_DIALOG_DATA, MatDialog, MatDialogModule, MatDialogRef} from '@angular/material/dialog';
import { OverlayContainer } from '@angular/cdk/overlay';
import {HttpClientModule} from ""@angular/common/http"";
import {RouterTestingModule} from ""@angular/router/testing"";
import {DataService} from ""../../../services/data.service"";

describe('Component: admin-dialog', () =&gt; {

  let component: AdminDialogComponent;
  let fixture: ComponentFixture&lt;AdminDialogComponent&gt;;
  let translate: TranslateService;
  let dialog: MatDialog;
  let overlayContainer: OverlayContainer;
  let dataService: DataService;
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [FormsModule, MatDialogModule, HttpClientModule,RouterTestingModule,TranslateModule.forRoot()],
      declarations: [AdminDialogComponent],
      providers: [TranslateService,
        { provide: MatDialogRef, useValue: {} },
        { provide: MAT_DIALOG_DATA, useValue: []},
        {provide: dataService, useValue: []}],
      schemas: [NO_ERRORS_SCHEMA]
  });
    TestBed.overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [AdminDialogComponent]
      }
    });

    TestBed.compileComponents();

    // create component and test fixture
    fixture = TestBed.createComponent(AdminDialogComponent);

    // get test component from the fixture
    component = fixture.componentInstance;
   // component.ngOnInit();
  });
  beforeEach(inject([MatDialog, OverlayContainer],
    (d: MatDialog, oc: OverlayContainer) =&gt; {
      dialog = d;
      overlayContainer = oc;
    })
  );
  afterEach(() =&gt; {
    overlayContainer.ngOnDestroy();
  });
  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

});
</code></pre>

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

<blockquote>
  <p>**TypeError: Cannot read property 'emailId' of undefined error properties:</p>
</blockquote>

<p>Object({ ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 33669121, rootNodeFlags: 33554433, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 33554433, childFlags: 114688, directChildFlags: 114688, childMatchedQueries: 0, matchedQueries: Object({  }), matchedQueryIds: 0, references: Object({  }), ngContentIndex: null, childCount: 1, bindings: [  ], bindingFlags: 0, outputs: [  ], element: Object({ ns: '', name: 'admin-dialog', attrs: [  ], template: null, componentProvider: Object({ nodeIndex: 1, parent: , renderParent: , bindingIndex: 0, outputIndex: 0, checkIndex: 1, flags: 114688, childFlags: 0, directChildFlags: 0, childMatchedQueries: 0, matchedQueries: Object, matchedQueryIds: 0, references: Object, ngContentIndex: -1, childCount: 0, bindings: Array, bindingFlags: 0, outputs:  ...
    at 
    at AdminDialogComponent.emailId [as editAdmin] (<a href=""http://localhost:9876/_karma_webpack_/webpack:/src/app/dashboard/manage-admin/admin-dialog/admin-dialog.component.ts:52:51"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/webpack:/src/app/dashboard/manage-admin/admin-dialog/admin-dialog.component.ts:52:51</a>)
    at new editAdmin (<a href=""http://localhost:9876/_karma_webpack_/webpack:/src/app/dashboard/manage-admin/admin-dialog/admin-dialog.component.ts:30:18"" rel=""nofollow noreferrer"">http://localhost:9876/_karma_webpack_/webpack:/src/app/dashboard/manage-admin/admin-dialog/admin-dialog.component.ts:30:18</a>)</p>

<pre><code>Expected undefined to be truthy.
Error: Expected undefined to be truthy.**
</code></pre>

<p><strong>Spec file update</strong></p>

<pre><code>        import { AdminDialogComponent } from ""./admin-dialog.component"";
    import { TestBed, ComponentFixture,async,inject  } from '@angular/core/testing';
    import { FormsModule } from ""@angular/forms"";
    import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing';
    import {TranslateModule,TranslateService} from ""@ngx-translate/core"";
    import {Inject, NO_ERRORS_SCHEMA} from ""@angular/core"";
    import {MAT_DIALOG_DATA, MatDialog, MatDialogModule, MatDialogRef} from '@angular/material/dialog';
    import { OverlayContainer } from '@angular/cdk/overlay';
    import {HttpClientModule} from ""@angular/common/http"";
    import {RouterTestingModule} from ""@angular/router/testing"";
    import {DataService} from ""../../../services/data.service"";
    import {of} from ""rxjs/internal/observable/of"";

    describe('Component: admin-dialog', () =&gt; {

      let component: AdminDialogComponent;
      let fixture: ComponentFixture&lt;AdminDialogComponent&gt;;
      let translate: TranslateService;
      let dialog: MatDialog;
      let overlayContainer: OverlayContainer;
      let dataService: DataService;
      beforeEach(() =&gt; {


        TestBed.configureTestingModule({
          imports: [FormsModule, MatDialogModule, HttpClientModule,RouterTestingModule,TranslateModule.forRoot()],
          declarations: [AdminDialogComponent],
          providers: [TranslateService,
            { provide: MatDialogRef, useValue: {} },
            {
              provide: MAT_DIALOG_DATA, useValue: {
                isNew: false, // I guess it's boolean
                adminObj: {firstName: ""AAAAAA"", lastName: ""AA"", password: null, emailId: ""asdsAAA@ddd.com""}
              }
            },
            {provide: dataService, useValue: {}}],
          schemas: [NO_ERRORS_SCHEMA]
      });
        TestBed.overrideModule(BrowserDynamicTestingModule, {
          set: {
            entryComponents: [AdminDialogComponent]
          }
        });

        TestBed.compileComponents();

        // create component and test fixture
        fixture = TestBed.createComponent(AdminDialogComponent);

        // get test component from the fixture
        component = fixture.componentInstance;
       // component.ngOnInit();
      });
      beforeEach(inject([MatDialog, OverlayContainer],
        (d: MatDialog, oc: OverlayContainer) =&gt; {
          dialog = d;
          overlayContainer = oc;
        })
      );
      afterEach(() =&gt; {
        overlayContainer.ngOnDestroy();
      });
      it('should create', () =&gt; {
        expect(component).toBeTruthy();
      });
it('saveAdmin', () =&gt; {
    expect(component.saveAdmin()).toBeTruthy();
  });

    });
</code></pre>

<p><strong><em>After fixing all the error i could find less overage for this .ts file as in screenshot. so how to over this subscribe code in unit testing</em></strong></p>

<p><a href=""https://i.stack.imgur.com/JvTFQ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/JvTFQ.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/57305715/getting-following-error-in-karma-jasmine-unit-test-case-expected-undefined-to-b,"['angular', 'unit-testing', 'jasmine']",6224,True,0,1
.NET core write better unit tests with Xunit + Autofixture + Moq,"<p>In .NET Core for unit testing, I'm using Xunit, Moq, and Autofixture. But even with them, I see that my unit tests become complicated and take time.</p>
<p>Maybe someone could tell me if there are any ways to make this test smaller?</p>
<pre class=""lang-cs prettyprint-override""><code>[Fact]
public async Task Verify_NotAuthorised_NoServiceSendInvoked()
{
    // Arrange
    var fixture = new Fixture()
        .Customize(new AutoMoqCustomization());

    var sut = fixture.Create&lt;VerificationService&gt;();

    var mockApiBuilder = fixture.Freeze&lt;Mock&lt;IApiEntityBuilder&gt;&gt;();
    //init mocked mockSendServiceOne, so later I could check if it was invoked or not
    var mockSendServiceOne = fixture.Freeze&lt;Mock&lt;ISendServiceOne&gt;&gt;();

    mockApiBuilder.Setup(x =&gt; x.Verification(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;()))
        .Returns(fixture.Create&lt;VerificationEntity&gt;());

    var call = fixture.Freeze&lt;Mock&lt;ISendServiceTwo&gt;&gt;();
    call.Setup(x =&gt; x.IsSuccessful()).Returns(false);

    // Act
    await sut.Verify(fixture.Create&lt;string&gt;(), fixture.Create&lt;string&gt;());

    // Assert
    mockSendServiceOne.Verify(x =&gt; x.Call(It.IsAny&lt;SendServiceOneEntity&gt;()), Times.Never);
}
</code></pre>
<p>The testing method itself</p>
<pre class=""lang-cs prettyprint-override""><code>public async Task&lt;CreatedEntity&gt; Verify(string dataOne, string dataTwo)
{
   await _someCaller.Call(_apiEntityBuilder.Verification(dataOne, dataTwo));
   _someCaller.CreatePayment();

   if (!_someCaller.IsSuccessful()) return _someCaller.CreatedEntity;

   await mockSendServiceOne.Call(_apiEntityBuilder.Call(_someCaller.CreatedEntity.SpecificData));

   return _someCaller.CreatedEntity;
}
</code></pre>
<p>Here I am testing if isSuccessful() returns fasle then no mockSendServiceOne.Call should be invoked.</p>
<p>Could someone give me some feedback on how to write a better unit tests.
Because only for this small check of code I had to write a lot of code to test it.</p>
",https://stackoverflow.com/questions/58197457/net-core-write-better-unit-tests-with-xunit-autofixture-moq,"['unit-testing', '.net-core', 'moq', 'xunit', 'autofixture']",6917,True,4,1
Jest - Jest encountered an unexpected token. Vanilla JS,"<p>I'm trying to make a complex zip extractor in JavaScript and I decided that unit testing would be very important. That being said, a friend recommended Jest. I couldn't get any of my tests to work so I made a dumb test that made sure the first value of my JS Enum is 0. Jest, however, fails ever time saying that it encountered an unexpected token</p>

<p>I tried a more complex test and simplified it down to this simple test:</p>

<p>enums.js:</p>

<pre><code>const Format = {
    UNKNOWN: 0,
    ZIP: 1,
    TAR_GZIP: 2,
    TAR_BZIP: 3,
};

export default Format
</code></pre>

<p>enums.test.js</p>

<pre><code>const {Format} = require(""../src/enums.js"");

test(""bad test"", () =&gt; {
   expect(Format.UNKNOWN).toBe(0);
});
</code></pre>

<p>The error that is gives me is this:</p>

<pre><code>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:

    /home/giovanni/WebstormProjects/extract.js/src/enums.js:7
    export default Format;
    ^^^^^^

    SyntaxError: Unexpected token export

    &gt; 1 | const Format = require(""../src/enums.js"");
        | ^
      2 | 
      3 | test(""bad test"", () =&gt; {
      4 |    expect(Format.UNKNOWN).toBe(0);

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
      at Object.&lt;anonymous&gt; (test/enum.test.js:1:1)

</code></pre>
",https://stackoverflow.com/questions/57368105/jest-jest-encountered-an-unexpected-token-vanilla-js,"['javascript', 'jestjs']",1221,True,4,1
Nest.js: initialization of property from controller&#39;s superclass,"<p>I have a question regarding unit testing controllers in Nest.js framework. Problem is that property from a superclass is not initialized in the controller class when creating a test module.</p>

<p>This is a sample code I'm talking about:</p>

<pre class=""lang-js prettyprint-override""><code>export class MyController extends SomeOtherController {

    // Inherited from SomeOtherController
    async initSomeObject() {
        this.someObject = await initializeThisSomehow();
    }

    async controllerMethod(args: string) {
        // Do something
    }

}

export abstract class SomeOtherController implements OnModuleInit {

    protected someObject: SomeObject;

    async onModuleInit() {
        await this.initSomeObject();
    }

    abstract async initSomeObject(): Promise&lt;void&gt;;
}
</code></pre>

<p>And this is how I've created my test</p>

<pre class=""lang-js prettyprint-override""><code>describe('MyController', () =&gt; {
  let module: TestingModule;
  let controller: MyController;
  let service: MyService;

  beforeEach(async () =&gt; {
    module = await Test.createTestingModule({
      imports: [],
      controllers: [MyController],
      providers: [
        MyService,
        {
          provide: MyService,
          useFactory: () =&gt; ({
            controllerMethod: jest.fn(() =&gt; Promise.resolve()),
          }),
        },
      ],
    }).compile();

    controller = module.get(MyController);
    service = module.get(MyService);
  });

  describe('controller method', () =&gt; {
    it('should do something', async () =&gt; {
      jest.spyOn(service, 'controllerMethod').mockImplementation(async _ =&gt; mockResult);
      expect(await controller.controllerMethod(mockArgs)).toBe(mockResult);
    });
  });
});
</code></pre>

<p>Now, if I were to run the application in development mode, the <code>someObject</code> property would get initialized, and code works. But when running tests, it seems like the test module is not initializing it (so it is undefined).</p>

<p>Any sort of help is much appreciated.</p>
",https://stackoverflow.com/questions/58077788/nest-js-initialization-of-property-from-controllers-superclass,"['javascript', 'typescript', 'testing', 'jestjs', 'nestjs']",3066,True,4,1
Integration testing a node.js socket.io server,"<p>I'm trying to set up a server to respond to socket.io clients using nodejs, express and socket.io. I want to write tests to probe the server and make sure it's handling the events correctly and sending appropriate responses to the client.</p>

<p>I tried writing some automated tests using jest but I couldn't figure out how to actually emit events to the server and have it respond.</p>

<p><a href=""https://stackoverflow.com/questions/15509231/unit-testing-node-js-and-websockets-socket-io"">Unit testing Node.js and WebSockets (Socket.io)</a></p>

<p>I checked out the above post but it didn't work for me...</p>
",https://stackoverflow.com/questions/54390971/integration-testing-a-node-js-socket-io-server,"['node.js', 'unit-testing', 'testing', 'socket.io', 'automated-tests']",3344,True,1,1
How to unit test MatDialog (Angular Material) the correct way?,"<p>I am busy wit unit testing. And I have a Matdialog form Angular material.</p>

<p>I tried to test this two functions:</p>

<pre><code>openEcheqSelectorDialog() {
    this.dialog.open(EcheqSelectorComponent, {
      width: '600px',
      maxHeight: 'calc(100vh - 2em)',
      data: {
        participant: this.participant
      }
    });
  }

  openSchemaSelectorDialog() {
    this.dialog.open(SchemaSendDialogComponent, {
      width: '600px',
      maxHeight: 'calc(100vh - 2em)',
      data: {
        participant: this.participant
      }
    });
  }
</code></pre>

<p>And this is the complete component:</p>

<pre><code>
export class DetailComponent implements OnInit {
  participant: ParticipantInfoDTO;

  constructor(private dialog: MatDialog, route: ActivatedRoute) {
    this.participant = route.snapshot.data['participant'];
  }

  ngOnInit() {
  }

  openEcheqSelectorDialog() {
    this.dialog.open(EcheqSelectorComponent, {
      width: '600px',
      maxHeight: 'calc(100vh - 2em)',
      data: {
        participant: this.participant
      }
    });
  }

  openSchemaSelectorDialog() {
    this.dialog.open(SchemaSendDialogComponent, {
      width: '600px',
      maxHeight: 'calc(100vh - 2em)',
      data: {
        participant: this.participant
      }
    });
  }
}


</code></pre>

<p>But if I do this in the unit test:</p>

<pre><code>
import { async, TestBed, ComponentFixture } from '@angular/core/testing';
import { ParticipantModule } from '../../participant.module';
import { ActivatedRoute } from '@angular/router';
import { PARTICIPANT_INFO_DTO } from 'src/app/shared/stubs/participant-info-dto.stub';
import { MatDialog } from '@angular/material/dialog';
import { I18nStub } from 'src/app/shared/stubs/i18n-stub';
import { I18n } from '@ngx-translate/i18n-polyfill';
import { DetailComponent } from './detail.component';
import { RouterTestingModule } from '@angular/router/testing';

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

  let component: DetailComponent;
  let fixture: ComponentFixture&lt;DetailComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        ParticipantModule,
        RouterTestingModule
      ],
      providers: [
        MatDialog,
        { provide: ActivatedRoute, useValue: {
          snapshot: {
            data: {
              participant: PARTICIPANT_INFO_DTO[0]
            }
          }
        }},
        { provide: I18n, useValue: I18nStub }
      ]
    }).compileComponents().then( () =&gt; {
      fixture = TestBed.createComponent(DetailComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });
  }));

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

  it('should open the EcheqSelectorComponent in a MatDialog', () =&gt; {
    component.openEcheqSelectorDialog();
  });

  it('Should open the SchemaSelectorDialog in a MatDialog' , () =&gt; {
    component.openSchemaSelectorDialog();
  });

});


</code></pre>

<p>Then in the code coverage of jasmine karma. Everything seems been covered- it says 100%. But I don't think this is the correct way to do the unit tests.</p>

<p>So my question is: Is the correct?</p>

<p>Or what I have to improve?</p>

<p>Thank you</p>

<p>This is the template:</p>

<pre><code>&lt;div class=""header""&gt;
  &lt;h1 class=""heading list-heading""&gt;&lt;span i18n&gt;Participant&lt;/span&gt; - {{ participant.fullName }}&lt;/h1&gt;
&lt;/div&gt;
&lt;div class=""body pulled-up""&gt;
  &lt;mat-card class=""card-spacing""&gt;
    &lt;mat-card-header&gt;
      &lt;mat-card-title i18n&gt;Actions&lt;/mat-card-title&gt;
    &lt;/mat-card-header&gt;
    &lt;mat-card-content&gt;
      &lt;button mat-raised-button class=""button-spacing"" (click)=""openEcheqSelectorDialog()"" i18n&gt;Send echeq&lt;/button&gt;
      &lt;button mat-raised-button class=""button-spacing"" (click)=""openSchemaSelectorDialog()"" i18n&gt;Send schema&lt;/button&gt;
    &lt;/mat-card-content&gt;
  &lt;/mat-card&gt;
  &lt;mat-card class=""card-spacing""&gt;
      &lt;mat-card-header&gt;
        &lt;mat-card-title i18n&gt;Overviews&lt;/mat-card-title&gt;
      &lt;/mat-card-header&gt;
      &lt;mat-card-content&gt;
        &lt;button mat-raised-button class=""button-spacing"" routerLink=""echeq"" i18n&gt;Echeqs&lt;/button&gt;
        &lt;button mat-raised-button class=""button-spacing"" routerLink=""schema"" i18n&gt;Schemas&lt;/button&gt;
        &lt;button mat-raised-button class=""button-spacing"" routerLink=""qrcode"" i18n&gt;Qrcode scans&lt;/button&gt;
      &lt;/mat-card-content&gt;
    &lt;/mat-card&gt;
&lt;/div&gt;

</code></pre>
",https://stackoverflow.com/questions/59035295/how-to-unit-test-matdialog-angular-material-the-correct-way,"['javascript', 'angular', 'unit-testing', 'karma-jasmine', 'istanbul']",7878,True,1,1
Is there a more efficient way to dockerize Luarocks?,"<p>I am trying to build a lean alpine docker container for unit testing Lua in Google Cloud Build.</p>

<p>It runs fine, but takes about 30 - 50 seconds to build. When I run busted and luacheck, it only takes a few seconds for each. Any thoughts on how I could optimize this build process?</p>

<p>I was using wget and then switched to git. I added curl and unzip since luarocks expects it and openssl for one of luacheck's dependencies. Are there different dependencies I could/should use?</p>

<pre><code>FROM alpine

ENV LUA_VERSION 5.1

RUN apk update

RUN apk add lua${LUA_VERSION} 
RUN apk add lua${LUA_VERSION}-dev

RUN apk add bash build-base curl git openssl unzip

RUN cd /tmp &amp;&amp; \
    git clone https://github.com/keplerproject/luarocks.git &amp;&amp; \
    cd luarocks &amp;&amp; \
    sh ./configure &amp;&amp; \
    make build install &amp;&amp; \
    cd &amp;&amp; \
    rm -rf /tmp/luarocks

RUN luarocks install busted
RUN luarocks install luacheck
RUN luarocks install luacov
</code></pre>
",https://stackoverflow.com/questions/56533133/is-there-a-more-efficient-way-to-dockerize-luarocks,"['docker', 'google-cloud-build', 'luarocks']",1772,False,1,2
Test case fails for toThrow() matcher,"<p>I am new to unit testing in JS, learning <code>jest</code> framework. I have problem with simple <code>toThrow()</code> matcher that I test my throwing error function with.</p>

<p>I have written simple <code>foo()</code> function that only throws an Error and test it with <code>toThrow()</code> matcher.</p>

<p><code>index.js</code></p>

<pre class=""lang-js prettyprint-override""><code>export const foo = () =&gt; {
  throw new Error('bar');
};
</code></pre>

<p><code>index.test.js</code></p>

<pre class=""lang-js prettyprint-override""><code>import {foo} from './index';

test('foo', () =&gt; {
  expect(foo()).toThrow();
});
</code></pre>

<p>As far as I understand, as the function throws error in any case, the expected result checked by <code>toThrow()</code> should resolve to a passed test. However, when I run <code>yarn test</code> I get the following failure:</p>

<pre><code> FAIL  index.test.js
  ✕ foo (3ms)

  ● foo

    bar

      21 | 
      22 | export const foo = () =&gt; {
    &gt; 23 |   throw new Error('bar');
         |         ^
      24 | };
      25 | 

      at foo (index.js:23:9)
      at Object.&lt;anonymous&gt; (index.test.js:13:10)

Test Suites: 1 failed, 1 total
</code></pre>

<p>Is there some error in my code or maybe my understanding of the <code>toThrow()</code> matcher?</p>
",https://stackoverflow.com/questions/55927552/test-case-fails-for-tothrow-matcher,"['unit-testing', 'jestjs']",112,True,1,1
Mocking constructor to force my way into a conditional,"<p>So I'm doing unit testing and I need to make it into a conditional based upon the below condition (i.e I want the condition to be true)</p>

<pre><code>if(foo.body.constructor === Object &amp;&amp; Object.keys(foo.body).length === 0) {
.
.
.
}
</code></pre>

<p>My mock up looks like this so far.  This doesn't crash but it won't go into the conditional as I would like.</p>

<pre><code>let foo = {
    body:()=&gt; jest.fn()
}
</code></pre>

<p>I've also tried the below and noticed that the length returned is always 1.</p>

<pre><code>let foo = {
        body:{
            constructor: Object
        }
    }
</code></pre>

<p>Not sure what I need to do to get the length of foo.body to be 0 as well as have the foo.body.constructor be 0</p>
",https://stackoverflow.com/questions/54987679/mocking-constructor-to-force-my-way-into-a-conditional,"['javascript', 'testing', 'jestjs']",28,True,1,2
Unit Test Stored Proc with H2 Database,"<p>I am unit testing a stored proc which is returning 2 result set.</p>

<p>How I can do this with H2? 
I have created a a Alias but when I am returning a Array of result set it is not working.</p>

<pre><code>    public static ResultSet[] createDummyStoredProc(
      Connection connection,
      String one,
      String two,
      String three,
      String four) {
    Statement statement = null;
    ResultSet[] resultSets = new ResultSet[2];
    ResultSet resultSet=null;
    ResultSet resultSet1=null;
    try {

      statement = connection.createStatement();
      resultSet =
          statement.executeQuery(
              ""select nm_feature, in_feature, id_feature as id, in_ui from tempui"");

          resultSet1 =
          connection.createStatement().executeQuery(
              ""select t.nm_sp from tempbusiness t"");

    } catch (SQLException e) {
      e.printStackTrace();
    }
    resultSets[0]= resultSet;
    resultSets[1]= resultSet1;
    return resultSets;
  }
</code></pre>

<p>I am using Spring boot and JDBC Template( as I didn't get any solution in JPA to handle multiple resultset)</p>

<p><strong>Note:</strong> It is working as expected with one resultSet returned in place of array but I want to test it for 2 result set</p>
",https://stackoverflow.com/questions/54889993/unit-test-stored-proc-with-h2-database,"['unit-testing', 'spring-boot', 'spring-data-jpa', 'h2', 'jdbctemplate']",230,False,1,0
react-testing-library | Cannot Split Test into smaller chunks inside describe method,"<p>I'm learning about unit testing React components using <a href=""https://github.com/kentcdodds/react-testing-library"" rel=""nofollow noreferrer"">react-testing-library</a> </p>

<p>I have the component rendering correctly, however, when I aim to break the test into smaller chunks inside a <code>describe()</code> function. The test breaks and here's why.</p>

<p>Current only one or the other <code>test()</code> passes but not both</p>

<pre><code>import React from 'react'
import 'react-testing-library/cleanup-after-each'
import { render, fireEvent } from 'react-testing-library'
import Quantity from '../components/Quantity'

describe('Quantity Component', () =&gt; {
  const { container, getByTestId } = render(&lt;Quantity /&gt;)

// first test
  test('checks that quantity is never 0', () =&gt; {
    expect(getByTestId('quantity')).not.toBe('0')
  })

// second test
  test('checks for the initial product quantity count', () =&gt; {
    expect(getByTestId('quantity')).toHaveTextContent('1')

    fireEvent.click(getByTestId('increment'))
    expect(getByTestId('quantity')).toHaveTextContent('2')
  })
})
</code></pre>

<p>When trying to run both tests it errors:
<code>Unable to find an element by: [data-testid=""quantity""]</code></p>

<p><code>[data-testid=""quantity""]</code> is just an attribute that I passed inside my desired JSX tag. </p>

<p>The test passes when running <strong>only</strong> the first or second test but not <strong>both</strong> concurrently.</p>

<p>What am I missing here?</p>
",https://stackoverflow.com/questions/55769370/react-testing-library-cannot-split-test-into-smaller-chunks-inside-describe-me,"['reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",784,True,1,3
Mockito mocking Akka Streams,"<p><em>When unit testing, what is the best approach to mocking out Akka Streams calls involving Sources, Flows and Sinks?</em></p>

<hr>

<p>For example, the <a href=""https://doc.akka.io/docs/akka/current/stream/operators/Source-or-Flow/takeWhile.html"" rel=""nofollow noreferrer""><code>takeWhile</code></a> function:</p>

<pre><code>def takeWhile(p: Out =&gt; Boolean): Repr[Out]
</code></pre>

<p>Where <a href=""https://github.com/akka/akka/blob/4e670553021a859b55ba2b1606ef1ae5ba2369bf/akka-stream/src/main/scala/akka/stream/scaladsl/Flow.scala#L750"" rel=""nofollow noreferrer""><code>Repr</code></a> is a trait within a trait:</p>

<pre><code>trait FlowOps[+Out, +Mat] {
  import akka.stream.impl.Stages._
  import GraphDSL.Implicits._

  type Repr[+O] &lt;: FlowOps[O, Mat] {
    type Repr[+OO] = FlowOps.this.Repr[OO]
    type Closed = FlowOps.this.Closed
  }
</code></pre>

<p>If an object under test calls something like: <code>mySource.takeWhile( ... ).runWith( ... )</code> I might need to mock it out...</p>

<p>How do you work out how to mock out, e.g., <code>mock[Source[Any, Any]].takeWhile(*) returns mock[?]</code></p>

<p>The interactions between <code>Source</code>, <code>Repr</code>, <code>FlowOps</code>, and <code>Out</code> are unclear to me.</p>

<p>The source code for the <code>FlowOps</code> trait <a href=""https://github.com/akka/akka/blob/4e670553021a859b55ba2b1606ef1ae5ba2369bf/akka-stream/src/main/scala/akka/stream/scaladsl/Flow.scala#L740"" rel=""nofollow noreferrer"">warns</a> that it is internal and that one should not derive from it...does this affect mocking it?</p>
",https://stackoverflow.com/questions/58492452/mockito-mocking-akka-streams,"['scala', 'akka', 'akka-stream', 'mockito-scala']",642,True,1,1
Jest is throwing type errors from dependent node_modules,"<p>I am using Jest + Enzyme for unit testing of react application, and I am also using my company owned dependent libraries as node_modules , those are in Javascript (ES6) but my application and my test scripts are in TypeScript, so here while running tests Jest is throwing type errors from those libraries ( node_modules) as you see in below picture, Abstract.jsx is coming from dependent node_modules
<a href=""https://i.stack.imgur.com/rhA65.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/rhA65.png"" alt=""enter image description here""></a></p>

<p>I am using below setting in jest config which is not helping, how to fix this continuous type errors. please help</p>

<pre><code>""globals"": {
  ""ts-jest"": {
    ""diagnostics"": false
  }
},
</code></pre>
",https://stackoverflow.com/questions/54642863/jest-is-throwing-type-errors-from-dependent-node-modules,"['reactjs', 'typescript', 'unit-testing', 'jestjs', 'babeljs']",400,False,1,1
How to unit test a private static/shared method?,"<p>As per <a href=""https://stackoverflow.com/a/15607491/4516834"">this answer</a> to <a href=""https://stackoverflow.com/questions/9122708/unit-testing-private-methods-in-c-sharp"">Unit testing private methods in C#</a> I am using a <a href=""https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.privateobject?view=mstest-net-1.2.0"" rel=""nofollow noreferrer"">PrivateObject</a> to unit test private methods. This generally works really well and is quite easy to use, however it doesn't appear to work if the method is <code>Shared</code> or <code>Static</code>.</p>

<p>I don't really want to make the method public (otherwise I wouldn't even be bothering with PrivateObjects but I'm failing to see another way.</p>

<p>Example vb methods in class being tested: </p>

<pre class=""lang-vb prettyprint-override""><code>    Private Sub SampleInstanceMethod(arg as Object)
        'Do something
    End Sub
    Private Shared Sub SampleSharedMethod(arg as Object)
        'Do something
    End Sub
</code></pre>

<p>Unit test code</p>

<pre class=""lang-vb prettyprint-override""><code>    Dim fooBarPO = New PrivateObject(GetType(FooBar))
    fooBarPO.Invoke(""SampleInstanceMethod"", {arg1}) ' Works
    fooBarPO.Invoke(""SampleSharedMethod"", {arg1}) ' Doesn't work
</code></pre>

<p>Interested in answers in either C# or VB</p>
",https://stackoverflow.com/questions/58801553/how-to-unit-test-a-private-static-shared-method,"['c#', '.net', 'vb.net', 'unit-testing']",468,True,0,1
Typescript Express unit rest case issues,"<p>I am using typescript with express in my project. I am using mocha and chai for unit testing. My package.json is as follows:</p>

<pre><code>{
  ""name"": ""node_ts"",
  ""version"": ""1.0.0"",
  ""description"": """",
  ""main"": ""dist/server.js"",
  ""scripts"": {
    ""lint"": ""./node_modules/.bin/tslint --project \"".\"""",
    ""build"": ""babel src --out-dir lib --extensions \"".ts,.tsx\"""",
    ""serve"": ""npm run build &amp;&amp; tsc &amp;&amp; node lib/server.js"",
    ""compile"": ""tsc &amp;&amp; node lib/server.js"",
    ""start"": ""nodemon -e ts --exec \""npm run build &amp;&amp; npm run compile\"""",
    ""test"": ""mocha --compilers babel-register-ts src/**/*.spec.ts""
  },
  ""keywords"": [],
  ""author"": """",
  ""license"": ""ISC"",
  ""devDependencies"": {
    ""@babel/cli"": ""^7.2.3"",
    ""@babel/core"": ""^7.2.2"",
    ""@babel/plugin-proposal-object-rest-spread"": ""^7.3.1"",
    ""@babel/preset-env"": ""^7.3.1"",
    ""@babel/preset-typescript"": ""^7.1.0"",
    ""@types/chai"": ""^4.1.7"",
    ""@types/mocha"": ""^5.2.5"",
    ""babel-register"": ""^6.26.0"",
    ""chai"": ""^4.2.0"",
    ""mocha"": ""^5.2.0"",
    ""nodemon"": ""^1.18.9"",
    ""ts-node"": ""^8.0.2"",
    ""tslint"": ""^5.12.1"",
    ""typescript"": ""^3.3.1""
  },
  ""dependencies"": {
    ""@babel/plugin-proposal-class-properties"": ""^7.3.0"",
    ""@babel/register"": ""^7.0.0"",
    ""@types/chai-http"": ""^3.0.5"",
    ""@types/express"": ""^4.16.1"",
    ""babel-register-ts"": ""^7.0.0"",
    ""chai-http"": ""^4.2.1"",
    ""express"": ""^4.16.4""
  }
}
</code></pre>

<p>when i am running my server using</p>

<pre><code>npm run start
</code></pre>

<p>I am getting the following issues.</p>

<pre><code>node_modules/chai-http/types/index.d.ts:51:19 - error TS2430: Interface 'ChaiHttp.Response' incorrectly extends interface 'import(""/home/anshu/projects/node_ts/node_modules/@types/superagent/index"").Response'.
  Types of property 'setEncoding' are incompatible.
    Type '(encoding: string) =&gt; void' is not assignable to type '(encoding: string) =&gt; this'.
      Type 'void' is not assignable to type 'this'.

51         interface Response extends request.Response {}
                     ~~~~~~~~

node_modules/chai-http/types/index.d.ts:52:19 - error TS2430: Interface 'Agent' incorrectly extends interface 'SuperAgentStatic'.
  Types of property 'del' are incompatible.
    Type '(url: string, callback?: (err: any, res: Response) =&gt; void) =&gt; Request' is not assignable to type '(url: string, callback?: CallbackHandler) =&gt; SuperAgentRequest'.
      Types of parameters 'callback' and 'callback' are incompatible.
        Types of parameters 'res' and 'res' are incompatible.
          Type 'ChaiHttp.Response' is not assignable to type 'import(""/home/anshu/projects/node_ts/node_modules/@types/superagent/index"").Response'.
            Types of property 'setEncoding' are incompatible.
              Type '(encoding: string) =&gt; void' is not assignable to type '(encoding: string) =&gt; Response'.
                Type 'void' is not assignable to type 'Response'.

52         interface Agent extends request.SuperAgentStatic {
                     ~~~~~


Found 2 errors.
</code></pre>

<p>Also when I am trying to run my test case using</p>

<pre><code>mocha --compilers babel-register-ts src/**/*.spec.ts
</code></pre>

<p>I am getting the error as : TypeError: chai.request is not a function</p>

<p>My test file is as follows:</p>

<pre><code>#hello.ts    
    import app from ""../app"";
    import * as chai from ""chai"";
    import chaiHttp from ""chai-http"";
    import ""mocha"";

    chai.use(chaiHttp);
    const expect = chai.expect;

    describe(""Hello API Request"", () =&gt; {
      it(""should return response on call"", () =&gt; {
        return chai.request(app).get(""/"")
          .then(res =&gt; {
            expect(res).to.eql(""lee"");
          });
      });
    });
</code></pre>

<p>I think this is due to chai-http. Can anyone help to overcome this issue or provide any alternate solution.</p>
",https://stackoverflow.com/questions/54516774/typescript-express-unit-rest-case-issues,"['typescript', 'express', 'mocha.js', 'chai']",334,False,0,0
Jest XMLHttpRequest mock request shows error,"<p>I have following function.</p>

<pre><code>export function sendWeatherrequest(countryName) {
    let xmrRequest = new XMLHttpRequest();
    xmrRequest.onload = requestListener;
    xmrRequest.onerror = requestError;

    xmrRequest.open('get', generateUrl(name), true);
    xmrRequest.send(); 
}

function requestListener() {
    let data = JSON.parse(this.responseText);
    displayPage(data); 
}
</code></pre>

<p>I am using <strong>jest</strong> for unit test.</p>

<p>As, i read somewhere that it is bad idea to test original XMLHttpRequest. Is it true? </p>

<p>So, created following from <a href=""https://stackoverflow.com/questions/28584773/xhr-testing-in-jest"">XHR testing in Jest</a> answer</p>

<pre><code>let open, send, status, onload, setRequestHeader, response;
function createXHRmock() {
    open = jest.fn();
    status = 200;
    response = JSON.stringify([{
        title: 'some data.',
        weather: 'wind'
    }]);

    send = jest.fn().mockImplementation(function(){   
        onload = this.onload.bind(this);
        onerror = this.onerror.bind(this);
    });

    const xhrMockClass = function () {
        return {
            open,
            send,
            status,
            setRequestHeader,
            response
        };
    };

    window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass);
}

it('XHR success', () =&gt; {
    createXHRmock();

    expect(open).toBeCalledWith('GET', 'http://example.com', true);
    expect(send).toBeCalled();

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

<p>But, i am getting following error.</p>

<blockquote>
  <p>XHR success</p>
  
  <p>expect(jest.fn()).toBeCalledWith(expected)</p>
  
  <p>Expected mock function to have been called with:
        [""GET"", ""<a href=""http://example.com"" rel=""nofollow noreferrer"">http://example.com</a>"", true]
      But it was not called.</p>
</blockquote>

<p>My be i done some stupid mistake but, can't figureout. I am very poor in unit testing.</p>

<p>Any help would be greatly appreciated.</p>
",https://stackoverflow.com/questions/54328113/jest-xmlhttprequest-mock-request-shows-error,"['javascript', 'unit-testing', 'jestjs']",3977,False,3,1
parsing object not working as expected in typescript,"<p>Are line1 and line 2 below equal to line3?</p>

<pre><code>let resultObject:UserProfileAPI  =JSON.parse(subscribed['additional-info']) as UserProfileAPI; //line 1
this.profile = new UserProfileAPI(new User(resultObject[""external-profile""].firstname,resultObject[""external-profile""].lastname,resultObject[""external-profile""].email))//line2 
//this.profile = JSON.parse(subscribed['additional-info']) as UserProfileAPI; //uncommenting line3 doesn't work if swapped with line1 and line2. I suppose line 1 and line2 do the same thing together as line 3
</code></pre>

<p>I have this piece of code. I am unable to understand why the un-commented code works but swapping it with the commented like doesn't</p>

<pre><code>profile:UserProfileAPI;
...
(result:Result)=&gt; {
        console.log(""In nav - result from user signin state "",result);
        let subscribed:UserSigninState = result.additionalInfo;
        console.log(""new user signin state received:"", subscribed);
        this.userLoggedIn = subscribed.isSignedIn;
        //success in login and got profile
        if(subscribed.isSignedIn ){
          if(subscribed['additional-info'] !== '') {
            let resultObject:UserProfileAPI  =JSON.parse(subscribed['additional-info']) as UserProfileAPI; //line 1 works
            this.profile = new UserProfileAPI(new User(resultObject[""external-profile""].firstname,resultObject[""external-profile""].lastname,resultObject[""external-profile""].email))//line2 works
            //this.profile = JSON.parse(subscribed['additional-info']) as UserProfileAPI; //uncommenting line3 doesn't work if swapped with line1 and line2. I suppose line 1 and line2 do the same thing together as line 3
          }else{
            console.log('login successful but didn\'t get profile');
            this.profile = new UserProfileAPI(new User('unavailable','unavailable','unavailable'));
          }
        }
        //fail in login, additional-inifo should have reason
        if(!subscribed.isSignedIn ){
          if(subscribed['additional-info'] !== '') {
            this.navEvent.emit(new NavContext(subscribed['additional-info']));
          } else{
            console.log('login wasn\'t successful but didn\'t get the reason for error');
            this.navEvent.emit(new NavContext('login failed. Reason unknown'));
          }
        }
      }
</code></pre>

<p>I am unit-testing the above piece of code in <code>Jasmine</code>. The spec tests that on successful login, the server should send user's profile which the client should store.</p>

<pre><code>fit('should set user profile for successful signin attempt',()=&gt;{
    let navComponent:NavComponentComponent = component;
    let userManagementService:MockUserManagementService = TestBed.get(UserManagementService);
    let user = new User('manu','chadha','test@test.com');//create a user
    let dummyUserProfile= new UserProfileAPI(user);//create a dummy profile using user
    console.log('dummy profile is ',dummyUserProfile);//prints 'dummy profile is ', UserProfileAPI{external-profile: User{firstname: 'manu', lastname: 'chadha', email: 'test@test.com', password: ''}} 
    console.log('dummy profile is JSON stringify',JSON.stringify(dummyUserProfile));//prints 'dummy profile is JSON stringify', '{""external-profile"":{""firstname"":""manu"",""lastname"":""chadha"",""email"":""test@test.com"",""password"":""""}}'
    let userSignInState = new UserSigninState(true,JSON.stringify(dummyUserProfile));//create part of response as string
    console.log('user signin state ',userSignInState);//prints 'user signin state ', UserSigninState{isSignedIn: true, additional-info: '{""external-profile"":{""firstname"":""manu"",""lastname"":""chadha"",""email"":""test@test.com"",""password"":""""}}'}
   let result:Result = new Result('success',userSignInState);
console.log('result is ',result);//prints 'result is ', Result{result: 'success', additionalInfo: UserSigninState{isSignedIn: true, additional-info: '{""external-profile"":{""firstname"":""manu"",""lastname"":""chadha"",""email"":""test@test.com"",""password"":""""}}'}}
userManagementService.signInStateSubject.next(result);//send response
    console.log('user profile is ',navComponent.profile);//prints user profile is ', Object{external-profile: Object{firstname: 'manu', lastname: 'chadha', email: 'test@test.com', password: ''}}
    expect(navComponent.profile).toBeTruthy();
    expect(navComponent.profile).toEqual(dummyUserProfile);
  });
</code></pre>

<p>The above test doesn't work for code if I comment line1 and line2 and use only line3</p>

<pre><code>if(subscribed['additional-info'] !== '') {
   //                let resultObject:UserProfileAPI  =JSON.parse(subscribed['additional-info']) as UserProfileAPI; //line1
      //              this.profile = new UserProfileAPI(new User(resultObject[""external-profile""].firstname,resultObject[""external-profile""].lastname,resultObject[""external-profile""].email)) //line2
                    this.profile = JSON.parse(subscribed['additional-info']) as UserProfileAPI; //line3
</code></pre>

<p>For above, I get error <code>Expected object to be a kind of UserProfileAPI, but was Object({ external-profile: Object({ firstname: 'manu', lastname: 'chadha', email: 'test@test.com', password: '' }) }).</code></p>
",https://stackoverflow.com/questions/54029610/parsing-object-not-working-as-expected-in-typescript,['typescript'],45,False,0,0
zf3 unit testing: getHeaders not accessible in onBootstrap,"<p>I am using <code>Module.php</code> <code>onBootstrap</code>function to check using authentication. on Postman and with browser everything works fine but when unittesting with <code>zend-test</code> it is not able to access the <code>getHeaders()</code> 
MY <code>Module.php</code></p>

<pre><code>     public function onBootstrap(MvcEvent $e)
      {
        $app = $e-&gt;getTarget();
        $locator = $app-&gt;getServiceManager();
        $this-&gt;authorize($e);
      }

      public function authorize($e){
        $sm = $e-&gt;getApplication()-&gt;getServiceManager();
        $request = $sm-&gt;get('Request');

       if($request-&gt;getHeaders('auth_token')){
            return;
        }
        $response = $e-&gt;getResponse();
    $model = new JsonModel(array(
        ""httpStatus"" =&gt; 401,
        ""title"" =&gt; ""Token Not Found"",
    ));
    $e-&gt;getResponse()-&gt;setStatusCode(401);
    $model-&gt;detail = ""Auth Token not provided"";

    $model-&gt;setTerminal(true);
    $e-&gt;setResult($model);
    $e-&gt;setViewModel($model);
}
</code></pre>

<p>Now i tried to follow <a href=""https://stackoverflow.com/questions/39075255/zf3-unit-test-authentication-onbootstrap"">this</a> but i couldn't because the code is so difficult to follow.</p>

<p>My test is something like that:</p>

<pre><code>public function testIndexIsAccessibleAction() {
    $headers = new \Zend\Http\Headers();
    $headers-&gt;addHeaders([
        ""auth_token"" =&gt; 'token' 
    ]);
    $this-&gt;getRequest()
            -&gt;setMethod('GET')
            -&gt;getHeaders()
            -&gt;addHeaders($headers);
         ;
    $this-&gt;dispatch('/action');
    $this-&gt;assertResponseStatusCode(200);
}
</code></pre>

<p>Now i am checking every request in <code>onBootstrap</code> because nothing is accessible if user is not authentic. How do i do my unit testing correctly. and how should i change it to using <code>Service</code> or <code>Factory</code>?</p>
",https://stackoverflow.com/questions/57951296/zf3-unit-testing-getheaders-not-accessible-in-onbootstrap,"['php', 'unit-testing', 'doctrine', 'zend-framework2', 'zend-framework3']",48,False,0,0
FluentValidation with ASP.NET Core: Ensure validation is active,"<p>We use FluentValidation for input validation in our ASP.NET Core MVC controllers. Since the validators are a critical part of the system from a security point of view, we'd like to create unit tests that ensure that validation in actually active, and that the right validator is used for each controller.</p>

<p>We enable FluentValidation as usual in <code>Startup.cs</code>:</p>

<pre><code>services.AddMvc(...).AddFluentValidation(...);
</code></pre>

<p>I haven't been able to find anything about this, only about unit testing the validators directly, which is a different case.</p>

<p>How do we unit-test the validation chain?</p>
",https://stackoverflow.com/questions/56335803/fluentvalidation-with-asp-net-core-ensure-validation-is-active,"['asp.net-core', 'asp.net-core-mvc', 'fluentvalidation']",426,False,0,1
What package level access needed in Java for?,"<p>In general what package level access needed in Java for? 
I can suggest only one reason:</p>

<ol>
<li>Unit testing</li>
</ol>

<p>Something else?</p>

<p><strong>UPD 1</strong></p>

<p>I know what is <strong>package level access</strong>. It's when any code from the same package can access. My question is: <strong>why</strong> this access level is needed? Why java creators invent this new level. I guess not for nothing but in purpose. What is the purpose?</p>

<p><strong>UPD2</strong></p>

<p>Actually the answer is found here: <a href=""https://softwareengineering.stackexchange.com/questions/220053/why-did-java-make-package-access-default/220066#220066"">https://softwareengineering.stackexchange.com/questions/220053/why-did-java-make-package-access-default/220066#220066</a></p>
",https://stackoverflow.com/questions/58756622/what-package-level-access-needed-in-java-for,"['java', 'access-modifiers']",72,True,-5,1
Cannot set property &#39;paginator&#39; of undefined - Unit Testing,"<p>I'm doing a unit testing on one of my component in Angular. The test scenario is to check if a div element with a class <code>.div-container</code> is exists in the page.
So basically, a variable in my component.ts dictates whether the said div is visible or not using <code>*ngIf</code>.</p>

<p>Please see my codes below what I have so far.</p>

<p><strong>HTML</strong></p>

<pre><code>&lt;div *ngIf=""isAdmin""&gt;
    &lt;div class='div-container'&gt;
       &lt;table mat-table [dataSource]=""dataSource"" matSort matSortActive=""DisplayName""
        matSortDirection=""asc"" matSortDisableClear&gt;
        &lt;ng-container matColumnDef=""Firstname""&gt;
          &lt;th mat-header-cell *matHeaderCellDef mat-sort-header&gt;First Name&lt;/th&gt;
          &lt;td mat-cell *matCellDef=""let row""&gt;
            {{row.Firstname}}
          &lt;/td&gt;
        &lt;/ng-container&gt;

        &lt;ng-container matColumnDef=""Lastname""&gt;
          &lt;th mat-header-cell *matHeaderCellDef mat-sort-header&gt;Last Name&lt;/th&gt;
          &lt;td mat-cell *matCellDef=""let row""&gt;{{row.Lastname}}&lt;/td&gt;
        &lt;/ng-container&gt;

        &lt;ng-container matColumnDef=""Gender""&gt;
          &lt;th mat-header-cell *matHeaderCellDef mat-sort-header&gt;Gender&lt;/th&gt;
          &lt;td mat-cell *matCellDef=""let row""&gt;{{row.Gender}}&lt;/td&gt;
        &lt;/ng-container&gt;

        &lt;tr mat-header-row *matHeaderRowDef=""displayedColumns""&gt;&lt;/tr&gt;
        &lt;tr mat-row *matRowDef=""let row; columns: displayedColumns;""&gt;&lt;/tr&gt;
      &lt;/table&gt;
      &lt;mat-paginator [length]=""resultsLength"" [pageSizeOptions]=""[10, 25, 50, 100]"" showFirstLastButtons&gt;&lt;/mat-paginator&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p><strong>TS</strong></p>

<pre><code>@Component({
    ...
})
export class SampleComponent implements OnInit {
  @ViewChild(MatSort, { static: false }) set matSort(ms: MatSort) {
    if (ms !== undefined) {
      this.sort = ms;
      this.dataSource.sort = this.sort;
    }
  }

  @ViewChild(MatPaginator, { static: false }) set matPaginator(mp: MatPaginator) {
    if (mp !== undefined) {
      this.paginator = mp;
      this.dataSource.paginator = this.paginator;
    }
  }

  ngOnInit() {
    this.names$ = this.dataService.names$
      .pipe(
        tap(names =&gt; {
          this.isLoadingResults = false;
          this.resultsLength = names.value.length;

          this.dataSource = new MatTableDataSource(names.value);
        }),
        catchError(this.handleError)
      )
  }
}
</code></pre>

<p><strong>SPEC</strong></p>

<pre><code>describe('SampleComponent', () =&gt; {
  let component: SampleComponent;
  let fixture: ComponentFixture&lt;SampleComponent&gt;;

    beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [SharedModule,
        MatPaginatorModule,
        MatSortModule,
        BrowserAnimationsModule],
      declarations: [SampleComponent]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(SampleComponent);
    component = fixture.componentInstance;

    paginator = component.matPaginator;
    sort = component.matSort;

    fixture.detectChanges();
  });

  it(`should hide the div container if 'isAdmin' is false`, () =&gt; {
    component.isAdmin = false;
    fixture.detectChanges();

    expect(fixture.debugElement.query(By.css('.div-container'))).toBeNull();
  });

  it(`should show the div container if 'isAdmin' is true`, () =&gt; {
    component.isAdmin = true;

    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('.div-container'))).toBeTruthy();
  });
);
</code></pre>

<p>Unfortunately, I cannot make this test to pass due to this error.</p>

<pre><code>TypeError: Cannot set property 'paginator' of undefined.
</code></pre>

<p>Hope someone can guide me on how to properly address this error.</p>

<p>TIA!</p>
",https://stackoverflow.com/questions/58833593/cannot-set-property-paginator-of-undefined-unit-testing,"['angular', 'angular-material', 'karma-jasmine']",3991,False,0,1
Scroll action for ScrollView not working when unit-testing,"<p>I have the following problem. I'm making <em>unit-tests</em> for a custom <code>DialogFragment</code>. This dialog has a <code>Scrollview</code>. when reaching the end of which, a <code>ViewSwitcher</code> has to switch a view. </p>

<p>Here is the scroll listener:</p>

<pre class=""lang-java prettyprint-override""><code>ViewSwitcher vs = getDialog().findViewById(R.id.vs);
scrollView.getViewTreeObserver()
     .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
      @Override
      public void onScrollChanged() {
           if (scrollView.getChildAt(0).getBottom()
                &lt;= (scrollView.getHeight() + scrollView.getScrollY())) {
                vs.setDisplayedChild(1);
            } else {
                vs.setDisplayedChild(0);
            }
       }
 });
</code></pre>

<p>A test setup method:</p>

<pre class=""lang-java prettyprint-override""><code>@Before
public void setUp() throws Exception {
    activity = Robolectric
        .buildActivity(FragmentTestActivity.class)
        .create()
        .resume()
        .get();

    subject = MemberConsentModal.newInstance(""long text"");
    subject.show(activity.getSupportFragmentManager(), MemberConsentModal.TAG);
}
</code></pre>

<p>And the test method code:</p>

<pre class=""lang-java prettyprint-override""><code>@Test
public void onScrolledToTopBottom_showOptionButtons() {
    final ScrollView scrollView = subject.getDialog().findViewById(R.id.member_consent_content);
    ViewSwitcher vs = subject.getDialog().findViewById(R.id.vs);

    scrollView.fullScroll(ScrollView.FOCUS_DOWN);

    assertThat(vs.getDisplayedChild()).isEqualTo(1);
}
</code></pre>

<p>When debugging, I see that <code>addOnScrollChangedListener</code> is never called, though, when launching the application as on an emulator, as on a physical device, it is working correctly. How can I make the scroll view to be scrolled in testing mode? </p>

<p>PS.
I'm using <code>Robolectric</code> and <code>Mockito</code> for <em>unit-testing</em>.</p>
",https://stackoverflow.com/questions/56049505/scroll-action-for-scrollview-not-working-when-unit-testing,"['android', 'unit-testing', 'android-scrollview', 'viewswitcher']",729,False,3,0
"Symfony 4, PHPUnit - authorize user for unit test","<p>I'm writing test to do the unit testing of controller. I want to check if I get the proper content for the url, which requires user to be logged in.</p>

<p>I have following test written</p>

<pre><code>class AdminControllerTest extends WebTestCase
{
    private $client = null;

    public function setUp()
    {
        $this-&gt;client = static::createClient();
    }

    public function testAdminHome(): void
    {
        $this-&gt;logIn();
        $crawler = $this-&gt;client-&gt;request('GET', '/admin/');

        $this-&gt;assertSame(Response::HTTP_OK, $this-&gt;client-&gt;getResponse()-&gt;getStatusCode());
        $this-&gt;assertGreaterThan(0, $crawler-&gt;filter('html:contains(""Welcome to Admin Panel"")')-&gt;count());
    }

    private function logIn()
    {
        $user = new User();
        $user-&gt;setId(1);
        $user-&gt;setEmail('test@admin.com');
        $user-&gt;setFullName('Admin User');
        $user-&gt;setEnabled(true);

        $session = $this-&gt;client-&gt;getContainer()-&gt;get('session');

        $firewallName = 'main';
        $firewallContext = 'main';

        $token = new UsernamePasswordToken($user, null, $firewallName, ['ROLE_ADMIN']);
        $session-&gt;set('_security_'.$firewallContext, serialize($token));
        $session-&gt;save();

        $cookie = new Cookie($session-&gt;getName(), $session-&gt;getId());
        $this-&gt;client-&gt;getCookieJar()-&gt;set($cookie);
    }
}

</code></pre>

<p>Configuration in my security.yml</p>

<pre><code>security:
    encoders:
        App\Entity\User: auto

    providers:
        database_users:
            entity:
                class: App\Entity\User
                property: username
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: true
            pattern: ^/
            context: main

            form_login:
                check_path: security_login
                login_path: security_login
                csrf_token_generator: security.csrf.token_manager
                default_target_path: admin_home

            logout:
                path: security_logout
                target: security_login

    access_control:
         - { path: ^/admin, roles: [ROLE_ADMIN, ROLE_EDITOR] }
    role_hierarchy:
        ROLE_ADMIN: ROLE_EDITOR
        ROLE_EDITOR: ROLE_USER
</code></pre>

<p>However assertion for the Response code returns me 200, but I land on login page instead of admin home. Also there is not required content, as I'm on login page not an admin home.</p>

<p>Could you please check the code and help me find out the issue?</p>
",https://stackoverflow.com/questions/59472651/symfony-4-phpunit-authorize-user-for-unit-test,"['symfony', 'phpunit', 'symfony4']",354,False,-1,1
Unit test Angular with stubbing a variable,"<p>I have created a class in Angular 7 to load a config file for environment variables. This is using the accepted answer here <a href=""https://stackoverflow.com/questions/49559009/angular5-deploying-angular-application-to-multiple-clients"">Angular5: Deploying Angular application to multiple clients</a></p>

<p>Now I want to add unit testing to my Services but I get the following error:</p>

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

<p>In other words when appConfig is imported, it is not recognised.</p>

<p>How can I stub the variable below to solve the error? I've tried using spy's but cannot get it working:</p>

<pre><code>/**
 * Global variable containing actual config to use. Initialised via ajax call
 */
export let appConfig: AppConfig;
</code></pre>
",https://stackoverflow.com/questions/55964769/unit-test-angular-with-stubbing-a-variable,"['angular', 'jasmine', 'stub']",129,False,0,0
Spring Boot - Unit Test on Controller - 404 Answer,"<p>I am setting up the unit testing on my @RestController's, but It is not working correctly.</p>

<p>This is only a unit test to validate the answer from the method of the RestEndpoint, but It is not working, please help me because I tried a lot of configurations and read the documentation and nothing worked.</p>

<p>This is my endpoint:</p>

<pre><code>@RestController
@RequestMapping(""/clients"")
public class ClientsEndpoint extends RestConfiguration {

@Autowired
private IClientService clientService;

@GetMapping(value = ""/{id}"")
private Object getById(@PathVariable(required = true) Long id) {
    try {
        Optional&lt;Client&gt; clientOptional = clientService.getById(id);
        if (clientOptional.isPresent()) {
            return clientOptional.get();
        } else 
            return new GeneralResponse(ErrorsEnum.CLIENT_NOT_FOUND);
    } catch (Exception e) {
        log.log(Level.SEVERE, ""Problemas al obtener datos del cliente con id: "" + id, e);
        return new GeneralResponse(ErrorsEnum.GENERAL_ERROR);
    }
}
</code></pre>

<p>This is my Unit Test where I only added the mock of the endpoint and a simple call is done:</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(ClientsEndpoint.class)
@ContextConfiguration(classes={ApplicationConfiguration.class})
public class QuarzoApiApplicationTests {

@Autowired
private MockMvc mockMvc;

@MockBean
private IClientService clientService;

@Test
public void getById() throws Exception {
    Client client = new Client(""Test"", ""Test"", ""Test"", (byte) 1,
            ""Test"", ""Test"", ""Test"", ""Test"", (byte) 1,
            (byte) 1, (short)1, ""Test"" );
    Optional&lt;Client&gt; clientOptional = Optional.of(client);
    BDDMockito.given(clientService.getById(anyLong())).willReturn(clientOptional);

    this.mockMvc.perform(get(""/clients/1"")
            .header(""Authorization"",""Bearer "" + TestUtils.createToken(""miltonc"")))
            .andExpect(status().isOk());
}
</code></pre>

<p>Results I am getting after running the unit test:</p>

<pre><code>2019-08-27 10:01:18.505  INFO 23606 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@7da39774, org.springframework.security.web.context.SecurityContextPersistenceFilter@5b7c8930, org.springframework.security.web.header.HeaderWriterFilter@4277127c, org.springframework.web.filter.CorsFilter@441b8382, org.springframework.security.web.authentication.logout.LogoutFilter@1a6dc589, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@40e32762, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@6f231ced, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@1df1ced0, org.springframework.security.web.session.SessionManagementFilter@2c05ff9d, org.springframework.security.web.access.ExceptionTranslationFilter@2a8a4e0c, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@27755487]
2019-08-27 10:01:18.526  INFO 23606 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring TestDispatcherServlet ''
2019-08-27 10:01:18.527  INFO 23606 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
2019-08-27 10:01:18.533  INFO 23606 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 6 ms
2019-08-27 10:01:18.555  INFO 23606 --- [           main] i.q.quarzoapi.QuarzoApiApplicationTests  : Started QuarzoApiApplicationTests in 1.371 seconds (JVM running for 1.825)

MOCK org.springframework.test.web.servlet.MockMvc@770beef5

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /clients/1
       Parameters = {}
          Headers = [Authorization:""Bearer eyJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE1NjY5MTQ0NzgsImlzcyI6IlFVQVJaTyIsInN1YiI6Im1pbHRvbmMiLCJleHAiOjE1NjY5NjQ4MDB9.hLu1Mcl_K-8smYnZnDu1ubkVTuNCkQnqhIQuypBsKBzQYxMlYlxqXhsYLCMB5iViCcDK33WXvO1Pjp15TR1ICg""]
             Body = &lt;no character encoding set&gt;
    Session Attrs = {}

Handler:
             Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = [X-Content-Type-Options:""nosniff"", X-XSS-Protection:""1; mode=block"", Cache-Control:""no-cache, no-store, max-age=0, must-revalidate"", Pragma:""no-cache"", Expires:""0"", X-Frame-Options:""DENY""]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []



java.lang.AssertionError: Status 
Expected :200
Actual   :404
&lt;Click to see difference&gt;


    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
    at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)
    at io.quarzo.quarzoapi.QuarzoApiApplicationTests.getById(QuarzoApiApplicationTests.java:78)
    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: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.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)


2019-08-27 10:01:18.772  INFO 23606 --- [       Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
</code></pre>
",https://stackoverflow.com/questions/57663357/spring-boot-unit-test-on-controller-404-answer,"['spring-boot', 'spring-mvc', 'spring-security', 'junit4', 'spring-test']",1696,True,0,1
Mocking IJSRuntime for Blazor Component unit tests,"<p>Following <a href=""https://blog.stevensanderson.com/2019/08/29/blazor-unit-testing-prototype/"" rel=""noreferrer"">this prototype</a> for unit testing I've ran into a problem when using JS interop.</p>

<pre><code>[Test]
public void ExampleTest()
{
    var component = host.AddComponent&lt;MyComponent&gt;();
}
</code></pre>

<p>Just adding a component that uses IJSRuntime will cause the following exception </p>

<blockquote>
  <p>System.InvalidOperationException : Cannot provide a value for property 'JsRuntime' on type 'Application.Components.MyComponent'. There is no registered service of type 'Microsoft.JSInterop.IJSRuntime'.</p>
</blockquote>

<p>The JS interop isn't doing anything of interest, it's just a void function that focuses an element - I don't care about testing it, I just want to be able to proceed with writing tests for the component itself.</p>

<p>How can I use Moq to mock IJSRuntime?</p>

<p>When I try something like</p>

<pre><code>[Test]
public void ExampleTest()
{
    var jsRuntimeMock = new Mock&lt;IJSRuntime&gt;();

    host.AddService(jsRuntimeMock);

    var component = host.AddComponent&lt;MyComponent&gt;();
}
</code></pre>

<p>I still get the exception</p>
",https://stackoverflow.com/questions/58589595/mocking-ijsruntime-for-blazor-component-unit-tests,"['c#', 'unit-testing', 'moq', 'blazor']",1873,True,8,2
Why to use MVVM instead of MVC in android,"<p><strong>What I am aware of</strong></p>

<ul>
<li>I have been using MVC with android for a while</li>
<li>Now I am learning MVVM with Data binding</li>
<li>I am aware of architecture difference between the two</li>
</ul>

<hr>

<p><strong>Questions</strong></p>

<ul>
<li>How MVVM usage is advantage to MVC</li>
<li>Is there any advantage of using ViewModel in MVVM for Automated Unit
testing</li>
<li>We write more code in MVVM compared to MVC to perform similar tasks.
Then what is the advantage</li>
<li>When Should I need to opt for mvc instead of mvvm &amp; visversa</li>
</ul>
",https://stackoverflow.com/questions/56770241/why-to-use-mvvm-instead-of-mvc-in-android,"['android', 'mvvm', 'android-databinding']",3211,True,-3,1
Unit test singleton class method in android using PowerMock,"<p>I need to do unit testing of methods of Singleton class which internally uses RxJava Singles, and used PowerMock test framework to mock static class and methods. I tried various method to mock Schedulers.io() and AndroidSchedulers.mainThread() methods but it's not working. I'm getting <strong>java.lang.NullPointerException</strong> error at line                 <strong>.subscribeOn(Schedulers.io())</strong> inside <strong>UserApi.verifyUserData()</strong> method.</p>

<blockquote>
  <p>Singleton Class UserApi (Class under Test)</p>
</blockquote>

<pre><code>final public class UserApi {
    private CompositeDisposable compositeDisposable;
    private String userID; 
    //private final SchedulerProvider schedulerProvider;

    private UserApi(String userId) {
        super();
        this.userID = userId;
        //this.schedulerProvider = schedulerProvider;
    }

    public static UserApi getInstance() {
        return SingletonHolder.sINSTANCE;
    }

    private static final class SingletonHolder {
        private static final UserApi sINSTANCE;

        static {
            String uuid = UUID.randomUUID().toString();
            sINSTANCE = new UserApi(uuid);
        }
    }

    // Rest Api call

    public void verifyUserData(byte[] doc, byte[] img) {
        this.compositeDisposable = new CompositeDisposable();
        String docStr = Base64.encodeToString(doc, Base64.NO_WRAP);
        String imgStr = Base64.encodeToString(img, Base64.NO_WRAP);

        final Disposable apiDisposable = IdvManager.getInstance().getUserManager().verifyUserData(docStr, imgStr)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer&lt;JsonObject&gt;() {
                    @Override
                    public void accept(JsonObject verifyResponse) throws Exception {
                        pollResult();
                    }
                }, new Consumer&lt;Throwable&gt;() {
                    @Override
                    public void accept(Throwable error) throws Exception {
                      // handle error code...
                    }
                });
        this.compositeDisposable.add(apiDisposable);
    }

    private void pollResult() {
        // code here...
    }

}
</code></pre>

<blockquote>
  <p>UserManager Class and Interface</p>
</blockquote>

<pre><code>public interface UserManager {

    Single&lt;JsonObject&gt; verifyUserData(String docStr, String imgStr);

}

final class UserManagerImpl implements UserManager {

    private final UserService userService;

    UserManagerImpl(final Retrofit retrofit) {
        super();
        this.userService = retrofit.create(UserService.class);
    }
    @Override
    public Single&lt;JsonObject&gt; verifyUserData(String docStr, String imgStr) {
     // Code here...
    }
}
</code></pre>

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

<pre><code>@RunWith(PowerMockRunner.class)
@PrepareForTest({IdvManager.class, Base64.class, Schedulers.class, AndroidSchedulers.class, UserApi.class})
public class UserApiTest {

    @Mock
    public UserManager userManager;
    @Mock
    private Handler handler;

    private IdvManager idvManager;
    private Schedulers schedulers;

    private UserApi spyUserApi;
    private TestScheduler testScheduler;
    private String userID;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        testScheduler = new TestScheduler();
        handler = new Handler();
        PowerMockito.suppress(constructor(IdvManager.class));
        // mock static
        PowerMockito.mockStatic(IdvManager.class);
        PowerMockito.mockStatic(Schedulers.class);
        PowerMockito.mockStatic(AndroidSchedulers.class);
        PowerMockito.mockStatic(Base64.class);
        // Create mock for class
        idvManager = PowerMockito.mock(IdvManager.class);
        schedulers = PowerMockito.mock(Schedulers.class);
        PowerMockito.when(IdvManager.getInstance()).thenReturn(IdvManager);
        when(idvManager.getUserManager()).thenReturn(userManager);

        spyUserApi = PowerMockito.spy(UserApi.getInstance());
        // TestSchedulerProvider testSchedulerProvider = new TestSchedulerProvider(testScheduler);

        when(Base64.encodeToString((byte[]) any(), anyInt())).thenAnswer(new Answer&lt;Object&gt;() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                return java.util.Base64.getEncoder().encodeToString((byte[]) invocation.getArguments()[0]);
            }
        });

        when(schedulers.io()).thenReturn(testScheduler);
        when(AndroidSchedulers.mainThread()).thenReturn(testScheduler);
        userID = UUID.randomUUID().toString();
    }

    @After
    public void clearMocks() {
        //Mockito.framework().clearInlineMocks();
    }

    @Test
    public void verifyUserData_callsPollResult_returnsResponse() {
        // Input
        String docStr = ""iVBORw0KGgoAAAANSUhEUgAAAJ4AAACeCAYAAADDhbN7AA....."";
        // Output
        JsonObject verifyResponse = new JsonObject();
        verifyResponse.addProperty(""status"", ""Response created"");
        doReturn(Single.just(verifyResponse)).when(userManager).verifyUserData(docStr, docStr);
        // spy method call
        spyUserApi.verifyUserData(docFrontArr, docFrontArr);
        testScheduler.triggerActions();
        // assert
        verify(userManager).verifyUserData(docStr, docStr);

    }
}
</code></pre>

<blockquote>
  <p>Error</p>
</blockquote>

<pre><code>java.lang.NullPointerException
    at com.rahul.manager.UserApi.verifyUserData(UserApi.java:60)
    at com.rahul.manager.UserApiTest.verifyUserData_callsPollResult_returnsResponse(UserApiTest.java:171)
    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>I'm not sure whether i can test methods of Singleton class by spying on real instance of Singleton class using PowerMock.</p>
",https://stackoverflow.com/questions/58935432/unit-test-singleton-class-method-in-android-using-powermock,"['java', 'android', 'mockito', 'rx-java', 'powermock']",401,False,-1,2
How to check that the constructor in a class correctly sets the property in a new object,"<p>The question is as follows
""This test checks that the constructor in the Command class correctly sets the commandType property in the new object.""</p>

<p>im not sure how to set it up </p>

<p>Here is the code that I have that is failing. The first test works but the second we are told we do not have to use assert.throws so i tried using a strictequals but am not sure how to go about setting it up.</p>

<pre><code>const assert = require('assert');
const Command = require('../command.js');

describe(""Command class"", function() {

  it(""throws error if command type is NOT passed into constructor as the first parameter"", function() {
    assert.throws(
      function() {
        new Command();
      },
      {
        message: 'Command type required.'
      }
    );
  });

  it(""constructor should set command type"",function(){
    let contructorCheck = Command(commandtype, 7);
    assert.sctrictEqual(contructorCheck, ""commandtype"")
  });

});
</code></pre>

<p>and this is the class that i am unit testing</p>

<pre><code>class Command {
  constructor(commandType, value) {
    this.commandType = commandType;
    if (!commandType) {
      throw Error(""Command type required."");
    }
    this.value = value;
  }

}
</code></pre>
",https://stackoverflow.com/questions/58778432/how-to-check-that-the-constructor-in-a-class-correctly-sets-the-property-in-a-ne,"['javascript', 'unit-testing']",1538,False,0,1
Error &quot; Invariant violation : Element type is invalid: expected a string,"<p>I am new to Unit testing. I am trying to run a test but I keep getting the following error : </p>

<p>React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
I ran with { import Headers } and without {} and I keep getting the same error.</p>

<p>This is the current test. </p>

<pre><code> import React from 'react';
import { Headers } from './Headers';
import { configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
import  * as renderer from 'react-test-renderer';

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

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

let tree;
let baseProps;
let mockauthKeyValues;
let mockheaderKeyValues = {
    type: ""TEST1"",
    defaultData : ""test"",
};
let mockaddNewKeyValue;

 beforeEach(() =&gt; {
    baseProps = { // assing all of the props into MOCK
        authKeyValues: mockauthKeyValues,
       headerKeyValues: mockheaderKeyValues,
       addNewKeyValue: mockaddNewKeyValue
    }
})

 it ('should render without a authkeyvalues',() =&gt; {
baseProps = {
    ...baseProps,
    authKeyValues: {},
    };
    tree = renderer.create(&lt;Headers {...baseProps } /&gt;)
    let treeJson = tree.toJSON();
    expect(treeJson).toMatchSnapshot();
    tree.unmount()
});

 it ('should render without headerKeyValues',() =&gt; {
baseProps = {
    ...baseProps,
    headerKeyValues: {},
};
    tree = renderer.create(&lt;Headers {...baseProps } /&gt;)
    let treeJson = tree.toJSON();
    expect(treeJson).toMatchSnapshot();
    tree.unmount()
});

it ('should render without addNewKeyValue',() =&gt; {
baseProps = {
    ...baseProps,
    addNewKeyValue: {},
};
    tree = renderer.create(&lt;Headers {...baseProps } /&gt;)
    let treeJson = tree.toJSON();
    expect(treeJson).toMatchSnapshot();
    tree.unmount()
});


 it('should render with all of the props', () =&gt; {  
    tree = renderer.create(&lt;Headers {...baseProps} /&gt;)
    let treeJson = tree.toJSON()
    expect(treeJson).toMatchSnapshot();
    tree.unmount()
});
</code></pre>

<p>});</p>

<p>Headers.js</p>

<pre><code>import React, { PropTypes, Component } from 'react'
import KeyValue from '../Utils/KeyValuePair'
const shortid = require('shortid')

export class Headers extends Component {

componentDidMount () {
if (this.props.authKeyValues == null) {
  this.setState({
    useDefaultData: false
  })
} else {
  this.setState({
    useDefaultData: true
  })
}
}

generateKeyValues = () =&gt; {
 if (this.props.headerKeyValues == null) {
  return (
    &lt;KeyValue
      id={shortid.generate()}
      type='headers'
      addNewKeyValue={this.props.addNewKeyValue}
    /&gt;
  )
} else {
 let defaultKeyValues = Object.keys(this.props.headerKeyValues).map((headerKey, idx) =&gt; {
    return (
      &lt;KeyValue
        key={headerKey}
        id={headerKey}
        type={this.props.headerKeyValues[headerKey].type}
        addNewKeyValue={this.props.addNewKeyValue}
        defaultData={this.props.headerKeyValues[headerKey]}
      /&gt;
    )
  })
  defaultKeyValues.push(
    &lt;KeyValue
      id={shortid.generate()}
      type='headers'
      addNewKeyValue={this.props.addNewKeyValue}
    /&gt;
  )
  return defaultKeyValues
}
}

render () {
  return (
    &lt;div&gt;
      {this.generateKeyValues()}
    &lt;/div&gt;
    )
 }
}
</code></pre>

<p>I expected the test to pass by getting all the props called correct.</p>
",https://stackoverflow.com/questions/54095668/error-invariant-violation-element-type-is-invalid-expected-a-string,"['javascript', 'reactjs', 'unit-testing']",5570,False,0,1
How to create the only copy of &quot;object&quot; and test it,"<p>So I am writing a program for BT RFCOMM in linux in C. There can only be one socket connecting to bluetooth hardware, so I thought of having private File Descriptor to the socket. So initialising RFCOMM updates local source file variable:</p>

<p>source_file.c</p>

<pre><code>static int fd;

int rcomm_init()
{
    fd = socket();
}
</code></pre>

<p>so by doing this there can only be one connection to bluetooth socket. But I have no way of unit testing this.</p>

<p>I was wondering if anyone knows a better way of creating ""something"" that can only be one and able to test it?</p>
",https://stackoverflow.com/questions/55278926/how-to-create-the-only-copy-of-object-and-test-it,"['c', 'linux']",49,False,0,1
Test Javascript calls to api with jest,"<p>I am trying to test the call to <code>github</code> <code>api</code> using <code>jest</code> to see if the results are returned (the aim of this is to test my unit testing skills). But for some reasons, my code works fine but still fails my test. My suspicion is that i most likely don't understand how to write these kind of test. Below is my code</p>

<pre><code>const functions = {
    getUserRepo: async (username) =&gt; {
    const url = `https://api.github.com/users/${username}/repos`;
    console.log(url);
    let result = [];
    await axios.get(url)
        .then(function (response) {
            response.data.forEach(value =&gt; result.push(value.name));
            return result;
        })
        .catch(function (error) {
            return error;
        });
    }
}  
</code></pre>

<p>This code above returns the right results in an <code>array</code> format but fails the <code>test</code> below</p>

<pre><code>describe('Check repos from git api', () =&gt; {
test('Should return user repos', async () =&gt; {
    await functions.getUserRepo('whitehox')
        .then((response) =&gt; {
            expect(response.data).toEqual([ '57','decafreelance','decases','eexport','exportchat','flisch', 'gitprac', 'itravelcentral', 'pollark', 'portfolio', 'startereit', 'talkative', 'team-portfolio'])
        })
    });
});
</code></pre>

<p>Please what is the issue with this <code>test</code> and how do i fix it?</p>
",https://stackoverflow.com/questions/55603838/test-javascript-calls-to-api-with-jest,"['javascript', 'asynchronous', 'jestjs']",82,True,0,1
java.lang.IllegalStateException: Failed to load ApplicationContext error in Spring Boot,"<p>I am new to unit testing and I have to test my methods in spring boot.
I created application with Spring Security JWT Authentication + PostgreSQL – RestAPIs SpringBoot + Spring MVC + Spring JPA from <a href=""https://grokonez.com/spring-framework/spring-boot/spring-security-jwt-authentication-postgresql-restapis-springboot-spring-mvc-spring-jpa?fbclid=IwAR29x1W_t-iHWnJqCucOV7QpYMHuRGIKRc0xEeYNXIQh7JQdNcquju0vC80"" rel=""nofollow noreferrer"">this link</a>
then I created controller for users to edit update ect.
My users controller looks like this</p>

<pre><code>    @RestController
@RequestMapping(""/users"")
public class Users {



    @Autowired
    private UserService userService;


    @GetMapping(value = ""/*"")//can access with this root
    @PreAuthorize(""hasRole('ADMIN')"") //Only admin can view all users' details
    public List&lt;User&gt; AllUsers(){

        return this.userService.getAllUsers();
    }



    @GetMapping(value = ""/{username}"")//can access with this root
    public User GetOneUser(@PathVariable(value = ""username"") String username){

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String auth_name = auth.getName(); //get logged in username

        if(auth_name.equals(username)||this.userService.isAdmin(auth_name)){//admin and user can see the details
            return this.userService.getUser(username);
        }
        else{
            return null;
        }

    }



    @DeleteMapping(value = ""/{id}"")//can access with this root
    @PreAuthorize(""hasRole('ADMIN')"") //Only admin can delete user
    public void DeleteUser(@PathVariable(value = ""id"") Long id){

        this.userService.deleteUser(id);
    }




    @PostMapping(value = ""/{username}"")//can access with this root
    public User EditUser(@PathVariable(value = ""username"") String username,@RequestBody SignUpForm user) {//only user can edit

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      String auth_name = auth.getName(); //get logged in username
      User upUser=null;
       if(auth_name.equals(username)){
            upUser=this.userService.updateUser(username,user);


        }
       return upUser;

    }


}

</code></pre>

<p>then I created UserService like this:</p>

<pre><code>    @Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    PasswordEncoder encoder;


    public List&lt;User&gt; getAllUsers(){
        // return topics;
        List&lt;User&gt; users=new ArrayList&lt;&gt;();
        userRepository.findAll().forEach(users::add);
        return users;
    }

    public boolean isAdmin(String username){

        boolean flag=false;
        if(this.userRepository.existsByUsername(username)){
            User user=this.userRepository.findByUsername(username).get();
            Role adminRole = roleRepository.findByName(RoleName.ROLE_ADMIN)
                    .orElseThrow(() -&gt; new RuntimeException(""Fail! -&gt; Cause: User Role not find.""));
            if(user.getId().equals(adminRole.getId())){
                flag=true;
            }
        }
        return flag;

    }

    public User getUser(String username){


        return userRepository.findByUsername(username).orElse(null);
    }



    public User updateUser(String username, SignUpForm user) {

        if(userRepository.existsByUsername(username)) {
            User ExistingUser=userRepository.findByUsername(username).get();
            if(ExistingUser.getName()!=user.getName()){
                ExistingUser.setName(user.getName());
            }
            if(ExistingUser.getUsername()!=user.getUsername()){
                ExistingUser.setUsername(user.getUsername());
            }
            if(ExistingUser.getPassword()!=user.getPassword()){
                ExistingUser.setPassword(encoder.encode(user.getPassword()));
            }

            if(ExistingUser.getEmail()!=user.getEmail()){
                ExistingUser.setEmail(user.getEmail());
            }



            Set&lt;String&gt; Roles =user.getRole();
            Set&lt;Role&gt; roles = new HashSet&lt;&gt;();

            Roles.forEach(role -&gt; {
                switch(role) {
                    case ""admin"":
                        Role adminRole = roleRepository.findByName(RoleName.ROLE_ADMIN)
                                .orElseThrow(() -&gt; new RuntimeException(""Fail! -&gt; Cause: User Role not find.""));
                        roles.add(adminRole);

                        break;
                    case ""pm"":
                        Role pmRole = roleRepository.findByName(RoleName.ROLE_PM)
                                .orElseThrow(() -&gt; new RuntimeException(""Fail! -&gt; Cause: User Role not find.""));
                        roles.add(pmRole);

                        break;
                    default:
                        Role userRole = roleRepository.findByName(RoleName.ROLE_USER)
                                .orElseThrow(() -&gt; new RuntimeException(""Fail! -&gt; Cause: User Role not find.""));
                        roles.add(userRole);
                }
            });

            if(ExistingUser.getRoles()!=roles){
                ExistingUser.setRoles(roles);
            }


              userRepository.save(ExistingUser);

            }

          return userRepository.findByUsername(user.getUsername()).get();

        }






        public void deleteUser(Long id) {

        userRepository.deleteById(id);
    }
}
</code></pre>

<p>it works.</p>

<p>But then I created class for testing that tests getUser() method from UserService</p>

<pre><code>
    @WebMvcTest
@RunWith(SpringRunner.class)
public class UserServiceTest {


    @MockBean
    UserRepository repository;

   @Autowired
   UserService userService;



    @Test
    public void getUserTest(){
        User user=this.userService.getUser(""arife"");

        assertThat(user).isNotNull();


}

}
</code></pre>

<p>But it gives me error that looks like this:</p>

<pre><code>
    java.lang.IllegalStateException: Failed to load ApplicationContext

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.postProcessFields(MockitoTestExecutionListener.java:95)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.injectFields(MockitoTestExecutionListener.java:79)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:54)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    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$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authRestAPIs': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'springbootjwtauthenticationpostgresql.springbootjwtauthenticationpostgresql.security.services.UserDetailsServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:598)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:376)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:847)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
    ... 25 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'springbootjwtauthenticationpostgresql.springbootjwtauthenticationpostgresql.security.services.UserDetailsServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:598)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:376)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:392)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1255)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1175)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:595)
    ... 43 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'springbootjwtauthenticationpostgresql.springbootjwtauthenticationpostgresql.security.services.UserDetailsServiceImpl' 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)
    ... 65 more
</code></pre>

<p>Please can someone help me?</p>
",https://stackoverflow.com/questions/58538842/java-lang-illegalstateexception-failed-to-load-applicationcontext-error-in-spri,"['postgresql', 'spring-boot', 'spring-mvc', 'jpa', 'jwt']",1012,True,0,2
Can I use Jacoco to check code coverage of an executable file .exe in the same way it does this with Jars?,"<p>I am attempting to create a test execution framework to run integration tests on a java application and was wondering how I would go about generating a code coverage report based off of the applications executabe file the test runner is using to start the application and only this. Is it possible to do this like it is done with unit testing within the applications project? </p>

<p>I've tried adding the jacoco agent as a VM option</p>

<pre><code>-javaagent:(filepath)jacocoagent.jar=destfile=(filepath)jacoco.exec,includes=com.*,append=true
</code></pre>

<p>in IntelliJ however the .exec its producing is 0 bytes in size after task execution is finished.</p>
",https://stackoverflow.com/questions/57991200/can-i-use-jacoco-to-check-code-coverage-of-an-executable-file-exe-in-the-same-w,"['java', 'integration-testing', 'jacoco']",172,False,2,0
Unable to mock RestTemplate in SpringBoot-Junit5-Mockito,"<p>I'm trying to mock a rest template in my DAO class but Mockito throws weird error saying it isn't able to mock.</p>

<p>Trying to cover unit test cases for my Spring boot app version 2.x. I have almost tried all possible solutions over the internet like updating JDK/JRE for compilation but I'm stuck with the following error:</p>

<pre><code>org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class org.springframework.web.client.RestTemplate.

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               : 1.8
JVM vendor name    : Oracle Corporation
JVM vendor version : 25.181-b13
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 1.8.0_181-b13
JVM info           : mixed mode
OS name            : Windows 10
OS version         : 10.0


Underlying exception : java.lang.IllegalArgumentException: Could not create type
    at org.mockito.junit.jupiter.MockitoExtension.beforeEach(MockitoExtension.java:115)
....
</code></pre>

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

<p>build.gradle</p>

<pre><code>dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-data-rest'
    implementation 'org.springframework.retry:spring-retry'
    implementation 'org.aspectj:aspectjrt'
    implementation 'org.aspectj:aspectjweaver'
    implementation 'org.springframework:spring-aop'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.2.0'
    testCompile 'org.junit.jupiter:junit-jupiter-params:5.2.0'
    testRuntime 'org.junit.jupiter:junit-jupiter-engine:5.2.0'
    testImplementation 'org.mockito:mockito-core:2.+'
    testImplementation 'org.mockito:mockito-junit-jupiter:2.18.3'
}

test {
    testLogging.showStandardStreams = true
    useJUnitPlatform()
}
</code></pre>

<p>MyDao.java</p>

<pre><code>@Repository
public class MyDao {    
    @Value(""${app.prop.service.url}"")
    private String url;

    @Autowired
    public RestTemplate restTemplate;

    public String getSignals() {
        System.out.println(""url -----------------------&gt; "" + url);
        return new RetryTemplate().execute(context -&gt; {
            ResponseEntity&lt;String&gt; response = restTemplate.getForEntity(url, String.class);

            if (response.getStatusCodeValue() == 200) {
                System.out.println(""Server response -&gt; "" + response.getBody());
                return response.getBody();
            } else {
                throw new RuntimeException(""server response status: "" + response.getStatusCode());
            }
        }, context -&gt; {
            System.out.println(""retry count: "" + context.getRetryCount());
            System.err.println(""error -&gt; "" + context.getLastThrowable());
            return null;
        });
    }
}
</code></pre>

<p>MyDaoTest.java</p>

<pre><code>@ExtendWith(MockitoExtension.class)
public class MyDaoTest {    
    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    private MyDao dao;

    @BeforeEach
    public void prepare() {
        ResponseEntity&lt;String&gt; response = new ResponseEntity&lt;&gt;(""{name: myname}"", HttpStatus.OK);
        Mockito.doReturn(response).when(restTemplate.getForEntity(Mockito.anyString(), String.class));
    }

    @Test
    public void testGetSignals() {
        System.out.println(""------------------TEST-------------------"");
        String result = dao.getSignals();
        System.out.println(""result ------&gt;"" + result);
        assertEquals(""{name: myname}"", result);
    }
}
</code></pre>

<p>BeanConfig for RestTemplate</p>

<pre><code>@Bean
public RestTemplate restTemplate() {
    // block of code for SSL config for HTTPS connection
    return new RestTemplate();
}
</code></pre>

<p>Any suggestions will be really helpful</p>

<p>P.S: The application is running perfectly fine through gradle command </p>

<pre><code>gradlew bootRun
</code></pre>

<p>The problem is only with unit testing</p>

<pre><code>gradlew test
</code></pre>
",https://stackoverflow.com/questions/54579940/unable-to-mock-resttemplate-in-springboot-junit5-mockito,"['java', 'spring-boot', 'mockito', 'resttemplate', 'junit5']",5762,True,2,3
Cloud Firestore Unit Testing Java,"<p>I am creating a REST API in Spring Boot and I am stuck with unit testing my service, which makes calls to my firestore database. I am trying to mock my Firestore database so I don't add unnecessary data to my firestore database as part of my tests. However, when I try to stub responses on the mocked Firestore object, I am getting a Null Pointer Exception. I am using JUnit 5 and mocking the Firestore class by</p>

<pre><code>@Mock
private Firestore db;

@InjectMocks
private ProductsService productsService;
</code></pre>

<p>In my test, I am stubbing a response from a method of the Firestore object by</p>

<pre><code>// Getting a null pointer exception here
when(db.collection(""products"").add(productToCreate).get()).thenReturn(any(DocumentReference.class));
</code></pre>
",https://stackoverflow.com/questions/58713663/cloud-firestore-unit-testing-java,"['java', 'spring-boot', 'google-cloud-firestore', 'mockito', 'junit5']",2142,True,2,2
How to create fake Realm results for unit tests,"<p>Maybe a duplicate, however; the accepted answer did not answer my question:
<a href=""https://stackoverflow.com/questions/38902475/how-to-fake-realm-results-for-tests"">How to fake Realm Results for tests</a></p>

<p>I want to return a fake Realm 'Results' object on my mocked object when unit testing my View Controller. (<a href=""https://pauldevenney.blogspot.com/2014/09/how-to-setup-async-and-task-return.html"" rel=""nofollow noreferrer"">Similar to how it can be done with Moq in C#</a>) </p>

<p>Is it possible to create a Realm Results object consisting of my test data without creating an In-Memory Realm database, adding the required data into it &amp; then querying it for the objects? </p>

<p>Mock Object:</p>

<pre><code>class MockRealmRepository: RealmRepository {

    override init() {}

    var getAccountRolesCallCount = 0
    var getAccountRolesReturnValue: Results&lt;AccountRole&gt;!


    override func getAccountRoles() -&gt; Results&lt;AccountRole&gt; {
        getAccountRolesCallCount += 1
        return getAccountRolesReturnValue
    }
}
</code></pre>

<p>Unit Test implementation of Mock:</p>

<pre><code>    class CreateProfileViewControllerTests: XCTestCase {

        private var mockRealmRepository: MockRealmRepository!

        override func setUp() {
            super.setUp()

            mockRealmRepository = MockRealmRepository()
        }

        func testCheckUsersRole_Valid() {

            let admin = AccountRole(role: ""Admin"")
            let user = AccountRole(role: ""User"")
            let guest = AccountRole(role: ""Guest"")

            // Create a Results&lt;AccountRole&gt;() containing the above AccountRole objects

            mockRealmRepository.getAccountRolesReturnValue = // Assign my Results&lt;AccountRole&gt; object here

        }
    }
</code></pre>
",https://stackoverflow.com/questions/57342146/how-to-create-fake-realm-results-for-unit-tests,"['ios', 'swift', 'xcode', 'realm']",1717,True,2,1
Setting up Mock repository with Moq,"<p>I am unit testing controller logic with xUnit and Moq.  I am trying to use a Mock repository object which will enable the test case to pass.  However, in my setup it caused the test to fail because the Mock repository returns <code>null</code> instead of a <code>TweetDay</code> object.</p>

<p>I am testing the TweetsController:</p>

<pre><code>public class TweetsController : ControllerBase
{
    private readonly ITweetDayRepository _tweetDayRepository;

    public TweetsController(ITweetDayRepository tweetDayRepository)
    {
        //Implementation here
    }

    public async Task&lt;IActionResult&gt; GetTweetDay()
    {
            var tweet = await _tweetDayRepository.GetTweetOfTheDayAsync(_systemClock.GetToday);

            if (tweet == null)
            {
                _logger.LogError(LoggingEvents.GetItemNotFound, ""An error occurred getting tweet with date: {Date}"", _systemClock.GetToday);
                return BadRequest();
            }

            return Ok(tweet);
        }
        catch (Exception ex)
        {
            _logger.LogError(LoggingEvents.GetItemNotFound, ex, ""An error occurred getting tweet with date: {Date}"", _systemClock.GetToday);
            return BadRequest();
        }
    }
}
</code></pre>

<p>Below is my test case:</p>

<pre><code>public class TweetsControllerTests
{
    private Mock&lt;IMemoryCache&gt; _cache;
    private readonly Mock&lt;IMapper&gt; _mapper;
    private readonly Mock&lt;ILogger&lt;TweetsController&gt;&gt; _logger;
    private readonly Mock&lt;ISystemClockService&gt; _systemClock;
    //private readonly ITweetDayRepository _tweetDayRepository;

    public TweetsControllerTests()
    {
        _cache = new Mock&lt;IMemoryCache&gt;();
        _mapper = new Mock&lt;IMapper&gt;();
        _systemClock = new Mock&lt;ISystemClockService&gt;();
        _logger = new Mock&lt;ILogger&lt;TweetsController&gt;&gt;();
    }

    [Fact]
    public async Task GetTweetDay_ReturnsOkResult_WithATweetObject()
    {
        // Arrange
        var mockRepo = new Mock&lt;ITweetDayRepository&gt;();
        mockRepo.Setup(repo =&gt; repo.GetTweetOfTheDayAsync(DateTime.Today))
            .ReturnsAsync(GetTestTweet());

        var controller = new TweetsController(mockRepo.Object, _cache.Object, _logger.Object,
                                                 _systemClock.Object, _mapper.Object);

        // Act
        var result = await controller.GetTweetDay();

        // Assert
        var okResult = Assert.IsType&lt;OkResult&gt;(result);
    }

    private TweetDay GetTestTweet()
    {
        var tweet = new TweetDay()
        {
            Bird = new Bird(),
            BirdId = 0,
            CreationDate = new DateTime(2016, 7, 2),
            DisplayDay = new DateTime(2016, 7, 2),
            LastUpdateDate = new DateTime(2016, 7, 2),
            TweetDayId = 0
        };

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

<p>Under my setup, I expect the Mock repository to return the TweetDay object intialised in</p>

<pre><code>mockRepo.Setup(repo =&gt; repo.GetTweetOfTheDayAsync(DateTime.Today))
    .ReturnsAsync(GetTestTweet());
</code></pre>

<p>I cannot isolate the exact source of the problem.  </p>

<p>Am I setting up the Mock repository properly?  Or is the problem elsewhere?</p>
",https://stackoverflow.com/questions/57346655/setting-up-mock-repository-with-moq,"['c#', 'unit-testing', 'asp.net-core', 'moq', 'xunit']",7601,True,2,1
How to launch a Docker container in Gitlab CI/CD,"<p>I'm new to Gitlab (and I only know the basic features of git : pull, push, merge, branch...).</p>

<p>I'm using a local DynamoDB database launched with <code>docker run -p 8000:8000 amazon/dynamodb-local</code> to do unit testing on my Python project. So I have to launch this docker container in the Gitlab CI/CD so that my unit tests work. </p>

<p>I already read the documentation on this subject on the site of gitlab without finding an answer to my problem and I know that I have to modify my <code>gitlab-ci.yml</code> file in order to launch the docker container.</p>
",https://stackoverflow.com/questions/57791094/how-to-launch-a-docker-container-in-gitlab-ci-cd,"['amazon-web-services', 'docker', 'gitlab', 'amazon-dynamodb']",302,True,2,1
Jest complains Cannot find module when using Yarn Link,"<p>So I have a components library that a repo uses to import its UI components. When I <code>yarn link</code> the library, every change works with the repo except for unit-testing with <code>jest</code></p>

<p>For some reason <code>jest</code> is not ""smart enough"" to detect package being <code>yarn linked</code> and therefore the tests fails. </p>

<p>The output of the errors is <code>Cannot find module '....' from '...'</code> </p>

<p>A workaround is doing a pre-release publish of the <code>components library</code> but that is <strong>NOT</strong> the solution and doesn't tackle the problem itself. I work at a company so ""hacky"" solutions will not be accepted. </p>

<p>Did anyone came across this problem and have a way to solve this? </p>
",https://stackoverflow.com/questions/55601239/jest-complains-cannot-find-module-when-using-yarn-link,"['javascript', 'reactjs', 'testing', 'jestjs', 'yarnpkg']",369,False,7,0
Correct structure of implementing MVVM LiveData RxJava Dagger Databinding?,"<p><strong>MainActivity</strong></p>

<pre><code>class MainActivity : AppCompatActivity() {
    @Inject
    lateinit var mainViewModelFactory: mainViewModelFactory
    private lateinit var mainActivityBinding: ActivityMainBinding
    private lateinit var mainViewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainActivityBinding = DataBindingUtil.setContentView(
                this,
                R.layout.activity_main
        )

        mainActivityBinding.rvmainRepos.adapter = mainAdapter
        AndroidInjection.inject(this)
        mainViewModel =
                ViewModelProviders.of(
                        this@MainActivity,
                        mainViewModelFactory
                )[mainViewModel::class.java]
        mainActivityBinding.viewmodel = mainViewModel
        mainActivityBinding.lifecycleOwner = this
        mainViewModel.mainRepoReponse.observe(this, Observer&lt;Response&gt; {
            repoList.clear()
            it.success?.let { response -&gt;
                if (!response.isEmpty()) {
                    //     mainViewModel.saveDataToDb(response)
                    //     mainViewModel.createWorkerForClearingDb()
                }
            }
        })
    }
}
</code></pre>

<p><strong>MainViewModelFactory</strong></p>

<pre><code>class MainViewModelFactory @Inject constructor(
        val mainRepository: mainRepository
) : ViewModelProvider.NewInstanceFactory() {

    override fun &lt;T : ViewModel?&gt; create(modelClass: Class&lt;T&gt;) =
            with(modelClass) {
                when {
                    isAssignableFrom(mainViewModel::class.java) -&gt; mainViewModel(
                            mainRepository = mainRepository
                    )
                    else -&gt; throw IllegalArgumentException(""Unknown ViewModel class: ${modelClass.name}"")
                }
            } as T
}
</code></pre>

<p><strong>MainViewModel</strong></p>

<pre><code>class MainViewModel(
        val mainRepository: mainRepository
) : ViewModel() {

    private val compositeDisposable = CompositeDisposable()
    val mainRepoReponse = MutableLiveData&lt;Response&gt;()
    val loadingProgress: MutableLiveData&lt;Boolean&gt; = MutableLiveData()
    val _loadingProgress: LiveData&lt;Boolean&gt; = loadingProgress
    val loadingFailed: MutableLiveData&lt;Boolean&gt; = MutableLiveData()
    val _loadingFailed: LiveData&lt;Boolean&gt; = loadingFailed
    var isConnected: Boolean = false

    fun fetchmainRepos() {
        if (isConnected) {
            loadingProgress.value = true
            compositeDisposable.add(
                    mainRepository.getmainRepos().subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe({ response -&gt;
                                run {
                                    saveDataToDb(response)
                                    )
                                }
                            },
                                    { error -&gt;
                                        processResponse(Response(AppConstants.Status.SUCCESS, null, error))
                                    }
                            )
            )
        } else {
            fetchFromLocal()
        }
    }

    private fun saveDataToDb(response: List&lt;mainRepo&gt;) {
        mainRepository.insertmainUsers(response)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(object : DisposableCompletableObserver() {
                    override fun onComplete() {
                        Log.d(""Status"", ""Save Success"")
                    }

                    override fun onError(e: Throwable) {
                        Log.d(""Status"", ""error ${e.localizedMessage}"")
                    }
                })
    }
}
</code></pre>

<p><strong>MainRepository</strong></p>

<pre><code>interface MainRepository {

    fun getmainRepos(): Single&lt;List&lt;mainRepo&gt;&gt;

    fun getAllLocalRecords(): Single&lt;List&lt;mainRepo&gt;&gt;

    fun insertmainUsers(repoList: List&lt;mainRepo&gt;): Completable
}
</code></pre>

<p><strong>MainRepositoryImpl</strong></p>

<pre><code>class mainRepositoryImpl @Inject constructor(
        val apiService: GitHubApi,
        val mainDao: AppDao
) : MainRepository {

    override fun getAllLocalRecords(): Single&lt;List&lt;mainRepo&gt;&gt; = mainDao.getAllRepos()

    override fun insertmainUsers(repoList: List&lt;mainRepo&gt;) :Completable{
        return   mainDao.insertAllRepos(repoList)
    }

    override fun getmainRepos(): Single&lt;List&lt;mainRepo&gt;&gt; {
        return apiService.getmainGits()
    }
}
</code></pre>

<p>I'm quite confused with the implementation of MVVM with LiveData and Rxjava, in my MainViewModel I am calling the interface method and implementing it inside ViewModel, also on the response I'm saving the response to db. However, that is a private method, which won't be testable in unit testing in a proper way (because it's private). What is the best practice to call other methods on the completion of one method or i have to implement all the methods inside the implementation class which uses the interface.</p>
",https://stackoverflow.com/questions/58109723/correct-structure-of-implementing-mvvm-livedata-rxjava-dagger-databinding,"['android', 'data-binding', 'rx-java2', 'android-livedata', 'dagger']",257,False,1,1
Need help differentiating between mocks and test drivers,"<p>I'm confused to say the least. I might be getting Mocks wrong, Test Drivers wrong or maybe both. </p>

<p>My understanding of Mocks is that it's a way of imitating units, to avoid depending on specific parts of your system when testing. </p>

<p>My understanding of Test Drivers is that it's specifically used for Bottom-up integration testing, to imitate High Level Modules, which haven't been implemented yet. </p>

<p>To me that makes Test Drivers sound like a type of Mock, but are Mocks specifically a unit testing thing? </p>

<p>What's the difference between the two?</p>
",https://stackoverflow.com/questions/56254037/need-help-differentiating-between-mocks-and-test-drivers,"['unit-testing', 'testing', 'mocking', 'integration-testing']",358,True,1,1
"Android Robolectric: OutOfMemoryError - GC overhead limit exceeded, when Creating ArrayList","<p>I want to create a test for a method that returns an <code>ArrayList</code>. The <code>ArrayList</code> type is a custom object called <code>DateItem</code>. But when I try to create the <code>ArrayList</code> in my test code (which is placed in <code>test</code> folder), the test failed with the following message: </p>

<pre><code>java.lang.OutOfMemoryError: GC overhead limit exceeded

Process finished with exit code 255
</code></pre>

<p>Here's my code:</p>

<pre><code>var expectedDateItems: ArrayList&lt;DateItem&gt; = ArrayList()
val currentDate = date1Start
while (currentDate.isBefore(date1End)) {
    val dateItem = DateItem(currentDate, ArrayList())
    expectedDateItems.add(dateItem)
    currentDate.plusDays(1)
}
</code></pre>

<p>I am wondering how to create such ArrayList in my test code. I've looked into <a href=""https://stackoverflow.com/a/36131976/8434188"">this answer</a> but it is for the whole app, not only for testing purposes. How to allocate more memory for unit testing?</p>

<p>EDIT: After debugging, the code failed when in this line: <code>val dateItem = DateItem(currentDate, ArrayList())</code>.</p>
",https://stackoverflow.com/questions/54712462/android-robolectric-outofmemoryerror-gc-overhead-limit-exceeded-when-creatin,"['android', 'arraylist', 'kotlin', 'garbage-collection', 'robolectric']",406,True,1,1
How to mock method in the same class that returns an Iterator in java,"<p>I am trying to unit test a method <code>getFruitItemMap()</code> which calls another method <code>getAllItemsBelongingToFruit</code> whose return type is <code>Iterator</code> in the same class. I am trying to mock this method using <code>Mockito.spy()</code>, but unsure of how to return an Iterator. I checked other answers on <a href=""https://stackoverflow.com/questions/23958611/how-to-mock-another-method-in-the-same-class-which-is-being-tested"">stack overflow here</a>, but looks like I am missing something here.</p>

<pre><code>class FruitItemImpl {

Map&lt;String, Fruit&gt; getFruitItemMap() {
        Map&lt;String, Fruit&gt; fruitMap = new HashMap&lt;&gt;();
        Iterator&lt;Fruit&gt; items = getAllItemsBelongingToFruit(""Apple"");

while (items.hasNext()) {
            Fruit fruitItem = items.next();
            fruitMap.put(fruitItem.getID(), fruitItem);
        }
        return fruitMap;
    }

public Iterator&lt;Fruit&gt; getAllItemsBelongingToFruit(String fruit) {
      //some logic that returns an iterator
}
</code></pre>

<p>Here is the unit test:</p>

<pre><code>    @Test
    public void testGetFruitItemMap() {
        Map&lt;String, Fruit&gt; fruitItemMap = new HashMap&lt;&gt;();
        FruitItemImpl doa1 = Mockito.spy(dao);
   Mockito.doReturn(**new Iterator&lt;Fruit&gt;**).when(doa1).getAllItemsBelongingToFruit(""Apple"") //Here
        Assert.assertEquals(fruitItemMap.size(), doa1.getFruitItemMap().size());
    }
</code></pre>

<p>Since I am new to Mockito and Unit Testing world, trying to get my head around it. I am not sure how to make mockito return an iterator <code>Mockito.doReturn()</code> in this case.</p>
",https://stackoverflow.com/questions/55371743/how-to-mock-method-in-the-same-class-that-returns-an-iterator-in-java,"['java', 'unit-testing', 'mocking', 'mockito']",358,True,1,1
Problem runing Angular Test In Azure DevOps Pipeline,"<p>I have a project with angular 7.2, in that project I create 3 angular libraries and cofigure my unit testing with jasmin-karma. I run all test one by none. In my local environment everything is executing fine, but when I trying to run in azure devops pipeline test not working. It show me an error like this "" <strong>Chrome 75.0.3770 (Windows 10.0.0) ERROR
  Disconnectedreconnect failed before timeout of 2000ms (ping timeout)</strong> "". Does anyone have an idea about what this is happen?. Thank you all anyway.</p>

<p>This is my karma config file for every library</p>

<pre><code>// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-phantomjs-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma'),
      require('karma-junit-reporter'),
    ],
    files:[""../../node_modules/jquery/dist/jquery.min.js"",
    ""../../node_modules/jquery-migrate/dist/jquery-migrate.min.js"",
    ""../../node_modules/lodash/lodash.min.js"",
    ""../../node_modules/moment/min/moment.min.js"",
    ""../../node_modules/app-resources/bits/Framework/scripts/app.js"",],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in 
      browser
    },
   coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../../coverage'),
      reports: ['html', 'lcov', 'cobertura'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml', 'junit'/* 'sonarqube' */],
    sonarqubeReporter: {
      basePath: 'src/lib', // test files folder
      filePattern: '**/*spec.ts', // test files glob pattern
      encoding: 'utf-8', // test files encoding
      outputFolder: 'reports', // report destination
      legacyMode: false, // report for Sonarqube &lt; 6.2 (disabled)
      reportName: (metadata) =&gt; { // report name callback
        /**
         * Report metadata array:
         * - metadata[0] = browser name
         * - metadata[1] = browser version
         * - metadata[2] = plataform name
         * - metadata[3] = plataform version
         */
        metadata[4] = 'lib';
        return metadata.concat('xml').join('.');
      }
    },
    junitReporter: {
      outputDir: '../../reports', // results will be saved as 
   $outputDir/$browserName.xml
    outputFile: undefined, // if included, results will be saved as 
   $outputDir/$browserName/$outputFile
   suite: '', // suite will become the package name attribute in xml 
   testsuite element
    useBrowserName: true, // add browser name to report and classes names
   nameFormatter: undefined, // function (browser, result) to customize the 
    name attribute in xml testcase element
   classNameFormatter: undefined, // function (browser, result) to customize 
   the classname attribute in xml testcase element
   properties: {} // key value pair of properties to add to the &lt;properties&gt; 
  section of the report
  },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome', ],
    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 3,
    browserNoActivityTimeout: 60000,
    flags: [
      '--disable-web-security',
      '--disable-gpu',
      '--no-sandbox'
    ],
    singleRun: true,
  });
};
</code></pre>
",https://stackoverflow.com/questions/56590671/problem-runing-angular-test-in-azure-devops-pipeline,"['azure-devops', 'karma-jasmine', 'karma-runner', 'angular7']",2087,False,1,1
Mockito ElasticSearch Unit test in Spring Boot,"<p>I am trying to use Mockito in Spring Boot in order to write a Unit Test that ""imitates"" a call to my ElasticSearch instance. Now since in Unit Testing you are not supposed to bother external resources, and thus using Mockito, I have my ElasticSearch instance stopped. The problem is that my UnitTest keeps trying to connect to my ElasticSearch instance so it fails by saying ""Connection refused"". Here is my test: </p>

<pre><code>import com.google.common.net.HttpHeaders;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.Base64Utils;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ElasticSearchConnectionTest {

@Autowired
private MockMvc mvc;

@Value(""${elasticsearch.user}"")
private String user;

@Value(""${elasticsearch.password}"")
private String password;

private String myjson = ""{ \""order\"": \n"" + ""{ \n"" + ""\""id\"":\""dbId\"",\n"" + ""\""status\"":\""completed\"",\n"" + ""} \n"" + ""}"";

@Test
public void contextLoads() throws Exception {

    this.mvc.perform(post(""/order"")
            .contentType(MediaType.APPLICATION_JSON)
            .content(myjson)
            .header(HttpHeaders.AUTHORIZATION, ""Basic "" +Base64Utils.encodeToString((user+"":""+password).getBytes())))
            .andExpect(status().is2xxSuccessful());
  }
}
</code></pre>

<p>The error message says: <code>java.net.ConnectException: Connection refused</code></p>

<p>I am using using <a href=""https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-low.html"" rel=""nofollow noreferrer"">Java Low Level Rest Client</a> for calling calls to ElasticSearch</p>
",https://stackoverflow.com/questions/56492178/mockito-elasticsearch-unit-test-in-spring-boot,"['spring-boot', 'elasticsearch', 'mockito']",2561,False,1,2
Mockito for EntityManager persist method call failed,"<p>I have code which uses <code>persist()</code> method of EntityManager. I am using SpringBoot with Mockito for my unit testing.</p>

<p><strong>Source.java</strong></p>

<pre><code>public class Operation {

    @PersistenceContext
    EntityManager entityManager;

    public addOperation(List&lt;Operation&gt; operationList) {
        for(Operation operation : operationList) {
            entityManager.persist(operation);
        }
    }
}
</code></pre>

<p><strong>Test.java</strong></p>

<pre><code>@SpringBootTest
@RunWith(SpringRunner.class)
public class OperationTest {

    @Mock
    EntityManager entityManager;

    @InjectMocks
    @Resource
    Operation sut;

    List&lt;Operation&gt; operationList;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        List&lt;Operation&gt; operationList = new ArrayList&lt;&gt;();
        Operation operation1 = new Operation();
        Operation operation2 = new Operation();

        // Add operations to the list 
        operationList.add(operation1);
        operationList.add(operation2);
    }

    @Test
    public void  importFileSuccessful() {

        doNothing().when(entityManager).persist(any(Operation.class));
        sut.addOperation(operationList);
    }
}
</code></pre>

<p><strong>Issue :</strong></p>

<p>When I run the test code, it is successfully passed. However, instead of mocking <code>persist()</code> method of EntityManager, my code is adding the data to the real database.</p>

<p><strong>Questions :</strong></p>

<ol>
<li><p>Do I need any special code to handle the entityManager annotated with @persistenceContext in source code?</p></li>
<li><p>What am I missing in the mocking for test class so that actual persist method is not called and mock is called?</p></li>
</ol>

<p>Any help would be appreciated.</p>
",https://stackoverflow.com/questions/57486183/mockito-for-entitymanager-persist-method-call-failed,"['java', 'unit-testing', 'spring-boot', 'junit', 'mockito']",934,False,1,0
Testing StyleSheet using react-native-testing-library,"<p>In our react-native application, we are developing custom style component for our component.</p>

<p>The style component contains StyleSheet 
example:</p>

<pre><code>export default StyleSheet.create({
  container: {
    flexGrow: 1,
    justifyContent: ""center"",
    alignItems: ""center"",
    borderTopWidth: 1,
  },
});
</code></pre>

<p>As this component is imported in our component and when we do unit testing of our component it goes 30 times in it and shows that if and else part were not run which leads to less coverage(style component is imported in the component)</p>

<p>So I have included a  <a href=""https://i.stack.imgur.com/IdUPJ.png"" rel=""nofollow noreferrer"">screenshot</a>  which explains the issue. Note that rest whole component is tested and fully covered. So the coverage which is left is for style component.</p>
",https://stackoverflow.com/questions/59302262/testing-stylesheet-using-react-native-testing-library,"['reactjs', 'react-native', 'react-testing-library', 'react-native-testing-library']",282,False,1,1
Getting a sun.reflect.annotation.TypeNotPresentExceptionProxy exception when trying to set up a spring boot rest test,"<p>I'm currently trying to make a unit test for a small project I'm doing. It's a contact management application which only passes rest apis, also implement login api. I've been reading this guide (<a href=""https://reflectoring.io/spring-boot-web-controller-test/"" rel=""nofollow noreferrer"">https://reflectoring.io/spring-boot-web-controller-test/</a>) on how to do it implement unit testing in rest, but I'm getting an exception when I implement the guide in my project. I'd love to get some pointers on how to solve this.</p>
<h1>ContactControllerTest</h1>
<pre class=""lang-java prettyprint-override""><code>@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = ContactController.class)
public class ContactControllerTest {

    @Autowired
    private MockMvc mvc;

    @Autowired
    private ObjectMapper objectMapper;

    @MockBean
    private ContactService contactService;

    @Test
    public void createAccount() throws Exception {
        String uri = &quot;/contacts/add&quot;;
        Contact contact = new Contact();
        contact.setFirst_name(&quot;George&quot;);
        contact.setLast_name(&quot;George2&quot;);
        contact.setMobile((long) 12345443);

        ObjectMapper objectMapper = new ObjectMapper();
        String inputJson = objectMapper.writeValueAsString(contact);

        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(inputJson)).andReturn();
        int status = mvcResult.getResponse().getStatus();
        assertEquals(200, status);
        String content = mvcResult.getResponse().getContentAsString();
        assertEquals(content, &quot;Contact is created successfully&quot;);
    }

}
</code></pre>
<h1>ContactController</h1>
<pre class=""lang-java prettyprint-override""><code>@RestController
public class ContactController {

    @Autowired
    private ContactService contactService;

    // ADD
    @PreAuthorize(&quot;hasRole('USER') or hasRole('ADMIN')&quot;)
    @RequestMapping(value = &quot;/contacts/add&quot;, method = POST)
    public Contact addContact(@RequestBody Contact contact){
        if (!contactService.checkContact(contact)){
           // throw new ContactBadRequestException(&quot;Bad contact request&quot;);
        }
        return contactService.createContact(contact);
    }
}
</code></pre>
<h1>ContactService</h1>
<pre class=""lang-java prettyprint-override""><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;36&lt;/groupId&gt;
    &lt;artifactId&gt;36&lt;/artifactId&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
                &lt;configuration&gt;
                    &lt;source&gt;8&lt;/source&gt;
                    &lt;target&gt;8&lt;/target&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;

    &lt;packaging&gt;war&lt;/packaging&gt;

    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;1.3.3.RELEASE&lt;/version&gt;
        &lt;relativePath /&gt;
    &lt;/parent&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
            &lt;artifactId&gt;spring-security-web&lt;/artifactId&gt;
            &lt;version&gt;4.0.4.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
            &lt;artifactId&gt;spring-security-config&lt;/artifactId&gt;
            &lt;version&gt;4.0.4.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;


        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
            &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
            &lt;version&gt;3.0.1&lt;/version&gt;
            &lt;scope&gt;provided&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;postgresql&lt;/groupId&gt;
            &lt;artifactId&gt;postgresql&lt;/artifactId&gt;
            &lt;version&gt;9.1-901.jdbc4&lt;/version&gt;
        &lt;/dependency&gt;


        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;
            &lt;version&gt;5.5.1&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
            &lt;version&gt;5.1.2.RELEASE&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-test-autoconfigure&lt;/artifactId&gt;
            &lt;version&gt;2.1.0.RELEASE&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

    &lt;/dependencies&gt;


&lt;/project&gt;
</code></pre>
<p>When I try to run the test, I get:
java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy</p>
<pre><code>at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:724)
at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:531)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:355)
at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:286)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)
at java.lang.Class.createAnnotationData(Class.java:3521)
at java.lang.Class.annotationData(Class.java:3510)
at java.lang.Class.getAnnotation(Class.java:3415)
at org.junit.validator.AnnotationsValidator$AnnotatableValidator.validateAnnotatable(AnnotationsValidator.java:65)
at org.junit.validator.AnnotationsValidator$AnnotatableValidator.validateTestClass(AnnotationsValidator.java:54)
at org.junit.validator.AnnotationsValidator.validateTestClass(AnnotationsValidator.java:36)
at org.junit.runners.ParentRunner.applyValidators(ParentRunner.java:134)
at org.junit.runners.ParentRunner.collectInitializationErrors(ParentRunner.java:128)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:124)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
at org.junit.runners.ParentRunner.&lt;init&gt;(ParentRunner.java:84)
at org.junit.runners.BlockJUnit4ClassRunner.&lt;init&gt;(BlockJUnit4ClassRunner.java:65)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
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 com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
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>Process finished with exit code -1</p>
",https://stackoverflow.com/questions/57149724/getting-a-sun-reflect-annotation-typenotpresentexceptionproxy-exception-when-try,"['java', 'spring', 'rest', 'junit5']",452,False,1,0
How to View Compiled Jar File in Android Studio for Top-Level Mocking?,"<p><strong>How may the compiled Jar file for an Android app built with Android Studio be accessed?</strong> </p>

<p><em>Use case</em> - <a href=""https://mockk.io"" rel=""nofollow noreferrer"">MockK</a> for JUnit 5 local unit testing in Kotlin, viewing the output of Kotlin  compiled to Java.</p>

<p><em>Android Studio version</em> - <strong>3.5</strong></p>

<p>@oleksiyp, <a href=""https://blog.kotlin-academy.com/mocking-is-not-rocket-science-mockk-advanced-features-42277e5983b5#6cb5"" rel=""nofollow noreferrer"">outlines here</a>, how top-level functions are compiled into Java in this Medium series and in this <a href=""https://stackoverflow.com/a/52894755/2253682"">StackOverflow post</a>. </p>

<p>Examining how the Kotlin files are compiled into Java will allow for mocking more advanced top-level functions where the output is not as straightforward as the below.</p>

<blockquote>
  <p>For instance, the following example:</p>

<pre><code>// Code.kt source file 
package pkg
fun lowercase(str: String): String {...}
</code></pre>
  
  <p>translates to:</p>

<pre><code>package pkg;
class CodeKt {
    public static String lowercase(String str) {...}
} 
</code></pre>
</blockquote>
",https://stackoverflow.com/questions/58102356/how-to-view-compiled-jar-file-in-android-studio-for-top-level-mocking,"['android', 'kotlin', 'junit', 'android-testing', 'mockk']",899,True,1,1
What is the point of mocking this Feign object?,"<p>I'm trying to write a unit test for an implementation of a Feign client. I wasn't sure how to go about it so I googled it and came across <a href=""https://stackoverflow.com/questions/53690959/feign-client-mocking-in-in-junit-implementation"">this</a> answer and the accepted answer is this code snippet:</p>

<pre><code>@Test
public someTestClient(){
    Person expectedPerson = new Person(""name"",12));
    when(mockPersonClient.getPerson()).return(expectedPerson);
    Person person = mockPersionClient.getPerson();
    assertEquals(expectedPerson, person);
}
</code></pre>

<p>I don't understand why this is a useful test or under what circumstance, other than a problem with the <code>Person</code> constructor, this test could ever fail. Isn't this test essentially the equivalent of:</p>

<pre class=""lang-java prettyprint-override""><code>Person person = new Person(""a"", 1)
Person expectedPerson = new Person(""a"", 1)
assertEquals(person, expectedPerson)
</code></pre>

<p>I understand unit testing should test functionality in isolation. Will this test just ensure that <code>mockPersonClient</code> exists at runtime?</p>
",https://stackoverflow.com/questions/56447383/what-is-the-point-of-mocking-this-feign-object,"['java', 'unit-testing', 'mockito']",86,False,1,2
unittesting perform click on a specific view in a childview in exandablelist view,"<p>I have an expandablelistview (for now I can't upgrade it for recycleview) My requirement is to create a test which will open an item in the expandable listview, then click on a specific view inside the child view. </p>

<p>I managed to write the unit testing just to open the expandable view but I was not able to pick one of the children and press on a specific view. </p>

<p>This is my code so far:</p>

<pre><code>@RunWith(AndroidJUnit4.class)
public class TestingListItemClick {

    @Rule
    public ActivityTestRule&lt;ClockActivity&gt; rule =
            new ActivityTestRule&lt;&gt;(ClockActivity.class, false, false);

    private Activity launchedActivity;

    @Before
    public void setup() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        launchedActivity = rule.launchActivity(intent);

        // Context of the app under test.
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        onView(withId(R.id.root_view)).perform(click());
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    @Test
    public void itemClick() {


        DataInteraction dataInteraction = onData(anything()).inAdapterView(withId(R.id.lvTodoList)).atPosition(3);
        dataInteraction.perform(click());


//        dataInteraction.onChildView(withId(R.id.todolisttop)).atPosition(0).perform(click());
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        dataInteraction.atPosition(0).perform(click());


//        onView(withId(R.id.lvTodoList)).perform(RecyclerViewActions.actionOnItemAtPosition(3, click()));
//        onView(withId(R.id.lvTodoList)).perform(RecyclerViewActions.actionOnItemAtPosition(0,
//                                ChildViewAction.clickChildViewWithId(
//                                        R.id.smart_action)));
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}
</code></pre>

<p>I added several thread sleep because I'm waiting for server responses during the workflow. </p>

<p>thank you</p>
",https://stackoverflow.com/questions/59504269/unittesting-perform-click-on-a-specific-view-in-a-childview-in-exandablelist-vie,"['android', 'junit', 'android-espresso']",77,False,1,0
How can I mock a single method from a mocked class in jest?,"<p>I am using <code>node 12</code> and jest for unit testing. I have a code to open connection via websocket.</p>

<pre><code>      const ws = require('ws');
      this.ws = new WebSocket(url);
      this.ws.on('open', () =&gt; {
        // How to test this callback?
        ...
        resolve();
      });
      this.ws.on('error', (err) =&gt; {
        // How to test this callback?
        ...
        reject(err)
      });
</code></pre>

<p>In my test case, I have mocked <code>ws</code> module via jtest:</p>

<pre><code>const WebSocket = require('ws');

jest.mock('ws')

test('quote server listener should be able to connect to quote server', () =&gt; {
  const server = new QuoteServerListener(null, 'http://mock.com');
  server.connect();
  const mockWSInstance = WebSocket.mock.instances[0];
  expect(mockWSInstance.on).toHaveBeenCalledTimes(1);
});
</code></pre>

<p>The above test case works fine. But I don't know how to trigger a call to the callback function on <code>ws.on('open', () =&gt; ...</code>. I'd like to test the logic when the connection is open. How can I achieve this in the mock? 
I have tried to emit a <code>open</code> event via <code>mockWSInstance</code> instance like <code>mockWSInstance.emit('open', null)</code> but it doesn't trigger the code. What should I do in this case?</p>
",https://stackoverflow.com/questions/59084313/how-can-i-mock-a-single-method-from-a-mocked-class-in-jest,"['node.js', 'unit-testing', 'jestjs']",1584,True,1,1
How to write a jest unit-test using the gatsby.navigate function?,"<p>Evening all,</p>

<p>I am building a client side only app with Gatsby.</p>

<p>I'm trying to write some unit tests for my <code>&lt;Login /&gt;</code> component.</p>

<p>Once a user has successfully logged in, they are redirected to /app/,
programatically via gatsby's navigate function</p>

<p>This is my test thus far:</p>

<pre><code>import React from 'react'
import userEvent from '@testing-library/user-event'
import 'jest-dom/extend-expect'
import { navigate } from 'gatsby'
import {
    render,
    fireEvent,
    cleanup,
    act,
    wait
} from '~/__tests__/utils/wrapper'
import Login from '../index'

describe('&lt;Login /&gt;', () =&gt; {

    afterEach(cleanup)

    it('should redirect to /app/ when the correct details are used', async () =&gt; {
        const { getByTestId, getByLabelText } = render(&lt;Login /&gt;)
        const emailField = getByLabelText('Email address')
        const passwordField = getByTestId('password-input')

        act(() =&gt; {
            userEvent.type(emailField, 'test@email.com')
            userEvent.type(passwordField, 'password')
        })

        await wait()

        act(() =&gt; {
            fireEvent.click(getByTestId('login-submit'))
        })

        await wait()

        expect(navigate).toHaveBeenCalledTimes(1) // FAILS
        expect(navigate).toHaveBeenCalledWith('/app/') // FAILS
    })
})
</code></pre>

<p>I have followed the docs here: 
<a href=""https://www.gatsbyjs.org/docs/unit-testing/#3-useful-mocks-to-complete-your-testing-environment"" rel=""nofollow noreferrer"">https://www.gatsbyjs.org/docs/unit-testing/#3-useful-mocks-to-complete-your-testing-environment</a></p>

<p>I've also added <code>navigate: jest.fn()</code> to the exported object.</p>

<p>The component is working so it's definitely something to do with my test.</p>

<p>Any help, greatly appreciated</p>
",https://stackoverflow.com/questions/56940753/how-to-write-a-jest-unit-test-using-the-gatsby-navigate-function,"['reactjs', 'unit-testing', 'jestjs', 'gatsby', 'react-testing-library']",2368,False,1,2
How can I access Objects within a void method while unit testing?,"<p>I am unit testing a Spring Boot service method. I have a void method with no args. It queries a db and gets a List. I can mock and assert on that. Then it runs through the list and changes object fields according to some condition. How can I check the contents of that list so I can assert on them?</p>

<pre><code>@Transactional
public void someMethod() {
    List&lt;Person&gt; myList = repository.findAllByAge(0);
    myList.forEach(person -&gt; person.setAge(18));
}
</code></pre>

<p>How can I assert on myList to check that each Person in myList with age 0 is getting set to age 18? I currently have this in my test class...</p>

<pre><code>@Test
public void someMethod_withSuccess() {
    List&lt;Person&gt; testList = new ArrayList&lt;&gt;();
    testList.add(toPersonEntity(createPersonDto().setAge(0)));
    when(mockRepo.findAllByAge(0)).thenReturn(testList);

    mockService.someMethod();
}
</code></pre>
",https://stackoverflow.com/questions/59204979/how-can-i-access-objects-within-a-void-method-while-unit-testing,"['java', 'unit-testing', 'mockito', 'void']",345,False,1,2
How to solve &#39;SyntaxError: Unexpected identifier&#39; while testing vuetify components using jest,"<p>I have written many components in vuetify that are reusable. I am using jest testing framework for unit testing. When I run 'npm run test', the test fails with 'SyntaxError: Unexpected identifier'.</p>

<p>All my babel config and jest config are in package.json file. When I create a spec file without any vuetify components, test works. But once I add vuetify, it distorts. I first used localValue from @vue/test-utils to consume vuetify. It didn't work. Then I used Vue.use(Vuetify) and still it didn't work.</p>

<p>package.json</p>

<pre><code>        {
      ""name"": ""xyz"",
      ""version"": ""0.2.0"",
      ""private"": true,
      ""scripts"": {
        ""serve"": ""vue-cli-service serve"",
        ""build"": ""vue-cli-service build"",
        ""test"": ""jest"",
        ""clear_jest"": ""jest --clearCache""
      },
      ""dependencies"": {
        ""@contentful/rich-text-html-renderer"": ""^13.0.0"",
        ""@storybook/addon-a11y"": ""^4.1.4"",
        ""avoriaz"": ""^6.3.0"",
        ""axios"": ""^0.18.0"",
        ""axios-mock-adapter"": ""^1.16.0"",
        ""contentful"": ""^7.3.0"",
        ""deepdash"": ""^1.9.5"",
        ""eslint"": ""^5.15.3"",
        ""jest"": ""^24.5.0"",
        ""jest-serializer-vue"": ""^2.0.2"",
        ""json-server"": ""^0.14.2"",
        ""lodash"": ""^4.17.11"",
        ""moment"": ""^2.24.0"",
        ""nightwatch"": ""^1.0.19"",
        ""node-sass"": ""^4.11.0"",
        ""purgecss"": ""^1.1.0"",
        ""sass-loader"": ""^7.1.0"",
        ""storybook-vue-router"": ""^1.0.2"",
        ""tailwindcss-aspect-ratio"": ""^1.0.1"",
        ""tailwindcss-gradients"": ""^1.1.0"",
        ""tailwindcss-transition"": ""^1.0.5"",
        ""vee-validate"": ""^2.2.2"",
        ""vue"": ""^2.5.19"",
        ""vue-faq-accordion"": ""^1.2.1"",
        ""vue-jest"": ""^3.0.4"",
        ""vue-router"": ""^3.0.2"",
        ""vue-template-compiler"": ""^2.5.20"",
        ""vuelidate"": ""^0.7.4"",
        ""vuetify"": ""^1.5.7"",
        ""vuex"": ""^3.1.0"",
        ""vuex-persist"": ""^2.0.0""
      },
      ""devDependencies"": {
        ""@babel/core"": ""^7.3.4"",
        ""@babel/preset-env"": ""^7.3.4"",
        ""@storybook/addon-actions"": ""^4.1.0"",
        ""@storybook/addon-links"": ""^4.1.0"",
        ""@vue/cli-plugin-babel"": ""^3.2.0"",
        ""@vue/cli-plugin-eslint"": ""^3.2.1"",
        ""@vue/cli-service"": ""^3.2.0"",
        ""@vue/test-utils"": ""^1.0.0-beta.29"",
        ""babel-core"": ""^7.0.0-bridge.0"",
        ""babel-jest"": ""^23.6.0"",
        ""babel-preset-vue"": ""^2.0.2"",
        ""chromedriver"": ""^2.46.0"",
        ""concurrently"": ""^4.1.0"",
        ""cross-env"": ""^5.2.0"",
        ""cucumber"": ""^5.1.0"",
        ""cucumber-html-reporter"": ""^4.0.5"",
        ""cucumber-pretty"": ""^1.5.0"",
        ""eslint"": ""^5.15.3"",
        ""geckodriver"": ""^1.16.0"",
        ""http-server"": ""^0.11.1"",
        ""jest-transform-stub"": ""^2.0.0"",
        ""mkdirp"": ""^0.5.1"",
        ""nightwatch-api"": ""^2.1.3"",
        ""stylus"": ""^0.54.5"",
        ""stylus-loader"": ""^3.0.1"",
        ""vue-cli-plugin-storybook"": ""^0.5.0"",
        ""vue-cli-plugin-svg"": ""^0.1.2"",
        ""vue-cli-plugin-tailwind"": ""^0.4.0"",
        ""vue-cli-plugin-vuetify"": ""^0.5.0"",
        ""vue-svg-loader"": ""^0.11.0"",
        ""vue-template-compiler"": ""^2.5.21"",
        ""vuetify"": ""^1.5.7"",
        ""vuetify-loader"": ""^1.0.5""
      },
      ""babel"": {
        ""presets"": [
          [
            ""@babel/preset-env"",
            {
              ""modules"": ""commonjs"",
              ""targets"": {
                ""node"": ""current""
              }
            }
          ]
        ]
      },
      ""eslintConfig"": {
        ""root"": true,
        ""env"": {
          ""node"": true
        },
        ""extends"": [
          ""plugin:vue/essential"",
          ""eslint:recommended""
        ],
        ""rules"": {},
        ""parserOptions"": {
          ""parser"": ""babel-eslint""
        }
      },
      ""browserslist"": [
        ""&gt; 5%"",
        ""last 5 versions"",
        ""not ie &lt;= 10""
      ],
      ""jest"": {
        ""moduleFileExtensions"": [
          ""js"",
          ""vue""
        ],
        ""moduleNameMapper"": {
          ""^@/(.*)$"": ""&lt;rootDir&gt;/src/$1"",
          ""\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$"": ""&lt;rootDir&gt;/__mocks__/fileMock.js"",
          ""\\.(css|less)$"": ""&lt;rootDir&gt;/__mocks__/styleMock.js""
        },
        ""snapshotSerializers"": [
          ""&lt;rootDir&gt;/node_modules/jest-serializer-vue""
        ],
        ""transformIgnorePatterns"": [
          ""&lt;rootDir&gt;/node_modules/(?!vuetify)""
        ],
        ""transform"": {
          "".*\\.(vue)$"": ""&lt;rootDir&gt;/node_modules/vue-jest"",
          ""^.+\\.js$"": ""&lt;rootDir&gt;/node_modules/babel-jest"",
          "".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$"": ""jest-transform-stub""
        }
      }
    }
</code></pre>

<p>Toolbar.vue</p>

<pre><code>        &lt;template&gt;
          &lt;div&gt;
            &lt;v-toolbar class=""toolbar"" height=""70""&gt;
              &lt;v-toolbar-title class=""toolbar-title"" @click=""goToHome()""&gt;{{ title }}&lt;/v-toolbar-title&gt;
              &lt;v-spacer&gt;&lt;/v-spacer&gt;
              &lt;Profile v-if=""user.status""/&gt;
            &lt;/v-toolbar&gt;
          &lt;/div&gt;
        &lt;/template&gt;

        &lt;script&gt;
        import Profile from '@/components/Profile'
        export default {
          props: {
            title: {
              type: String,
              required: true
            }
          },
          components: {
            Profile
          },
          methods: {
            goToHome() {
              this.$router.push('/home')
            }
          }
        }
        &lt;/script&gt;

        &lt;style scoped lang=""postcss""&gt;
        .toolbar-title {
          color: #ffffff;
          text-decoration: none;
          cursor: pointer;
        }
        .toolbar {
          @apply bg-secondary !important;
        }
        &lt;/style&gt;
</code></pre>

<p>Toolbar.spec.js</p>

<pre><code>    import { shallowMount } from '@vue/test-utils'
    import Toolbar from '@/components/List'
    import Vuetify from 'vuetify'
    import Vue from 'vue'

    describe('Toolbar.vue', () =&gt; {
        let wrp
        beforeEach(() =&gt; {
            Vue.use(Vuetify)
            wrp = shallowMount(Toolbar)
        })

        it('Toolbar is a vue instance', () =&gt; {
            expect(wrp.isVueInstance()).toBeTruthy()
        })
    })
</code></pre>

<p>Desired result should be:</p>

<pre><code>    &gt; jest

     PASS  test/unit/component/Toolbar.spec.js
      Toolbar.vue
        √ Toolbar is a vue instance (21ms)

    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        4.882s
    Ran all test suites.
</code></pre>

<p>Actual:
        C:\rahul13615>npm run test</p>

<pre><code>    &gt; myproject@0.2.0 test C:\rahul13615\
    &gt; jest

     FAIL  test/unit/component/Toolbar.spec.js
      ● Test suite failed to run

        C:\rahul13615\node_modules\@babel\runtime-corejs2\helpers\esm\typeof.js:1
        ({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){import _Symbol$iterator from ""../../core-js/symbol/iterator"";
                                                                                                        ^^^^^^^^^^^^^^^^

        SyntaxError: Unexpected identifier

          at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:451:17)
          at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:493:19)
          at Object.&lt;anonymous&gt; (node_modules/vuetify/dist/vuetify.js:91:39)

    Test Suites: 1 failed, 1 total
    Tests:       0 total
    Snapshots:   0 total
    Time:        6.328s
    Ran all test suites.
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! myproject@0.2.0 test: `jest`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the myproject@0.2.0 test script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

    npm ERR! A complete log of this run can be found in:
</code></pre>
",https://stackoverflow.com/questions/55654949/how-to-solve-syntaxerror-unexpected-identifier-while-testing-vuetify-componen,"['vue.js', 'jestjs', 'vuetify.js', 'babel-jest', 'vue-test-utils']",2470,True,6,3
How to import modules for unit tests with QUnit,"<p>I've been trying to add unit tests for some modular ES6 code. I have a project structure like this:</p>

<pre><code>project
└───src
|   └───js
|           cumsum.js
|       index.js &lt;--- entry point
└───test
        tests.js &lt;--- QUnit test code
</code></pre>

<p>This is what's in <code>cumsum.js</code>:</p>

<pre><code>export const cumsum=x=&gt;{
    var result = x.reduce((r, a)=&gt; {
        if (r.length &gt; 0) {
            a += r[r.length - 1];
        }
        r.push(a);
        return r;
    }, []);
    return result;
}
</code></pre>

<p>Now, if I run this sample test by running <code>qunit</code> in the command line, it will work:</p>

<pre><code>const A=[1,2,3,4,5];
const expected=[1,3,6,10,15];
QUnit.test( ""cumsum"", function( assert ) {
    assert.deepEqual([1,3,6,10,15],expected);
});
</code></pre>

<p>but if I try to import the actual <code>cumsum</code> function, it doesn't recognize proper ES6 import syntax:</p>

<pre><code>import {cumsum} from '../src/js/cumsum';
const A=[1,2,3,4,5];
const expected=[1,3,6,10,15];
QUnit.test( ""cumsum"", function( assert ) {
    assert.deepEqual(cumsum(A),expected);
});
</code></pre>

<p>I just get the error </p>

<blockquote>
  <p>SyntaxError: Unexpected token {</p>
</blockquote>

<p>Is there a way to use QUnit with ES6 modules? If not, is there a unit testing framework that will let me test these modules?</p>
",https://stackoverflow.com/questions/57029959/how-to-import-modules-for-unit-tests-with-qunit,"['javascript', 'unit-testing', 'qunit']",1429,False,1,1
Mocking Python function according to different input arguments unittest python,"<p>I have a utility function that takes the argument <strong>case</strong> and return the value accordingly</p>

<pre><code>helper.py
def get_sport_associated_value(dictionary, category, case):
    if case == 'type':
        return ""soccer""
    else: 
        return 1 #if case = 'id'
</code></pre>

<p>I have a main function that use the above function</p>

<pre><code>crud_operations.py
def get_data(category):
    dictionary ={.....}
    id =  get_sport_associated_value(dictionary, category, 'id')
    .....
    .....
    type = get_sport_associated_value(dictionary, category, 'type')
    ....
    return ""successful""
</code></pre>

<p>Now I am unittesting the <strong>get_data()</strong> module using the unittest.Mock. I am having trouble passing the values to <strong>id and type</strong>.</p>

<pre><code>@mock.patch('helper.get_sport_associated_value')
def test_get_data(self, mock_sport):
    with app.app_context():
        mock_sport.side_effect = self.side_effect
        mock_sport.get_sport_associated_value(""id"")
        mock_sport.get_sport_associated_value(""type"")
        result = get_queries(""Soccer"")
        asserEquals(result, ""successful"")

 def side_effect(*args, **kwargs):
     if args[0] == ""type"":
         print(""Soccer"")
         return ""Soccer""
     elif args[0] == ""id"":
         print(""1"")
         return 1
</code></pre>

<p>I tried <a href=""https://stackoverflow.com/questions/16162015/mocking-python-function-based-on-input-arguments"">this</a> using <strong>side_effect function</strong> and facing problem to mock the <strong>get_sport_associated_value()</strong> according to the different values of input argument.</p>

<p>Question 2 : Which is the best method to use <strong>mock</strong> or <strong>mock.magicmock</strong> in this scenario? </p>

<p>Any help is appreciated with unit testing
Thanks</p>
",https://stackoverflow.com/questions/58597991/mocking-python-function-according-to-different-input-arguments-unittest-python,"['python', 'unit-testing', 'mocking', 'magicmock']",139,True,1,1
How to properly patch boto3 calls in unit test,"<p>I'm new to Python unit testing, and I want to mock calls to the boto3 3rd party library.  Here's my stripped down code:</p>

<p>real_code.py:</p>

<pre><code>import boto3

def temp_get_variable(var_name):
  return boto3.client('ssm').get_parameter(Name=var_name)['Parameter']['Value']
</code></pre>

<p>test_real_code.py:</p>

<pre><code>import unittest
from datetime import datetime
from unittest.mock import patch

import real_code

class TestRealCode(unittest.TestCase):

    @patch('patching_config.boto3.client')
    def test_get_variable(self, mock_boto_client):

        response = {
            'Parameter': {
                'Name': 'MyTestParameterName',
                'Type': 'String',
                'Value': 'myValue',
                'Version': 123,
                'Selector': 'asdf',
                'SourceResult': 'asdf',
                'LastModifiedDate': datetime(2019, 7, 16),
                'ARN': 'asdf'
            }
        }

        mock_boto_client.get_variable.return_value = response

        result_value = real_code.get_variable(""MyTestParameterName"")

        self.assertEqual(""myValue"", result_value)
</code></pre>

<p>When I run it the test fails with</p>

<pre><code>Expected :myValue
Actual   :&lt;MagicMock name='client().get_parameter().__getitem__().__getitem__()' id='2040071816528'&gt;
</code></pre>

<p>What am I doing wrong?  I thought by setting <code>mock_boto_client.get_variable.return_value = response</code> it would mock out the call and return my canned response instead. I don't understand why I am getting a MagicMock object instead of the return value I tried to set.  I'd like to set up my test so that when the call to <code>get_parameter</code> is made with specific parameters, the mock returns the canned response I specified in the test.</p>
",https://stackoverflow.com/questions/57065702/how-to-properly-patch-boto3-calls-in-unit-test,"['python', 'unit-testing', 'mocking', 'boto3']",11414,True,6,1
Jest: Mocking third-party modules,"<p>I have been trying to learn unit testing with Jest recently, reading through the docs and various articles.</p>

<p>One thing I have not been able to figure out is the following:</p>

<p>I am trying to test a nodeJS module that has an <code>if</code> statement conditional on <code>os.platform()</code>.</p>

<p>Is there any way for my test to set/mock the <code>os.platform</code> return value to something else, so when the Jest runs the test file the test file will read the os.platform() value specified in the test suite?</p>

<p>PS: <code>foo()</code> cannot accept the platform via dependency injection. The implementation of <code>foo()</code> is fixed.</p>

<p><strong>myModule.js</strong></p>

<pre><code>import os from 'os';
export const foo = () =&gt; {
  if (os.platform() === `win32`) {
    module = module.split(`\\`).join(`\\\\`);
  }
}
</code></pre>

<p><strong>myModule.test.js</strong></p>

<pre><code>import * as myModule from '../myModule.js';

// Guessing I need to use spyOn, to test the actual module code?
const myModuleMock = jest.spyOn(myModule, 'foo');

describe('myModule', () =&gt; {
  it('can run with different os.platform() values', () =&gt; {
    myModuleMock();
    expect(myModuleMock).toHaveBeenCalled();
    // How do I specify what value os.platform() in foo() should return?
  });
});
</code></pre>
",https://stackoverflow.com/questions/55970713/jest-mocking-third-party-modules,"['javascript', 'unit-testing', 'jestjs']",8127,True,6,2
Why Xcode returns the error &quot;file not found&quot; when i import a header file into my unit test class?,"<p>I am trying to create an unit test for my Objective-C project, and I go through the following steps:</p>

<ol>
<li>File > New > Target</li>
<li>Select iOS Unit Testing Bundle</li>
<li>I select my project as 'Target to be tested'</li>
<li>Xcode creates the .m file for the test</li>
</ol>

<p>When i import the class i want to test it highlights the line in red and show ViewController.h file not found</p>

<p>What am I missing, why my test class is not able to import my other classes?</p>

<p>I am using Xcode 10.1 and i have never had this problem before</p>

<p>Thanks,</p>

<p>FP</p>
",https://stackoverflow.com/questions/55120978/why-xcode-returns-the-error-file-not-found-when-i-import-a-header-file-into-my,"['objective-c', 'xcode', 'unit-testing']",868,True,6,2
How to create an in-memory database for PHPUnit testing?,"<p>I'm a newcomer to PHPUnit (and unit testing in general).  I want to work on a test suite that developers can run locally, but can also be run in our integration system (Codeship).  I understand that it is possible to use an in-memory database, but it seems like that relies on the migrations, which we are not using (doesn't seem to handle views, stored procedures, functions, triggers, etc very well?).</p>

<p>What's the best way (place in Laravel) to 1) create a database in memory and seed the database with default data (to be used for ALL test)?</p>
",https://stackoverflow.com/questions/56674160/how-to-create-an-in-memory-database-for-phpunit-testing,"['mysql', 'laravel', 'phpunit', 'laravel-5.5']",10159,True,6,2
ASP.NET Effort CsvLoader does not return data,"<p>I'm using Entity Framework 6 with Code First and I want to mock my DbContext for unit testing. 
Because I need lots of test data for the unit tests, I wanted to load them from a csv-file using Entity Framework Effort (<a href=""https://entityframework-effort.net/"" rel=""nofollow noreferrer"">https://entityframework-effort.net/</a>). </p>

<p>I don't get any errors, but I also don't get any data from the csv-file. All I get is a DbContext (the FapContext in the code) with no data. </p>

<p>Do you have any suggestions to solve my problem?</p>

<p>Unit Test with NUnit:</p>

<pre><code>    private FapContext context;
    private IUnitOfWork unitOfWork;
    private IDataLoader csvLoader;
    private IDataLoader dataLoader;

    [SetUp]
    public void SetUp()
    {
        this.csvLoader = new CsvDataLoader(@""C:\path\TestData\CSV-TestData"");
        this.dataLoader = new CachingDataLoader(this.csvLoader, false);
        DbConnection connection = DbConnectionFactory.CreateTransient(this.dataLoader);

        try
        {
            this.context = new FapContext(connection);
            this.context.Database.CreateIfNotExists();
        }
        catch (Exception e)
        {
            Debug.Print(e.GetType().FullName);
            throw;
        }

        this.unitOfWork = new UnitOfWork(this.context);
    }

    [Test]
    public void ShouldReturnData()
    {
        // Arrange
        List&lt;State&gt; states = this.context.States.ToList();

        // Act

        // Assert
        Assert.IsNotNull(states);           // passes
        Assert.IsTrue(states.Count &gt; 0);    // don't pass
    }
</code></pre>

<p>CSV-File:</p>

<pre><code>ID,StateGroupID,Name,Description,CreatedAt,ChangedAt,RowVersion
""187968CE-0489-4A57-81F4-0BECDF9CC005"",""5FBAD179-68F5-46D2-A0A6-82516A3F2E4D"",""APPROVED"",""Approved material"",,,
""222E365D-A8D7-4DFF-8807-18EC85481FD8"",""AED80358-D2A3-4CC9-A7E5-EA1C8931C27A"",""Running"",,,,
""8433F457-31F1-40D4-AF78-2058415407F7"",""28E828D7-6B5B-9BEC-928D-101DEB38B4C5"",""Pending"",,,,
</code></pre>
",https://stackoverflow.com/questions/54629014/asp-net-effort-csvloader-does-not-return-data,"['c#', '.net', 'entity-framework', 'csv', 'effort']",245,False,1,1
Is there anything in MVC that can&#39;t be implemented in webform,"<p>I have been doing research on the internet on things in MVC that can be implemented through the webform. I have found many articles and like to consolidate things.</p>

<p>1 loosely coupled architecture in MVC can be implemented in webform by implemented similar folder structure for web forms. i.e, keeping aspx in view folder, models in model and custom controller in controller folder. Something that is similar to the aspx view in MVC 2 and 3 using aspx views.</p>

<p>2 MVC URL routing can be implemented by creating a URL rewrite in web forms.</p>

<p>3 unit testing in MVC can also be implemented if we create service that are unit testing friendly and consumes those service in web forms.</p>

<p>4 Dependency Injection can also be achieved using the webform.</p>

<p>5 MVC easiness to support external jQuery libraries can also be implemented using web API in the webform.</p>

<p>6 the problem of view state and event binding of webform server-side controls can also be removed if we use HTML controls in webforms. ( Much easy after webform 4 in .net framework 4.5)</p>

<p>7 we can easily communicate from.webform to MVC controller and vice versa if a project has both web forms and MVC in it.</p>

<p>Can anyone point out anything in MVC that can't be implemented using webforms or contradict with any of the statement made above?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/56945218/is-there-anything-in-mvc-that-cant-be-implemented-in-webform,"['c#', 'asp.net-mvc', 'webforms', 'comparison']",69,True,1,1
How to fix `TypeError: Cannot read property &#39;type&#39; of undefined` when testing i18next with Jest,"<p>I have a react project and I have included i18next = 15.0.4 and react-i18next = 10.2.0 dependencies. I have created a module for initializing i18next with react-i18next and I'm trying to unit test this code using Jest.</p>

<p>I tried importing my i18n module that initializes i18next and unit testing it using jest.</p>

<p>Here is my module for i18n.ts</p>

<pre><code>import i18next from ""i18next"";
import { initReactI18next } from ""react-i18next"";

const config = {
    resources: {
        en: {
            static: {},
        },
    },
    fallbackLng: ""en"",
    defaultNS: ""static"",
    ns: ""static"",
    interpolation: {
        prefix: ""["",
        suffix: ""]"",
    },
};

i18next.use(initReactI18next).init(config);

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

<p>And I'm trying to call it from my test code like this (i18n.test.ts):</p>

<pre><code>import i18n from ""./i18n"";

describe(""i18n"", () =&gt; {

    it(""should work fine"", () =&gt; {
        const strings = {
            key: ""value"",
        };
        i18n.addResourceBundle(""en"", ""static"", strings, true, true);
    });
});

</code></pre>

<p>I would expect this test to pass, but instead I'm getting the following error:</p>

<pre><code>TypeError: Cannot read property 'type' of undefined
      at I18n.use (node_modules/i18next/dist/commonjs/i18next.js:257:18)
</code></pre>

<p>Which basically points out to this code in i18next.js</p>

<pre><code>    value: function use(module) {
      if (module.type === 'backend') {
        this.modules.backend = module;
      }
</code></pre>

<p>How can I fix this issue?</p>
",https://stackoverflow.com/questions/55507684/how-to-fix-typeerror-cannot-read-property-type-of-undefined-when-testing-i1,"['typescript', 'jestjs', 'i18next', 'react-i18next']",10394,True,6,5
Selenium c# Wait for javascript to execute,"<p>I an working on some unit testing using Selenium with Nunit in c#.</p>

<p>In theory this is quite simple, i have a element i want to click to go to another page. 
The issue i have is that the part that makes it clickable loads later than the actual element. Meaning that if i just wait until the element has loaded, clicking it still does nothing.
I also tried waiting for it to be clickable, but it still doesn't seem to work.</p>

<p>Is there any way around this except a static delay?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/58281260/selenium-c-wait-for-javascript-to-execute,"['c#', 'selenium', 'unit-testing', 'selenium-webdriver', 'nunit']",993,True,0,2
Django - Testing Carrying Over POST Variables,"<p>I am working on doing some code coverage unit testing for my Django application when I ran into this interesting predicament.</p>

<h3>tests/test_views.py</h3>

<pre><code>class TestLogin(TestCase):
    def setUp(self):
        self.client = Client()
        self.url = reverse('account:login')
        self.template = 'account/login.html'

    # This test works
    def test_POST_invalid_login(self):
        response = self.client.post(self.url, {
            'username': 'foo',
            'password': 'bar'
        })
        self.assertEqual(response.status_code, 401)
        self.assertTemplateUsed(response, self.template)

    # This is not working as intended.
    def test_POST_no_data(self):
        with self.assertRaises(MultiValueDictKeyError):
            self.client.post(self.url, None)
</code></pre>

<h3>views.py</h3>

<pre><code>class Login(View):
    form_class = LoginForm
    template = 'account/login.html'

    def get(self, request):
        form = self.form_class(None)
        context = {
            'form': form
        }

        return render(request, self.template, context)

    def post(self, request):
        try:
            # Retrieve the username and password
            username = request.POST['username']
            password = request.POST['password']

            # Create a user object from authentication, or return None
            user = authenticate(username=username, password=password)

            # Check if user was created
            if user is not None:
                # Login the user to the website
                login(request, user)

                messages.success(request, 'Login successful! Welcome ' + user.first_name + ' ' + user.last_name)

                # Eventually have this go to profile pages.
                return redirect('home', permanent=True)
            else:
                messages.error(request, 'Login failed: Invalid User.')

        except MultiValueDictKeyError:
            messages.error(request, 'Login failed: Invalid User.')

        # Clear the form since the login attempt failed.
        form = self.form_class(None)

        context = {
            'form': form
        }

        return render(request, self.template, context, status=401)
</code></pre>

<p>The first test, the <code>test_POST_invalid_login</code> sends the data as it suppose to, but the second test, <code>test_POST_no_data</code> should not send any data, but the view still recognizes the <code>foo</code> and <code>bar</code> username and password values thus not catching the exception as it should. I originally written the <em>no data</em> test first and it worked originally. I tried moving the test method above the <em>invalid login</em> test, and it will still fail.</p>

<p>Any suggestions?</p>
",https://stackoverflow.com/questions/58504721/django-testing-carrying-over-post-variables,"['python', 'django', 'unit-testing', 'django-unittest']",619,True,0,2
How can i pass N number of variables for testing in parameterized googletest?,"<p>I am using gtest for unit testing. I have to call a lot to arrays to test. But I am not figuring out how i can pass <code>N - number of variables</code> in <code>'INSTANTIATE_TEST_CASE_P'</code> to test.  </p>

<p>I have simply created two arrays <code>array1</code> and <code>array2</code> and I am passing these two array in the field <code>'testing :: Values'</code> of <code>INSTANTIATE_TEST_CASE_P</code> to test both of them and this test is working fine. </p>

<pre><code>INSTANTIATE_TEST_CASE_P(
        ParameterizedTest,
        TestParam,
        testing :: Values(
                   array1,array2
                   ));
</code></pre>

<p>I want to create <code>N</code>-number of arrays like <code>array1,array2,...,arrayN</code>. But I do not know how i can pass them in the field <code>testing :: Values</code> of <code>INSTANTIATE_TEST_CASE_P</code> to test all of these N arrays.</p>
",https://stackoverflow.com/questions/58746653/how-can-i-pass-n-number-of-variables-for-testing-in-parameterized-googletest,"['c++', 'googletest', 'parametrized-testing']",291,True,0,1
Repository pattern questions,"<p>Lately, I implemented repository pattern and unit of work (using generic repository) because it helps unit testing. There are many tutorials which are in conflict with each other.</p>

<p>I have a few questions related to my code below:</p>

<ul>
<li>I currently have <code>IUnitOfWork/UnitOfWork</code> added as a scoped service in Startup.cs. I'm not quite sure whether it should be one instance (singleton) or new instance (scoped), or even transient.</li>
<li>Did I miss to dispose anything else than <code>IDisposable</code>'s implementation in UnitOfWork?</li>
<li>Anything else wrong with my repository pattern/UnitOfWork implementation?</li>
</ul>

<p>IUnitOfWork.cs</p>

<pre><code>using System.Threading.Tasks;

namespace SaveBees.Repositories
{
    public interface IUnitOfWork
    {
        IUserRepository Users { get; }
        IRoleRepository Roles { get; }

        Task&lt;int&gt; SaveAsync();
    }
}
</code></pre>

<p>UnitOfWork.cs</p>

<pre><code>using System;
using System.Threading.Tasks;

namespace SaveBees.Repositories
{
    public class UnitOfWork : IUnitOfWork, IDisposable
    {
        private readonly SaveBeesContext _context;

        public UnitOfWork(SaveBeesContext context)
        {
            _context = context;
        }

        private IRoleRepository _roleRepository;

        public IRoleRepository Roles
        {
            get
            {
                if (_roleRepository == null)
                {
                    _roleRepository = new RoleRepository(_context);
                }

                return _roleRepository;
            }
        }

        private IUserRepository _userRepository;

        public IUserRepository Users
        {
            get
            {
                if (_userRepository == null)
                {
                    _userRepository = new UserRepository(_context);
                }

                return _userRepository;
            }
        }

        public async Task&lt;int&gt; SaveAsync()
        {
            return await _context.SaveChangesAsync();
        }

        private bool _disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            _disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
</code></pre>

<p>IGeneralRepository.cs</p>

<pre><code>using SaveBees.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace SaveBees.Repositories
{
    public interface IGenericRepository&lt;TEntity&gt; where TEntity : class, IEntity
    {
        Task&lt;List&lt;TEntity&gt;&gt; GetAllAsync(Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null, Func&lt;IQueryable&lt;TEntity&gt;, IQueryable&lt;TEntity&gt;&gt; includes = null);
        Task&lt;List&lt;TEntity&gt;&gt; QueryAsync(Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter, Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null, Func&lt;IQueryable&lt;TEntity&gt;, IQueryable&lt;TEntity&gt;&gt; includes = null);
        Task&lt;TEntity&gt; GetByIdAsync(int id, Func&lt;IQueryable&lt;TEntity&gt;, IQueryable&lt;TEntity&gt;&gt; includes = null);
        Task&lt;TEntity&gt; SingleOrDefaultAsync(Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter, Func&lt;IQueryable&lt;TEntity&gt;, IQueryable&lt;TEntity&gt;&gt; includes = null);
        Task AddAsync(TEntity entity);
        void Update(TEntity entity);
        void Remove(TEntity entity);
    }
}
</code></pre>

<p>GeneralRepository.cs</p>

<pre><code>using Microsoft.EntityFrameworkCore;
using SaveBees.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace SaveBees.Repositories
{
    public abstract class GenericRepository&lt;TEntity, TContext&gt; : IGenericRepository&lt;TEntity&gt;
        where TEntity : class, IEntity
        where TContext : DbContext
    {
        private readonly TContext _context;

        public GenericRepository(TContext context)
        {
            _context = context;
        }

        public async Task&lt;List&lt;TEntity&gt;&gt; GetAllAsync(Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null, Func&lt;IQueryable&lt;TEntity&gt;, IQueryable&lt;TEntity&gt;&gt; includes = null)
        {
            IQueryable&lt;TEntity&gt; query = _context.Set&lt;TEntity&gt;();

            if (includes != null)
            {
                query = includes(query);
            }

            if (orderBy != null)
            {
                query = orderBy(query);
            }

            return await query.ToListAsync();
        }

        public async Task&lt;List&lt;TEntity&gt;&gt; QueryAsync(Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter, Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null, Func&lt;IQueryable&lt;TEntity&gt;, IQueryable&lt;TEntity&gt;&gt; includes = null)
        {
            IQueryable&lt;TEntity&gt; query = _context.Set&lt;TEntity&gt;();

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

            if (includes != null)
            {
                query = includes(query);
            }

            if (orderBy != null)
            {
                query = orderBy(query);
            }

            return await query.ToListAsync();
        }

        public async Task&lt;TEntity&gt; GetByIdAsync(int id, Func&lt;IQueryable&lt;TEntity&gt;, IQueryable&lt;TEntity&gt;&gt; includes = null)
        {
            IQueryable&lt;TEntity&gt; query = _context.Set&lt;TEntity&gt;();

            if (includes != null)
            {
                query = includes(query);
            }

            return await query.SingleOrDefaultAsync(x =&gt; x.Id == id);
        }

        public async Task&lt;TEntity&gt; SingleOrDefaultAsync(Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter, Func&lt;IQueryable&lt;TEntity&gt;, IQueryable&lt;TEntity&gt;&gt; includes = null)
        {
            IQueryable&lt;TEntity&gt; query = _context.Set&lt;TEntity&gt;();

            if (includes != null)
            {
                query = includes(query);
            }

            return await query.SingleOrDefaultAsync(filter);
        }

        public async Task AddAsync(TEntity entity)
        {
            await _context.Set&lt;TEntity&gt;().AddAsync(entity);
        }

        public void Update(TEntity entity)
        {
            _context.Set&lt;TEntity&gt;().Update(entity);
        }

        public void Remove(TEntity entity)
        {
            _context.Remove(entity);
        }
    }
}
</code></pre>

<p>IUserRepository.cs</p>

<pre><code>using SaveBees.Models;
using System.Threading.Tasks;

namespace SaveBees.Repositories
{
    public interface IUserRepository : IGenericRepository&lt;User&gt;
    {
        Task&lt;User&gt; GetByEmailAsync(string email);
    }
}
</code></pre>

<p>UserRepository.cs</p>

<pre><code>using Microsoft.EntityFrameworkCore;
using SaveBees.Models;
using System.Threading.Tasks;

namespace SaveBees.Repositories
{
    public class UserRepository : GenericRepository&lt;User, SaveBeesContext&gt;, IUserRepository
    {
        public UserRepository(SaveBeesContext context) : base(context)
        {
        }

        public async Task&lt;User&gt; GetByEmailAsync(string email)
            =&gt; await SingleOrDefaultAsync(e =&gt; e.Email == email,
                e =&gt; e.Include(u =&gt; u.UserRoles)
                    .ThenInclude(ur =&gt; ur.Role));
    }
}
</code></pre>

<p>IEntity.cs</p>

<pre><code>namespace SaveBees.Data
{
    public interface IEntity
    {
        public int Id { get; set; }
    }
}
</code></pre>
",https://stackoverflow.com/questions/58268736/repository-pattern-questions,"['c#', 'asp.net-core']",157,False,0,0
JUnit test of a method does compile and shows multiple error markers,"<p>I am new to Unit testing and do not understand why the following code does not work. I have this method:</p>

<pre><code>public class TaxTime {


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

public static double calculateFamilyTaxSaving(double taxAmount, int familyMembers) {
  for (int i = 0; i &lt;= familyMembers; i++){
       taxAmount = taxAmount - 100;
   }
   return taxAmount;
 }
</code></pre>

<p>And I am trying to test the code with this testing class:</p>

<pre><code> import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.fail;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;

 class TaxTimeTest {

  @BeforeEach
  void setUp() throws Exception {
  }

  @Test
  void test() {
    fail(""Not yet implemented"");

}

@Test
static void stattestCalculateFamilyTaxSaving() {
    TaxTime taxtime = new TaxTime();
    double taxAmount = 600;
    int familyMembers = 3;
     assertTrue(taxtime.calculateFamilyTaxSaving(taxAmount,familyMembers).equals(200.0));
 }
}
</code></pre>

<p>Despite that the code does not compile and I get this message:</p>

<blockquote>
  <p>Multiple markers at this line</p>
  
  <ul>
  <li>Cannot invoke equals(double) on the primitive type double</li>
  <li>The static method calculateFamilyTaxSaving(double, int) from the type TaxTime should be accessed in a static way</li>
  </ul>
</blockquote>

<p>Could someome help me understand what I am doing wrong? I think I am missing something really essential.</p>
",https://stackoverflow.com/questions/54044799/junit-test-of-a-method-does-compile-and-shows-multiple-error-markers,"['java', 'unit-testing', 'junit']",161,True,-1,2
Trouble with View Unit Testing in AngularJS,"<p>In doing some research on AngularJS component testing I've read about <strong>View Unit Testing</strong>, as described <a href=""https://medium.com/@carmelc_20450/testing-angular-components-you-dont-know-what-you-re-missing-149a1cae6668"" rel=""nofollow noreferrer"">here</a>. I've tried it this way: </p>

<h2>component</h2>

<pre><code>angular.module(""recipeDetail"").component(""recipeSummary"", {
  templateUrl:
    ""modules/recipe-detail/recipe-summary/recipe-summary.template.html"",
  bindings: { recipe: ""&lt;"" },
  controller: function RecipeSummaryController() {}
});
</code></pre>

<h2>template</h2>

<pre class=""lang-js prettyprint-override""><code>&lt;h1 id=""recipe-title""&gt;{{ $ctrl.recipe.title }}&lt;/h1&gt;
&lt;p&gt;
  Steps:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li ng-repeat=""step in $ctrl.recipe.steps"" class=""recipe-summary-step""&gt;
    {{ step.text }}
  &lt;/li&gt;
&lt;/ul&gt;
</code></pre>

<h2>test</h2>

<pre><code>describe(""recipeSummary ViewUnitTest"", () =&gt; {
  let scope;
  let $compile;
  beforeEach(module(""recipeDetail""));

  beforeEach(inject(($rootScope, _$compile_) =&gt; {
    scope = $rootScope.$new();
    $compile = _$compile_;
  }));

  it(""should display the steps"", () =&gt; {
    scope.recipe = recipe;
    let el = angular.element('&lt;recipe-summary recipe=""recipe""/&gt;');
    el = $compile(el)(scope);
    scope.$digest();
    expect(el[0].querySelectorAll(""p"").length).toBe(1); // to make sure this whole thing is working 
    expect(el[0].querySelectorAll("".recipe-summary-step"").length).toBe(3);
  });
});
</code></pre>

<p>Both assertions fail – both the first (<code>p</code>) that checks that I'm implementing the test correctly, and the second (<code>.recipe-summary-step</code>) which tests the actual function of the component.</p>

<h2>UPDATE</h2>

<p>Well don't I feel dumb. George pointed out that I didn't actually <em>call</em> <code>scope.$digest()</code>.</p>

<p>So after doing that I have a new error/failure:</p>

<pre><code>Chrome 74.0.3729 (Mac OS X 10.14.4) recipeSummary ViewUnitTest should display the steps FAILED
        Error: Unexpected request: GET modules/recipe-detail/recipe-summary/recipe-summary.template.html
        No more request expected
        error properties: Object({ $$passToExceptionHandler: true })
            at createFatalError (/Users/TuzsNewMacBook/Development/code/AngularJS/recipe-angular-from-phonecat/node_modules/angular-mocks/angular-mocks.js:1569:19)
            at $httpBackend (/Users/TuzsNewMacBook/Development/code/AngularJS/recipe-angular-from-phonecat/node_modules/angular-mocks/angular-mocks.js:1616:11)
            at sendReq (lib/angular/angular.js:13257:9)
            at serverRequest (lib/angular/angular.js:12998:16)
            at processQueue (lib/angular/angular.js:17914:37)
            at lib/angular/angular.js:17962:27
            at ChildScope.$digest (lib/angular/angular.js:19075:15)
            at UserContext.&lt;anonymous&gt; (modules/recipe-detail/recipe-summary/recipe-summary.component.spec.js:32:11)
            at &lt;Jasmine&gt;
</code></pre>

<p>Apparently a <code>templateUrl</code> is resolved with an actual <code>get</code> request and apparently that's a fatal error. So how do I use this technique? </p>
",https://stackoverflow.com/questions/56309030/trouble-with-view-unit-testing-in-angularjs,"['angularjs', 'unit-testing']",84,False,0,0
"When unit testing my ViewModel, list always returns empty","<p>I'm trying to learn unit testing, I have my code factored into an MVVM(i) architecture, but when I run my testParseToList() test function, it always comes back with an empty list and I can't figure out why.  I fear it may have something to do with the i part of the MVVM(i) and whether or not I'm correctly mocking my viewmodel.  I'm starting with my most simple viewmodel in hopes to get a grasp of the concepts before moving onto my more complex ones.</p>

<p><strong>OfflineViewModelUnitTest.kt</strong></p>

<pre><code>@RunWith(JUnit4::class)
class OfflineViewModelUnitTest {

    @get:Rule
    val rule = InstantTaskExecutorRule()

    @Mock
    var offlineViewModel: OfflineViewModel = OfflineViewModel(OfflineInteractorImpl())

    @Before
    fun setup() {
        MockitoAnnotations.initMocks(this)
        DaggerOfflineViewModelComponent.builder()
            .offlineInteractorImplModule(OfflineInteractorImplModule())
            .build()
            .inject(offlineViewModel)

//        this.offlineViewModel = OfflineViewModel(OfflineInteractorImpl())
    }

    @Test
    fun testParseToList() {

        val test = offlineViewModel.parseTextToList(""dried bonito extract,\n"" +
                ""    ketchup,\n"" +
                ""    millet,\n"" +
                ""    corn &amp; wheat protein"")

        val a = ""dried bonito extract""
        val b = ""ketchup""
        val c = ""millet""
        val d = ""corn &amp; wheat protein""

        val expectedResult = listOf(a, b, c, d)

        assertEquals(expectedResult, test)
    }
}
</code></pre>

<p><strong>OfflineViewModel.kt</strong></p>

<pre><code>class OfflineViewModel(private val offlineInteractor: OfflineInteractor): ViewModel() {

    init {
        DaggerOfflineViewModelComponent.builder()
            .offlineInteractorImplModule(OfflineInteractorImplModule())
            .build()
            .inject(this)
    }
    fun parseTextToList(firebaseVisionTextString: String): MutableList&lt;String&gt; {
        Log.d(""here it is"", firebaseVisionTextString)
        return offlineInteractor.parseTextToList(firebaseVisionTextString)
    }

    fun readCsvFromAssetFolder(inputStream: InputStream): List&lt;String&gt;{
        return offlineInteractor.readCsvFromAssetFolder(inputStream)
    }
}
</code></pre>

<p><strong>OfflineInteractorImpl.kt</strong></p>

<pre><code>class OfflineInteractorImpl: OfflineInteractor {

    override fun parseTextToList(firebaseVisionTextString: String): MutableList&lt;String&gt; {

            val ingredientsList: MutableList&lt;String&gt; = firebaseVisionTextString.split("","").map { it.trim() }.toMutableList()

            return ingredientsList
    }

    override fun readCsvFromAssetFolder(inputStream: InputStream): List&lt;String&gt; {
        val csvLine: ArrayList&lt;String&gt; = ArrayList()
        var content: Array&lt;String&gt;?
        try
        {
            val br = BufferedReader(InputStreamReader(inputStream))
            for (line in br.lines())
            {
                content = line.split(("","").toRegex()).dropLastWhile{ it.isEmpty() }.toTypedArray()
                csvLine.add(content[0].substringBefore("";""))
            }
            br.close()
        }
        catch (e: IOException) {
            e.printStackTrace()
        }
        return csvLine
    }
}
</code></pre>

<p><strong>Test Results</strong></p>

<pre><code>java.lang.AssertionError: 
Expected :[dried bonito extract, ketchup, millet, corn &amp; wheat protein]
Actual   :[]
</code></pre>
",https://stackoverflow.com/questions/57862471/when-unit-testing-my-viewmodel-list-always-returns-empty,"['unit-testing', 'kotlin', 'junit', 'mockito']",684,True,0,1
Expected Response with status: null null for URL: null to equal &#39;Project11&#39;,"<p>I am using angular7 and doing unit testing in jasmine and karma. And I am facing error - </p>

<blockquote>
  <p>Error: Expected Response with status: null null for URL: null to equal 'Project11'.</p>
</blockquote>

<p>My packages versions are -</p>

<blockquote>
  <p>""@types/jasmine"": ""~2.8.6"",
      ""@types/jasminewd2"": ""~2.0.3"",
      ""@types/jquery"": ""^3.3.22"",
      ""@types/node"": ""~8.9.4"",
      ""codelyzer"": ""~4.2.1"",
      ""jasmine-core"": ""~2.99.1"",
      ""jasmine-spec-reporter"": ""~4.2.1"",
      ""karma"": ""~1.7.1"",
      ""karma-chrome-launcher"": ""~2.2.0"",
      ""karma-coverage-istanbul-reporter"": ""~1.4.2"",
      ""karma-jasmine"": ""~1.1.1"",
      ""karma-jasmine-html-reporter"": ""^0.2.2"",
      ""protractor"": ""^5.4.1"",
      ""ts-node"": ""~5.0.1"",
      ""tslint"": ""~5.9.1"",
      ""typescript"": ""~3.1.3""</p>
</blockquote>

<p><a href=""https://stackoverflow.com/questions/39472364/testing-cant-resolve-all-parameters-for-classname"">Testing - Can&#39;t resolve all parameters for (ClassName)</a></p>

<pre><code>import { inject } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';
import {
  Http, HttpModule, XHRBackend, ResponseOptions,
  Response, BaseRequestOptions
} from '@angular/http';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA} from '@angular/core';;


fdescribe('ProjectManagementComponent', () =&gt; {
  let comp: ProjectManagementComponent;
  let fixture: ComponentFixture&lt;ProjectManagementComponent&gt;;
  let de: DebugElement;
  let el: HTMLElement;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ProjectManagementComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      imports: [HttpClientModule, RouterTestingModule, RouterModule, NgbModule, NgxPaginationModule, FormsModule, ReactiveFormsModule, BrowserModule,],
      providers: [{ provide: ProjectManagementServiceStub, useClass: ProjectManagementServiceStub },
      { provide: ProductsService, useClass: ProductsService }, {
        provide: HttpClient,Http, useFactory: (backend, options) =&gt; {
          return new Http(backend, options);
        },
        deps: [MockBackend, BaseRequestOptions]
      },
        MockBackend,
        BaseRequestOptions,ProjectManagementService
      ]
    }) .compileComponents()

  }));

  beforeEach(async(() =&gt; {
    fixture = TestBed.createComponent(ProjectManagementComponent);
    comp = fixture.componentInstance;

    fixture.nativeElement.querySelectorAll('button');
  }));

  it('should create component', () =&gt; {
    fixture = TestBed.createComponent(ProjectManagementComponent);
    comp = fixture.componentInstance;
    expect(comp).toBeTruthy();
  });


  it('should get value of toEqual', async(inject([ProjectManagementServiceStub, MockBackend],
    (service: ProjectManagementServiceStub, backend: MockBackend) =&gt; {

      backend.connections.subscribe((conn: MockConnection) =&gt; {
        const options: ResponseOptions = new ResponseOptions({ body: 'Project11' });
        conn.mockRespond(new Response(options));
      });

      service.getProject(""http://192.168.5.140:3002/api/project/"").subscribe(res =&gt; {
        console.log(""Subscription called"")
        expect(res).toEqual('Project11')
      })
    })))
});
</code></pre>

<p>app.component.service.stub.ts</p>

<pre><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { config } from ""config"";
import { Observable } from ""rxjs"";
const baseUrl: string = config.url;

@Injectable()
export class ProjectManagementServiceStub {
    constructor(private http: HttpClient) { }

    getProject(url) :Observable&lt;any&gt;{

        return this.http.get(url )
            .pipe(map(Response =&gt; Response))

    }
}
</code></pre>
",https://stackoverflow.com/questions/57690695/expected-response-with-status-null-null-for-url-null-to-equal-project11,"['angular', 'typescript', 'jasmine', 'karma-jasmine']",442,True,-1,1
Unit testing fs-extra writeFile,"<p>I have used <code>writeFile</code> from <code>fs-extra</code> to generate my file When I tried to do unit testing using JEST I'm always getting an error like the <code>writeFile</code> method was not called even though it has been called. Can someone plz suggest me ways to get it tested properly.</p>

<p>These are the functions I'm using.
Note: No class has been used, we are consuming it as methods</p>

<pre><code>import { writeFile } from 'fs-extra';
import { resolve as pathResolve } from 'path';

export default async function generateFile(): Promise&lt;void&gt;{
   await writeSampleFile(value);
   // other stuffs
}

async function writeSampleFile(value: string): Promise&lt;void&gt; {
  try {
    await writeFile(pathResolve(path), value, 'utf8');
  } catch (err) {
  }
}
</code></pre>

<p><code>spec.ts</code>:</p>

<pre><code>import generateFile from './x';
import * as fsExtra from 'fs-extra';

const writeFileSpy = jest.spyOn(fsExtra, 'writeFile');


describe('writeFile', async () =&gt; {
  test('it should check whether writeFile has been called', async () =&gt; {
    await generateFile();
    //Since internally it was calling writeFile i was checking for writeSampleFile as well
    expect(writeFileSpy).toHaveBeenCalled();
  });
});
</code></pre>

<p>Though I have called everything I'm not getting the method as called and the test got failed but my file is getting generated using the <code>writeFile</code>.</p>
",https://stackoverflow.com/questions/58625148/unit-testing-fs-extra-writefile,"['node.js', 'angular', 'jestjs']",1375,True,0,1
Unit Testing non returning functions in Qt,"<p>you might remember me or running a kind of a 'Lightroom' panel, using C++ and Qt for GUI.
Today I was reading about implementing a unit testing for my main classes, but my question is, how can I test a function that does not return anything?</p>

<p>for example, I got that function:</p>

<pre><code>void ImgProcessing::processMaster(cv::Mat&amp; img, cv::Mat&amp; tmp, int brightness, int red, int green, int blue, double contrast){

for(int i = 0; i &lt; img.rows; i++)
    for(int j = 0; j &lt; img.cols; j++)
        for(int k = 0; k &lt; 3; k++){
            if(k == 0)  //_R
                tmp.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;((img.at&lt;cv::Vec3b&gt;(i,j)[k] + brightness + red )*(259 * (contrast + 255) / (255 * (259 - contrast))));
            if(k == 1)  //_G
                tmp.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;((img.at&lt;cv::Vec3b&gt;(i,j)[k] + brightness + green )*(259 * (contrast + 255) / (255 * (259 - contrast))));
            if(k == 2)  //_B
                tmp.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;((img.at&lt;cv::Vec3b&gt;(i,j)[k] + brightness + blue )*(259 * (contrast + 255) / (255 * (259 - contrast))));
        }            
</code></pre>

<p>this function just take the obj 'mat img', and modify the 'mat tmp' obj.
than I update the UI for display the modified image, by using another dedicated function in my gui class.</p>

<p>Has someone already encounter something like that?</p>
",https://stackoverflow.com/questions/56768238/unit-testing-non-returning-functions-in-qt,"['c++', 'qt', 'unit-testing', 'qt-creator']",196,True,0,1
Jasmine Global Variable initialization,"<p>I am writing Angular component unit testing using jasmine.
We are having class with static variables which is initialized during loading time of application.
Currently we are initializing those static variables in beforeAll of the unit test of component which uses those variable.</p>

<p><strong>Calling the same initialization function in all the unit test files seems redundant.</strong></p>

<p><strong>Is there any way to initialize those static variables globally during the beginning of jasmine unit test which can be available to all the unit test suits ?</strong></p>

<p>Currently we are initializing those static variable like this :</p>

<pre><code>describe(('mycomponent'), () =&gt; {
  beforeAll(()=&gt;{
   // call to initialize function
  });
});
</code></pre>
",https://stackoverflow.com/questions/54341919/jasmine-global-variable-initialization,"['angular', 'unit-testing', 'jasmine', 'angular-unit-test']",948,False,0,1
Junit mocking error : org.mockito.exceptions.misusing.MissingMethodInvocationException,"<p>I am using <code>spring data JPA</code> for creating services and for unit testing I am using <code>Junit</code> and <code>mockito</code>. In following code I am trying to do junit testing for service class.</p>

<p>Room account mapping service class is dependent on Room Investigator mapping service class so I used mockito for mocking room Investigator mapping service class method but that method calling one more method of same class.</p>

<p>I tried like below but I am getting error in mockito. Can any one please tell me how I can do mocking?</p>

<p><strong>TestRoomAccountMappingService class</strong></p>

<pre><code>public class TestRoomAccountMappingService {
    @MockBean
    RoomAccountMappingRepository roomAccountMapRepository;

    @Autowired
    RoomAccountMappingService roomAccountMappingService;

    @Autowired
    RoomInvestigatorMappingService roomInvestMapService;

    @Test
    public void deleteAccountMapping() {

        Integer[] RoomAllocationId= {1839};         

        //here getting error
        Mockito.when(roomInvestMapService.returnRoomWithinClusterByRoomAllocationID(1839)).thenReturn(RoomAllocationId);

        RoomAccountMapping roomAcctMap= new RoomAccountMapping();
        roomAcctMap.setnRoomAllocationId(1);

        List&lt;RoomAccountMapping&gt; roomList= new ArrayList&lt;&gt;();
        roomList.add(roomAcctMap);      

        Mockito.when(roomAccountMapRepository.findByNRoomAllocationId(1839)).thenReturn(roomList);

        Boolean actual = roomAccountMappingService.deleteAccountMapping(1839);

        assertEquals(true, actual );
    }
}
</code></pre>

<p><strong>Failure Trace</strong></p>

<pre><code>org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

    at com.spacestudy.service.TestRoomAccountMappingService.deleteAccountMapping(TestRoomAccountMappingService.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
</code></pre>
",https://stackoverflow.com/questions/54920697/junit-mocking-error-org-mockito-exceptions-misusing-missingmethodinvocationexc,"['junit', 'spring-data-jpa', 'mockito']",457,True,0,1
Sqlite keep in memory database open until jvm exit,"<p>I'd like to keep an in memory sqlite database, but without attached connections.</p>

<p>I'm unit testing a web app, so in the @BeforeAll method I do some initialization and then, in the various test methods, do some DDL manipulation.</p>

<p>Of course, when the last open connection is closed, sqlite in memory db is teared down, breaking my tests.</p>

<p>I achieved to keep a H2 in memory database open till the JVM lives, doing this</p>

<pre><code>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
</code></pre>

<p>But I can't find an alternative for sqlite.
I tried with </p>

<pre><code>jdbc:sqlite::memory:&amp;cache=shared
</code></pre>

<p>But doesn't seem to work.</p>

<p>Is it possible?</p>
",https://stackoverflow.com/questions/56363640/sqlite-keep-in-memory-database-open-until-jvm-exit,"['java', 'sqlite']",471,False,0,1
How do you Mock AutoMapper MapTo?,"<p>I've seen lots of questions around unit testing automapper 'map' but how do you mock 'MapTo'. This expects an IMapper as it's object. So, this is what I have so far:</p>

<pre><code>private Mock&lt;IMapper&gt; _mapper;

[TestInitialize]
public void Init()
{
    _mapper = new Mock&lt;IMapper&gt;();

    //other stuff initialised.
}

[TestMethod]
public void MyTest()
{
    _mapper.Setup(m =&gt; m.MapTo&lt;IList&lt;Something&gt;&gt;(_mapper.Object)).Returns(myList);

    //setup repository etc.
}
</code></pre>

<p>This throws an error of ""Invalid setup on an extension method..."". So, how do I mock out the call to 'MapTo'?</p>

<p>Just to clarify, I know I can use an actual version of the mapper and create actual maps like:</p>

<pre><code>private MapperConfiguration CreateMaps()
{
    return new MapperConfiguration(mc =&gt;
   {
       mc.CreateMap&lt;MyEntity, MyObject&gt;();
       mc.CreateMap&lt;MyOtherEntity, MyOtherObject&gt;();
   });
}

_mapper = new Mapper(CreateMaps());
</code></pre>

<p>However, I was still curious how to mock it. It seems an easy thing to do with Map but not MapTo         </p>
",https://stackoverflow.com/questions/54811587/how-do-you-mock-automapper-mapto,"['c#', 'unit-testing', 'automapper', 'moq']",635,True,0,2
Script codecept handling the __exec_command event returned with error code 255,"<p>I am very new to unit testing and have been trying to use codeception to do it. So I have followed the following guidelines <a href=""https://codeception.com/for/laravel"" rel=""nofollow noreferrer"">link</a>
and installed it using composer: <code>composer require ""codeception/codeception"" --dev</code>, it was successful, but when I tried to set it up using <code>composer exec codecept bootstrap</code> I got the following error:</p>

<blockquote>
  <p>Script codecept handling the __exec_command event returned with error
  code 255</p>
</blockquote>

<p>Anyone knows how to fix it?</p>

<p>Just FYI, I have pulled the whole project from a repo that already has the tests/unit folder with previous tests already.</p>

<p>My composer.json file has the following</p>

<pre><code>    ""require"": {
        ""codeception/robo-paracept"": ""dev-master"",
    },
    ""require-dev"": {
        ""codeception/codeception"": ""2.6.x-dev"",
</code></pre>
",https://stackoverflow.com/questions/55015900/script-codecept-handling-the-exec-command-event-returned-with-error-code-255,"['laravel', 'unit-testing', 'composer-php', 'codeception']",2203,False,0,2
Unit testing methods which update UI elements in iOS,"<p>I am trying to write unit tests for my existing code. 
I have 3 methods.</p>

<pre><code>func methodOne() {
    // code
    methodTwo()
}

func methodTwo() {
    // code
    methodThree()
}

func methodThree() {
    // code
    // update UI element
}
</code></pre>

<p>What's the ideal way to unit test such methods. While unit testing <code>methodTwo()</code> it calls <code>methodThree()</code> as the UI elements are not loaded they have <code>nil</code> value when <code>methodThree()</code> is called. How to unit test methods which involve UI elements. I don't want to test if the UI element is loaded properly, I just want to test the code in <code>methodTwo()</code> and <code>methodThree()</code>. Is there a way to bypass UI elements related code. Any help is appreciated. Thank you.</p>
",https://stackoverflow.com/questions/55727108/unit-testing-methods-which-update-ui-elements-in-ios,"['ios', 'swift', 'unit-testing']",180,False,0,2
undefined object when defined in Angular Unit testing,"<p>I'm working through my test environment and am trying to get around an issue with a single user profile through <code>oidc-client</code> being undefined during unit testing. </p>

<p>I have tried making the <code>BeforeEach</code> methods <code>async</code> that has not helped, and I have also tried restructuring my <code>AuthService</code> as well. </p>

<p>This is the error that I am getting from the test components:</p>

<p><code>ResourcesCardComponent &gt; should create</code></p>

<p><code>Failed: Cannot read property 'profile' of undefined</code></p>

<p><strong>AuthService</strong> </p>

<pre><code>import { Injectable } from '@angular/core';
import { UserManager, User, WebStorageStateStore } from 'oidc-client';
import { BehaviorSubject } from 'rxjs';
import { ConfigAssetLoaderService } from '../config-asset-loader.service';
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private _userManager: UserManager;
  public _user: User;
  public isLoggedInSubject$ = new BehaviorSubject&lt;any&gt;(this._user);
  isLoggedIn = this.isLoggedInSubject$.asObservable();

  constructor(private configService: ConfigAssetLoaderService) {
    const config = {};
    this.configService.loadConfiguration().subscribe(response =&gt; {
      config['authority'] = response.authority;
      config['client_id'] = response.client_id;
      config['redirect_uri'] = response.redirect_uri;
      config['scope'] = response.scope;
      config['response_type'] = response.response_type;
      config['loadUserInfo'] = response.loadUserInfo;
      config['userStore'] = new WebStorageStateStore({store: window.sessionStorage});
      config['metadata'] = {
        issuer: response.issuer,
        authorization_endpoint: response.authorization_endpoint,
        userinfo_endpoint: response.userinfo_endpoint,
        jwks_uri: response.jwks_uri,
        end_session_endpoint: response.end_session_endpoint
      };
      config['signingKeys'] = response.signingKeys;
      config['extraQueryParams'] = {
        resource: response.claimsApiResourceId
      };
      this._userManager = new UserManager(config);
      this._userManager.getUser().then(user =&gt; {
        if (user &amp;&amp; !user.expired) {
          this._user = user;
          this.isLoggedInSubject$.next(user);
        }
      });
    });
  }
}
</code></pre>

<p>The <code>AuthService</code> is pretty standard, all the important pieces for this question are in the constructor. </p>

<p>The component in question using this service is the following: </p>

<pre><code>import { Component, Input } from '@angular/core';
import { ActionLink } from '../../shared/models/actionlink';
import { AuthService } from '../../core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'thrive-resources-card',
  templateUrl: './resources-card.component.html',
  styleUrls: ['./resources-card.component.scss']
})
export class ResourcesCardComponent {

  @Input() public actionLinks: ActionLink[];

  public firstName$: Observable&lt;string&gt;;

  constructor(private authService: AuthService) {
    this.firstName$ = this.authService.isLoggedInSubject$.pipe(
      map(response =&gt; response.profile.unique_name.replace(/\s+/, '').split(',')[1])
    );
  }
}
</code></pre>

<p>Here is the test component for the <code>ResourceCardComponent</code> as well:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ResourcesCardComponent } from './resources-card.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ActivatedRoute, RouterModule } from '@angular/router';
import { ResourcesCardContainerComponent } from './resources-card-container/resources-card-container.component';

const fakeRoute = {
  snapshot: {
      data: {
        actionLinks: []
      }
  }
};

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        ResourcesCardComponent,
        ResourcesCardContainerComponent
      ],
      imports: [
        RouterModule,
        HttpClientTestingModule
      ],
      providers: [
        {
          provide: ActivatedRoute,
          useFactory: () =&gt; fakeRoute
        }
      ]
    }).compileComponents();
  }));

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

  it('should create', () =&gt; {
    component.actionLinks = [];
    expect(component).toBeTruthy();
  });
});
</code></pre>
",https://stackoverflow.com/questions/58737675/undefined-object-when-defined-in-angular-unit-testing,"['angular', 'unit-testing', 'jasmine']",328,True,0,1
Keeping Class Component methods pure by instead passing props or state as arguments,"<p>It's typical to access props/state from within Class Component methods as in <code>bar()</code> however, it's much nicer to unit test a more pure equivalent as in <code>foo()</code> as you don't have to repeatedly mock external state.</p>

<pre><code>foo(state, props) {
    // do something with state or props passed as argument

}

bar() {
    // do something with this.state or this.props directly
}
</code></pre>

<p>However something about having state/props available throughout a Class, but passing state/props as arguments in all methods which could be pure feels antithetical to the Component state/props typical usage patterns.</p>

<p>Is this the typical way of refactoring Class Component methods for easier unit testing, or am I missing some React functionality which does this behind the scenes?</p>
",https://stackoverflow.com/questions/57460019/keeping-class-component-methods-pure-by-instead-passing-props-or-state-as-argume,"['reactjs', 'jestjs', 'enzyme']",29,False,0,1
Excluding test folder from pom doesn&#39;t work,"<p>I have 2 sets of testing. One for junit tests and the other for db-unit testing. I want to execute only db-unit test cases in a separate phase like saying ""mvn integration-test"". </p>

<pre><code>junit test cases folder: bso
db-unit test cases folder: dao
</code></pre>

<p>But when I run ""mvn integration-test"", it will automatically run the junit test cases too. So I excluded that junit test case folder, which is called ""bso"". But still it will run the test cases inside the bso folder.
See my pom file here. How can I run the test cases ONLY in ""dao"" folder?</p>

<pre><code>     &lt;plugin&gt;
        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
        &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
        &lt;version&gt;2.22.0&lt;/version&gt;
        &lt;configuration&gt;
            &lt;trimStackTrace&gt;false&lt;/trimStackTrace&gt;
        &lt;/configuration&gt;
        &lt;executions&gt;
            &lt;execution&gt;
              &lt;id&gt;unit-tests&lt;/id&gt;
              &lt;phase&gt;test&lt;/phase&gt;
              &lt;goals&gt;
                 &lt;goal&gt;test&lt;/goal&gt;
              &lt;/goals&gt;
              &lt;configuration&gt;
                  &lt;skip&gt;true&lt;/skip&gt;
              &lt;/configuration&gt;
           &lt;/execution&gt;
           &lt;execution&gt;
              &lt;id&gt;integration-tests&lt;/id&gt;
              &lt;phase&gt;integration-test&lt;/phase&gt;
              &lt;goals&gt;
                 &lt;goal&gt;test&lt;/goal&gt;
              &lt;/goals&gt;
              &lt;configuration&gt;
                 &lt;skip&gt;false&lt;/skip&gt;
                 &lt;includes&gt;
                   &lt;include&gt;**/dao/**&lt;/include&gt;
                 &lt;/includes&gt;
                 &lt;excludes&gt;
                    &lt;exclude&gt;**/bso/**&lt;/exclude&gt;
                 &lt;/excludes&gt;
              &lt;/configuration&gt;
           &lt;/execution&gt;
        &lt;/executions&gt;
    &lt;/plugin&gt;
</code></pre>
",https://stackoverflow.com/questions/56763632/excluding-test-folder-from-pom-doesnt-work,"['maven', 'maven-3', 'pom.xml']",732,False,0,2
Add automatic test to package examples,"<p>Our package has a few example scripts that show how the package can be used.</p>

<p>Whenever we make a breaking change in my package, the examples may need to be updated. Right now I need to manually keep track of this, by checking whether the example scripts still run. Is there some way to add a test_examples function to my unit testing setup that doesn't assert the return value of a specific function, but simply runs all (or specific) files in the examples folder and checks that these scripts complete without error?</p>
",https://stackoverflow.com/questions/55593421/add-automatic-test-to-package-examples,"['python', 'python-3.x', 'pytest']",27,True,0,1
Entity Framework Core FromSql mock test cases,"<p>I am using EF Core non-entity model with get stored procedure calling. See below sample code</p>

<pre><code>context.Query&lt;ClassDTO&gt;().FromSql(""SpName @Param1, @Param2, @Param3"", 
                                  new SqlParameter[] { param1, param2, param3 }).ToList();
</code></pre>

<p>Code is working fine. But I need to write mock test cases.</p>

<p>Can anyone help me out? How to mock <code>Context.Query</code> or how to write test cases for this code?</p>

<p>I tried to implement the follow way:</p>

<p><a href=""https://nodogmablog.bryanhogan.net/2017/11/unit-testing-entity-framework-core-stored-procedures/"" rel=""nofollow noreferrer"">https://nodogmablog.bryanhogan.net/2017/11/unit-testing-entity-framework-core-stored-procedures/</a></p>

<p>But it will work for
 ** productContext.Products.MockFromSql(...)</p>

<p>But for me It is Like productContext.Query.MockFromSql(). So advice me how to write test cases.</p>

<p>Thanks in advance.</p>

<p>A Siva</p>
",https://stackoverflow.com/questions/56071216/entity-framework-core-fromsql-mock-test-cases,"['c#', '.net', 'entity-framework-core']",2888,True,0,1
Unit testing for spring boot RESTFUL Controller,"<p>I am trying to do unit testing for spring boot RESTFUL controller but I am receiving a null pointer exception. The application has a <code>StudentController</code> which depends on a <code>StudentService</code>. 
Here is the controller code: </p>

<pre><code>package com.demo.student.demo.controller;

import com.demo.student.demo.annotation.ApiDescription;
import com.demo.student.demo.entity.Student;
import com.demo.student.demo.entity.StudentDto;
import com.demo.student.demo.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = ""/v1/students"")
@Api(description = ""This is a general description for StudentController RESTFUL Controller"")
public class StudentController {

    private StudentService studentService;
    private ModelMapper modelMapper;

    public StudentController(ModelMapper modelMapper, StudentService studentService){
        this.studentService = studentService;
        this.modelMapper = modelMapper;
    }

    private StudentDto convertToDto(Student student) {
        StudentDto studentDto = modelMapper.map(student, StudentDto.class);
        return studentDto;
    }

    private Student convertToEntity(StudentDto studentDto) {
        Student student = modelMapper.map(studentDto, Student.class);
        return student;
    }

    @GetMapping
    @ApiOperation(""Returns a list of all students in the system."")
    @ApiDescription(""FIND_ALL_STUDENTS.md"")
    public List&lt;StudentDto&gt; findAll(){
        List&lt;Student&gt; students = studentService.findAl();
        return students.stream()
                .map(student -&gt; convertToDto(student))
                .collect(Collectors.toList());
    }

    @GetMapping(""/{id}"")
    @ApiOperation(""Returns a specific Student by his/her identifier. 404 if does not exist."")
    @ApiDescription(""FIND_STUDENT_BY_ID.md"")
    public StudentDto findById(@PathVariable(""id"") long id){
        return convertToDto(studentService.findById(id));
    }

    @PostMapping
    @ApiOperation(""Creates/Updates a new Student."")
    @ApiDescription(""SAVE_OR_UPDATE_STUDENT.md"")
    public StudentDto saveOrUpdate(@RequestBody StudentDto studentDto) {
        Student student = convertToEntity(studentDto);
        student.setUsername(student.getEmail() + ""----"" + student.getId());
        Student studentCreated = studentService.saveOrUpdate(student);
        return convertToDto(studentCreated);
    }

    @DeleteMapping(""/{id}"")
    @ApiOperation(""Deletes a Student from the system. 404 if the Student's identifier is not found."")
    @ApiDescription(""DELETE_STUDENT_BY_ID.md"")
    public void deleteById(@PathVariable(""id"") long id){
        studentService.deleteById(id);
    }

}
</code></pre>

<p>And here is the service implementation code: </p>

<pre><code>package com.demo.student.demo.service;

import com.demo.student.demo.entity.Student;
import com.demo.student.demo.exception.StudentNotFoundException;
import com.demo.student.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class StudentServiceImpl implements StudentService {

    private StudentRepository studentRepository;

    @Autowired
    public StudentServiceImpl(StudentRepository studentRepository){
        this.studentRepository = studentRepository;
    }

    @Override
    public List&lt;Student&gt; findAl() {
        return studentRepository.findAll();
    }

    @Override
    public Student findById(long id) {
        return  studentRepository.findById(id).orElseThrow(() -&gt; new StudentNotFoundException(id));
    }

    @Override
    public Student saveOrUpdate(Student student) {
        studentRepository.save(student);
        return student;
    }

    @Override
    public void deleteById(long id) {
        if(this.findById(id) != null)
            studentRepository.deleteById(id);
    }

}
</code></pre>

<p>And this is the test class for the controller: </p>

<pre><code>package com.demo.student.demo.controller;

import com.demo.student.demo.entity.Student;
import com.demo.student.demo.service.StudentService;
import com.demo.student.demo.service.StudentServiceImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
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 java.util.Arrays;
import java.util.List;

import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(StudentController.class)
class StudentControllerTest {

    private final static String URI = ""/v1/students"";

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private StudentService studentService;

    @Test
    void findAll() throws Exception {    
        // given
        Student student = new Student(1, ""test"", ""test@test.test"");
        List&lt;Student&gt; students = Arrays.asList(student);
        given(studentService.findAl()).willReturn(students);

        // when + then
        mockMvc.perform(get(URI))
                .andExpect(status().isOk())
                .andExpect(content().json(""[{'id':1,'email':'test@test.test'}]""));
    }

}
</code></pre>

<p>Here is also the pom.xml:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://maven.apache.org/POM/4.0.0""
         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.0.5.RELEASE&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
    &lt;groupId&gt;com.demo.student&lt;/groupId&gt;
    &lt;artifactId&gt;demo&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;name&gt;demo&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-actuator&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.h2database&lt;/groupId&gt;
            &lt;artifactId&gt;h2&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.postgresql&lt;/groupId&gt;
            &lt;artifactId&gt;postgresql&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&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.modelmapper/modelmapper --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.modelmapper&lt;/groupId&gt;
            &lt;artifactId&gt;modelmapper&lt;/artifactId&gt;
            &lt;version&gt;0.7.5&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.plugin&lt;/groupId&gt;
            &lt;artifactId&gt;spring-plugin-core&lt;/artifactId&gt;
            &lt;version&gt;1.2.0.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.springfox&lt;/groupId&gt;
            &lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt;
            &lt;version&gt;2.8.0&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.springfox&lt;/groupId&gt;
            &lt;artifactId&gt;springfox-swagger-ui&lt;/artifactId&gt;
            &lt;version&gt;2.8.0&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.springfox&lt;/groupId&gt;
            &lt;artifactId&gt;springfox-bean-validators&lt;/artifactId&gt;
            &lt;version&gt;2.8.0&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;javax.xml&lt;/groupId&gt;
            &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt;
            &lt;version&gt;2.1&lt;/version&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;dependency&gt;
            &lt;groupId&gt;org.javassist&lt;/groupId&gt;
            &lt;artifactId&gt;javassist&lt;/artifactId&gt;
            &lt;version&gt;3.25.0-GA&lt;/version&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.22.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.skyscreamer&lt;/groupId&gt;
            &lt;artifactId&gt;jsonassert&lt;/artifactId&gt;
            &lt;version&gt;1.5.0&lt;/version&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>When I run the test I receive a NULL POINTER EXCEPTION pointing to a code line in the <code>StudentController</code> class where the student service retrieves all the student data: <code>List&lt;Student&gt; students = studentService.findAl();</code></p>

<pre><code>java.lang.NullPointerException: null
    at com.demo.student.demo.controller.StudentController.findAll
</code></pre>

<p>Can anyone tell me what is the problem?</p>
",https://stackoverflow.com/questions/59051719/unit-testing-for-spring-boot-restful-controller,"['java', 'spring-boot', 'unit-testing', 'mockito', 'mockmvc']",1224,False,0,3
.NET Dependency Injection of Windows API,"<p>What's the right way of using Windows API with Dependency Injection best practices design? Since it interacts with the outside world, I need to abstract those calls to be able to mock them for unit testing.</p>

<p>Let's take these 2 functions.</p>

<pre><code>[DllImport(""user32.dll"")]
internal static extern IntPtr GetForegroundWindow();

[DllImport(""user32.dll"")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetForegroundWindow(IntPtr hWnd);
</code></pre>

<p>I can create a class WindowsApiService. But then these methods are static and I'm not supposed to expose static methods. I could also make them private and expose public methods that redirect to the static one, but then the method names will conflict.</p>

<p>What's the recommended way of handling this situation?</p>
",https://stackoverflow.com/questions/54248489/net-dependency-injection-of-windows-api,"['c#', '.net', 'dependency-injection']",73,False,0,0
Jasmine Global Variable initialization,"<p>I am writing Angular component unit testing using jasmine.
We are having class with static variables which is initialized during loading time of application.
Currently we are initializing those static variables in beforeAll of the unit test of component which uses those variable.</p>

<p><strong>Calling the same initialization function in all the unit test files seems redundant.</strong></p>

<p><strong>Is there any way to initialize those static variables globally during the beginning of jasmine unit test which can be available to all the unit test suits ?</strong></p>

<p>Currently we are initializing those static variable like this :</p>

<pre><code>describe(('mycomponent'), () =&gt; {
  beforeAll(()=&gt;{
   // call to initialize function
  });
});
</code></pre>
",https://stackoverflow.com/questions/54341919/jasmine-global-variable-initialization,"['angular', 'unit-testing', 'jasmine', 'angular-unit-test']",948,False,0,1
Junit mocking error : org.mockito.exceptions.misusing.MissingMethodInvocationException,"<p>I am using <code>spring data JPA</code> for creating services and for unit testing I am using <code>Junit</code> and <code>mockito</code>. In following code I am trying to do junit testing for service class.</p>

<p>Room account mapping service class is dependent on Room Investigator mapping service class so I used mockito for mocking room Investigator mapping service class method but that method calling one more method of same class.</p>

<p>I tried like below but I am getting error in mockito. Can any one please tell me how I can do mocking?</p>

<p><strong>TestRoomAccountMappingService class</strong></p>

<pre><code>public class TestRoomAccountMappingService {
    @MockBean
    RoomAccountMappingRepository roomAccountMapRepository;

    @Autowired
    RoomAccountMappingService roomAccountMappingService;

    @Autowired
    RoomInvestigatorMappingService roomInvestMapService;

    @Test
    public void deleteAccountMapping() {

        Integer[] RoomAllocationId= {1839};         

        //here getting error
        Mockito.when(roomInvestMapService.returnRoomWithinClusterByRoomAllocationID(1839)).thenReturn(RoomAllocationId);

        RoomAccountMapping roomAcctMap= new RoomAccountMapping();
        roomAcctMap.setnRoomAllocationId(1);

        List&lt;RoomAccountMapping&gt; roomList= new ArrayList&lt;&gt;();
        roomList.add(roomAcctMap);      

        Mockito.when(roomAccountMapRepository.findByNRoomAllocationId(1839)).thenReturn(roomList);

        Boolean actual = roomAccountMappingService.deleteAccountMapping(1839);

        assertEquals(true, actual );
    }
}
</code></pre>

<p><strong>Failure Trace</strong></p>

<pre><code>org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

    at com.spacestudy.service.TestRoomAccountMappingService.deleteAccountMapping(TestRoomAccountMappingService.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
</code></pre>
",https://stackoverflow.com/questions/54920697/junit-mocking-error-org-mockito-exceptions-misusing-missingmethodinvocationexc,"['junit', 'spring-data-jpa', 'mockito']",457,True,0,1
Sqlite keep in memory database open until jvm exit,"<p>I'd like to keep an in memory sqlite database, but without attached connections.</p>

<p>I'm unit testing a web app, so in the @BeforeAll method I do some initialization and then, in the various test methods, do some DDL manipulation.</p>

<p>Of course, when the last open connection is closed, sqlite in memory db is teared down, breaking my tests.</p>

<p>I achieved to keep a H2 in memory database open till the JVM lives, doing this</p>

<pre><code>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
</code></pre>

<p>But I can't find an alternative for sqlite.
I tried with </p>

<pre><code>jdbc:sqlite::memory:&amp;cache=shared
</code></pre>

<p>But doesn't seem to work.</p>

<p>Is it possible?</p>
",https://stackoverflow.com/questions/56363640/sqlite-keep-in-memory-database-open-until-jvm-exit,"['java', 'sqlite']",471,False,0,1
I am getting TypeError undefined for property &#39;false&#39; in my unit test results,"<p>I am learning unit testing with mocha and chai. I have most tests passing but 1 test failing with TypeError: cannot read property 'false' of undefined.</p>

<p>I tried adding a third parameter 'input[2]' when calling adder but I still get the same error. </p>

<pre><code>const adder = (a, b) =&gt; {
  if (!(typeof a === 'number' &amp;&amp; typeof b === 'number')) {
    throw Error('Oh no!');
  }
  return a + b;
}

module.exports = adder;


const expect = require('chai').expect;
const adder = require('../adder');

describe('adder', () =&gt; {
  it('should add two numbers', () =&gt; {
    const useCases = [
      {
        a: 2,
        b: 3,
        expected: 5
      },
      {
        a: 100,
        b: 1000,
        expected: 1100
      },
      {
        a: 10,
        b: -15,
        expected: -5
      }
    ];

    useCases.forEach(function (input) {
      const answer = adder(input.a, input.b);
      expect(answer).to.equal(input.expected);
    });
  });

  it('should give error if input not numbers', function () {
    const notNumbers = [
      ['a', 1,]
      ['b', 2]
      [2, false]
    ];
    notNumbers.forEach(function (input) {
      expect(function () {
        adder(input[0], input[1]);
      }).to.throw(Error);
    });
  });
});
</code></pre>

<p>Part of the expected result is passing, 'it adds two numbers'
adder
    √ should add two numbers
    1) should give error if input not numbers</p>

<p>1) adder
       should give error if input not numbers:
     TypeError: Cannot read property 'false' of undefined
      at Context. (test\test-adder.js:34:7)</p>
",https://stackoverflow.com/questions/56191133/i-am-getting-typeerror-undefined-for-property-false-in-my-unit-test-results,"['node.js', 'mocha.js', 'chai']",25,False,0,0
How to unit test a KinesisRecord-based DoFn?,"<p>I’m getting started on a Beam project that reads from AWS Kinesis, so I have a simple DoFn that accepts a KinesisRecord and logs the contents. I want to write a unit test to run this DoFn and prove that it works. Unit testing with a KinesisRecord has proven to be challenging, though.</p>

<p>I get this error when I try to just use <code>Create.of(testKinesisRecord)</code>:</p>

<pre><code>java.lang.IllegalArgumentException: Unable to infer a coder and no Coder was specified. Please set a coder by invoking Create.withCoder() explicitly  or a schema by invoking Create.withSchema().
</code></pre>

<p>I have tried providing the KinesisRecordCoder explicitly using ""withCoder"" as the error suggests, but it’s a private class. Perhaps there's another way to unit test a DoFn?</p>

<p>Test code:</p>

<pre><code>public class MyProjectTests {
    @Rule
    public TestPipeline p = TestPipeline.create();

    @Test
    public void testPoC() {
        var testKinesisRecord = new KinesisRecord(
                ByteBuffer.wrap(""SomeData"".getBytes()),
                ""seq01"",
                12,
                ""pKey"",
                Instant.now().minus(Duration.standardHours(4)),
                Instant.now(),
                ""MyStream"",
                ""shard-001""
        );


        PCollection&lt;Void&gt; output =
                p.apply(Create.of(testKinesisRecord))
                        .apply(ParDo.of(new MyProject.PrintRecordFn()));

        var result = p.run();
        result.waitUntilFinish();
        result.metrics().allMetrics().getCounters().forEach(longMetricResult -&gt; {
            Assertions.assertEquals(1, longMetricResult.getCommitted().intValue());
        });
    }
}
</code></pre>

<p>DoFn code:</p>

<pre><code>  static class PrintRecordFn extends DoFn&lt;KinesisRecord, Void&gt; {
    private static final Logger LOG = LoggerFactory.getLogger(PrintRecordFn.class);
    private final Counter items = Metrics.counter(PrintRecordFn.class, ""itemsProcessed"");

    @ProcessElement
    public void processElement(@Element KinesisRecord element) {
      items.inc();

      LOG.info(""Stream: `{}` Shard: `{}` Arrived at `{}`\nData: {}"",
              element.getStreamName(),
              element.getShardId(),
              element.getApproximateArrivalTimestamp(),
              element.getDataAsBytes());
    }
  }
</code></pre>
",https://stackoverflow.com/questions/58825879/how-to-unit-test-a-kinesisrecord-based-dofn,"['java', 'apache-beam', 'amazon-kinesis-analytics']",970,True,0,1
How to access the @ContentChildren in the spec file?,"<p>I am testing a component that has a query list of <code>@ContentChildren</code>. In my component these are accessible in the 'AfterContentInit` life cycle hook. But, when i intend to access the same in my spec file, my query list return me with an empty arrays. </p>

<p>I am trying to test the component <strong>without creating any mock component</strong> as it is done in this <a href=""https://stackoverflow.com/questions/38479704/angular-2-unit-testing-component-mocking-contentchildren"">link</a>. I have tried the solution provided in the link below but that didn't work for me.</p>

<p><a href=""https://stackoverflow.com/questions/42724179/angular-2-unit-testing-viewchild-is-undefined"">Angular 2 unit testing - @ViewChild is undefined</a></p>

<p><strong>In my Component:</strong></p>

<pre><code>    @ContentChildren(GetTemplateDirective) public templates: QueryList&lt;GetTemplateDirective&lt;AccordionTemplate&gt;&gt;;
</code></pre>

<p><strong>In the component's spec file:</strong></p>

<pre><code>    it('should show the custom icon when the external template is passed', async(function () {
       accordionFixture.detectChanges();
       accordionComponent.ngAfterContentInit();
       console.log(accordionComponent.templates);
       expect(component.templates.toArray().length).toBeGreaterThan(0);
    }));
</code></pre>
",https://stackoverflow.com/questions/54148795/how-to-access-the-contentchildren-in-the-spec-file,"['angular', 'jasmine', 'karma-runner']",518,False,0,1
Connecting CppUTest to C Interface,"<p>I'm using CppUTest to handle unit testing with my C library. However, I'm having an issue when compiling the test file.</p>

<p>Here's my <code>Makefile</code> (The <code>CPPUTEST_HOME</code> var is an environment variable):</p>

<pre><code>CPPFLAGS += -I$(CPPUTEST_HOME)/include
CXXFLAGS += -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorNewMacros.h
CFLAGS += -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorMallocMacros.h
LD_LIBRARIES = -L$(CPPUTEST_HOME)/lib -lCppUTest -lCppUTestExt

all:
        c++ -g -Wall $(CPPFLAGS) $(CXXFLAGS) $(CFLAGS) commonTest.cpp -o commonTest $(LD_LIBRARIES)

clean:
        rm -rf *.dSYM commonTest
</code></pre>

<p>When I run <code>make</code>, the following output is given:</p>

<pre><code>Undefined symbols for architecture x86_64:
  ""_test_common_algos_commonCalloc_wrapper_c"", referenced from:
      TEST_common_algos_commonCalloc_Test::testBody() in commonTest-992552.o
  ""_test_common_algos_commonMalloc_wrapper_c"", referenced from:
      TEST_common_algos_commonMalloc_Test::testBody() in commonTest-992552.o
  ""_test_common_algos_commonRealloc_wrapper_c"", referenced from:
      TEST_common_algos_commonRealloc_Test::testBody() in commonTest-992552.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: *** [all] Error 1
</code></pre>

<p>To me, this seems like a linking problem. However, I don't think I've done anything wrong according to <a href=""https://cpputest.github.io/manual.html#c_interface"" rel=""nofollow noreferrer"">the manual</a>:</p>

<p><code>commonTest.c</code>:</p>

<pre><code>#include ""../common.h""
#include ""CppUTest/TestHarness_c.h""

void *ptr = NULL;
int list[10] = {1, 2, 32, 33, 2, 5, 7, 3, 9, 34};

TEST_GROUP_C(common_algos)
{

};

TEST_C(common_algos, commonMalloc)
{
  ptr = malloc_c(6);
  CHECK_EQUAL_C_INT(algos_error, ALGOS_OK);
  strncpy(ptr, ""Hello"", 5);
  CHECK_EQUAL_C_STRING(""Hello"", ptr);
  free_c(ptr);
}

TEST_C(common_algos, commonCalloc)
{
  ptr = calloc_c(sizeof(int), 10);
  CHECK_EQUAL_C_INT(algos_error, ALGOS_OK);
  memcpy(ptr, list, sizeof(int)*10);
  for (int i = 0; i &lt; 10; i++)
      CHECK_EQUAL_C_INT(list[i], ptr[i]);
  free_c(ptr);
}

TEST_C(common_algos, commonRealloc)
{
  ptr = malloc_c(10);
  CHECK_EQUAL_C_INT(ALGOS_OK, algos_error);
  memcpy(ptr, list, sizeof(int)*10);
  ptr = realloc_c(ptr, 20);
  CHECK_EQUAL_C_INT(ALGOS_OK, algos_error);
  memcpy(ptr + 10, list, sizeof(int)*10);
  for (int i = 9; i &lt; 19; i++)
      CHECK_EQUAL_C_INT(list[i-9], ptr[i]);
  free_c(ptr);
}
</code></pre>

<p><code>commonTest.cpp</code>:</p>

<pre><code>#include ""CppUTest/CommandLineTestRunner.h""
#include ""CppUTest/TestHarness_c.h""

TEST_GROUP_C_WRAPPER(common_algos)
{

};

TEST_C_WRAPPER(common_algos, commonMalloc);
TEST_C_WRAPPER(common_algos, commonCalloc);
TEST_C_WRAPPER(common_algos, commonRealloc);


int main(int ac, char **av)
{
 return RUN_ALL_TESTS(ac, av);
}
</code></pre>

<p>Lastly, my directory structure:</p>

<pre><code>common
  |______ common.c
  |
  |______ common.h
  |
  |______ test
           |
           |____commonTest.c
           |
           |____commonTest.cpp
</code></pre>

<p>For some context, I'm not a C++ programmer, and I'm not experienced with using CppUTest, so bear with me.</p>

<p>Thanks for any help and feel free to ask questions.</p>
",https://stackoverflow.com/questions/55251920/connecting-cpputest-to-c-interface,"['c++', 'c', 'cpputest']",435,False,0,0
Visual Studio: Load SQL file from SQL Studio Unit Test,"<p>I am trying to set up a Microsoft Visual Studio Unit Testing environment for some of my SQL queries.  My scenario is somewhat backwards to the typical software development scenario.  For any given work product that I work on, I am trying to exercise <strong>ONE</strong> query through different scenarios, by passing in different parameters and comparing results.</p>

<p>My intention is to load my SQL query from a .sql file in each of my unit tests.</p>

<p><strong>How do I open my SQL file for reading from within my <code>SqlServerUnitTest1.cs</code> file?</strong></p>
",https://stackoverflow.com/questions/55481493/visual-studio-load-sql-file-from-sql-studio-unit-test,"['visual-studio-2013', 'sql-server-data-tools']",81,True,0,1
How To Unit Test PostgreSQL C-Language Functions,"<p>I am developing a user defined function for PostgreSQL in C. This function will be used as part of a user defined aggregate. I am following the documentation on <a href=""https://www.postgresql.org/docs/11/xaggr.html"" rel=""nofollow noreferrer"">User-defined Aggregates</a> and <a href=""https://www.postgresql.org/docs/11/xfunc-c.html"" rel=""nofollow noreferrer"">C-Language Funtions</a>. I am aware of the extension building infrastructure that a PostgreSQL installation provides, documented <a href=""https://www.postgresql.org/docs/11/extend-pgxs.html"" rel=""nofollow noreferrer"">here</a> , which also provides a means of testing the extension. However, to ease the development of PostgreSQL extensions, I was wondering if there is any way to test the user function using regular C unit testing techniques. </p>

<p>I am trying to use CMocka for my unit testing. This is complicated by the<code>PG_FUNCTION_ARGS</code> and <code>PG_FUNCTION_INFO_V1</code> macros from <code>fmgr.h</code> that are needed for <code>C</code> functions that will be interfacing with PostgreSQL. These macros tend to abstract some of the parameter handling and as a result obfuscate this functionality. As a result, I am having difficulty calling my PostgreSQL user function in a unit test. The errors I am having are related to the expected parameter types. I'm not sure how to manually construct a parameter list via the macros for my function. Below are the GCC errors I get when I try to run my unit test.</p>

<pre><code>    gcc -fprofile-arcs -ftest-coverage -I '/usr/include/postgresql/10/server' ./tests/test_max_pos_min_neg.c -o ./build/tests/test_max_pos_min_neg
./tests/test_max_pos_min_neg.c: In function ‘test_get_max_pos_min_neg’:
./tests/test_max_pos_min_neg.c:21:25: warning: passing argument 1 of ‘get_max_pos_min_neg’ from incompatible pointer type [-Wincompatible-pointer-types]
     get_max_pos_min_neg((float4 *) init_cond, 10.0, -2.5, 7.5);
                         ^
In file included from ./tests/test_max_pos_min_neg.c:6:0:
./tests/../src/max_pos_min_neg.h:8:7: note: expected ‘FunctionCallInfo {aka struct FunctionCallInfoData *}’ but argument is of type ‘float4 * {aka float *}’
 Datum get_max_pos_min_neg(PG_FUNCTION_ARGS);
       ^~~~~~~~~~~~~~~~~~~
./tests/test_max_pos_min_neg.c:21:5: error: too many arguments to function ‘get_max_pos_min_neg’
     get_max_pos_min_neg((float4 *) init_cond, 10.0, -2.5, 7.5);
     ^~~~~~~~~~~~~~~~~~~
In file included from ./tests/test_max_pos_min_neg.c:6:0:
./tests/../src/max_pos_min_neg.h:8:7: note: declared here
 Datum get_max_pos_min_neg(PG_FUNCTION_ARGS);
       ^~~~~~~~~~~~~~~~~~~
./tests/test_max_pos_min_neg.c:24:5: warning: implicit declaration of function ‘assert_float_equal’; did you mean ‘assert_int_equal’? [-Wimplicit-function-declaration]
     assert_float_equal(init_cond[0], 10.0, EPSILON);
     ^~~~~~~~~~~~~~~~~~
     assert_int_equal
Makefile:59: recipe for target 'build/tests/test_max_pos_min_neg' failed
make: *** [build/tests/test_max_pos_min_neg] Error 1
</code></pre>

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

<pre><code>#include ""postgres.h""
#include ""fmgr.h""
#include ""utils/array.h""

PG_MODULE_MAGIC;

Datum get_max_pos_min_neg(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(get_max_pos_min_neg);

// Computes the maximum positive and mininum negative sentiment scores.
Datum
get_max_pos_min_neg(PG_FUNCTION_ARGS)
{
    ArrayType *state_array;
    float4 *state;
    float4 pos, neg, score;

    state_array = PG_GETARG_ARRAYTYPE_P(0);
    pos = PG_GETARG_FLOAT4(1);
    neg = PG_GETARG_FLOAT4(2);
    score = PG_GETARG_FLOAT4(3);

    state = (float4 *) ARR_DATA_PTR(state_array);

    if (state[2] &lt; score)
    {
        state[0] = pos;
        state[1] = neg;
        state[2] = score;
    }
    if (score &lt; state[5])
    {
        state[3] = pos;
        state[4] = neg;
        state[5] = score;
    }
    PG_RETURN_ARRAYTYPE_P(state);
}
</code></pre>

<p>My header file:</p>

<pre><code>#include ""postgres.h""
#include ""fmgr.h""
#include ""utils/array.h""

Datum get_max_pos_min_neg(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(get_max_pos_min_neg);
</code></pre>

<p>My unit test:</p>

<pre><code>#include ""../src/max_pos_min_neg.h""
#include &lt;stdarg.h&gt;
#include &lt;stddef.h&gt;
#include &lt;setjmp.h&gt;
#include ""cmocka.h""

const float4 EPSILON = 0.001;

void 
test_get_max_pos_min_neg(void **state)
{
    (void) state; /* unused */
    // This is the initial condition used by the SQL stored procedure
    float4 init_cond[] = {0, 0, -1, 0, 0, 100};

    get_max_pos_min_neg(init_cond, 10.0, -2.5, 7.5);

    // init_cond should now be {10.0, -2.5, 7.5, 10.0, -2.5, 7.5}
    assert_float_equal(init_cond[0], 10.0, EPSILON);
    assert_float_equal(init_cond[1], -2.5, EPSILON);
    assert_float_equal(init_cond[2], 7.5, EPSILON);
    assert_float_equal(init_cond[3], 10.0, EPSILON);
    assert_float_equal(init_cond[4], -2.5, EPSILON);
    assert_float_equal(init_cond[5], 7.5, EPSILON);
}

const struct CMUnitTest tests[] = { 
    cmocka_unit_test(test_get_max_pos_min_neg)
};

int 
main(void)
{
    return cmocka_run_group_tests(tests, NULL, NULL);
}
</code></pre>

<p>Any help you can provide on how to unit test PostgreSQL C-Language functions outside of PostgreSQL would be much appreciated. Thank you!</p>
",https://stackoverflow.com/questions/55480318/how-to-unit-test-postgresql-c-language-functions,"['c', 'postgresql', 'unit-testing']",449,True,1,1
Unit Testing Domain Models attributes in CQRS System,"<p>I'm seeking other's thoughts on a specific scenario re: unit testing domain model (entities, VOs etc) attributes in a App that is utilising CQRS.</p>

<p>Imagine a simplified example of a Product (entity), with a Product Name (VO).</p>

<pre><code>class Product
private ProductName productName
</code></pre>

<p>Product has some basic guard rails and invariants:</p>

<ul>
<li>A Product Name can't be more than 100 characters (enforced in the VO).</li>
<li>A Product must have a Product Name (enforced in the entity, with Product Name set in the constructor to ensure it's always valid).</li>
</ul>

<p>I can unit test the Product entity and Product Name VO to ensure these are enforced correctly by ensuring the correct errors and exceptions are raised. Easy.</p>

<p>My question is regarding Unit Testing the happy path — that the Product Name is set successfully when a Product is initially Developed.</p>

<p>In a non-CQRS system I would have a public read-only property or getter on the Product Name, so that it can be retrieved for reporting, displaying or populating a DTO. I can then unit test with this property.</p>

<p>In a CQRS system though, the Product Name can be private in the Entity, as retrieval of the Product Name happens via the Read Model on the query side. Setting the Product Name happens through the command when the product is Developed, but after that the Product Name isn't required for any core business actions (except I could imagine for renaming the product).</p>

<p>To unit test the successful creation of a product though I need to make the Product Name a read-only public property to test it, but it doesn't seem right to do this just to fulfil a unit test. Without the unit test the Product Name can remain private and everything would work as needed. </p>

<p>Wondering if anyone has come across a similar scenario for unit testing -> Where an attribute that is mostly for presentation purposes (although obviously very important... I wouldn't expect users to try and work with Products via only part numbers or identifiers) is being tested?</p>

<p>I'm leaning towards testing this via the Read Model? ie. Create the Product , then determine the name has been successfully set via the Read Model. But this seems to be a lot for a unit test to take on.</p>
",https://stackoverflow.com/questions/54185538/unit-testing-domain-models-attributes-in-cqrs-system,"['unit-testing', 'domain-driven-design', 'cqrs', 'accessor']",438,True,1,1
How to test onclick api call with react,"<p>I have 3 react components and when the user clicks on USER_CARD in header then an api is called and the response is displayed in TwitterList component. I have no experience with unit testing, so what are the unit test needs to be done and how? I have read about enzyme and jest but not sure about the implementation.</p>

<p>Fews things I understand here that I need to test the click and also check if the api is responding with any data or not.</p>

<p>Please help me understand how to do this?</p>

<pre><code>    import React ,{Component}from 'react'

    // Import all contianers here
    import Header from './containers/header'
    import TweetList from './containers/tweetlist'

    // Import all services here
    import Http from './services/http'

    import './App.css'

    class App extends Component {

      constructor() {
        super()

        this.state = {
          data: [],
          isTop: true,
          userName: ''
        }
      }

      _getUserTweets = (user) =&gt; {
        console.log(user)
        if (user !== undefined &amp;&amp; user !== '') {
          Http.get('/' + user)
          .then(response =&gt; {
            if (response.data.length &gt; 0) {
              this.setState((prevState) =&gt; {
                return {
                  ...prevState,
                  data: response.data,
                  userName: user
                }
              })
            }
          })
          .catch(error =&gt; {
            console.log(error)
          })
        } else {
          console.log('No user found!!')
        }
      }

      render() {
        const {data, userName} = this.state
        return (
          &lt;div className=""app_container""&gt;
            &lt;Header getUserTweets={this._getUserTweets} /&gt;
            &lt;TweetList data={data} user={userName} /&gt;
          &lt;/div&gt;
        );
      }
    }

    export default App;



    import React, {Component} from 'react'

    class TweetList extends Component {

        constructor() {
            super()

            this.state = {
                tweets: []
            }
        }

        componentWillReceiveProps(nextProps) {

            if (nextProps.data.length &gt; 0) {
                this.setState((prevState) =&gt; {
                    return {
                        ...prevState,
                        tweets: nextProps.data
                    }
                })
            }
        }

        render() {
            const {tweets} = this.state
            return (
                &lt;div&gt;
                    {
                        tweets.length &gt; 0
                        &amp;&amp;
                        tweets.map((currentValue, index) =&gt; {
                            return (
                                &lt;p&gt;{currentValue.full_text}&lt;/p&gt;
                            )
                        })
                    }
                &lt;/div&gt;
            )
        }
    }

    export default TweetList



    import React, {Component} from 'react'
    import './style.css'

    const USER_CARD = ({userName, onClickHandler}) =&gt; {
        return (
            &lt;p onClick={() =&gt; onClickHandler(userName)}&gt;{userName}&lt;/p&gt;
        )
    }

    class Header extends Component {

        componentWillMount() {
            if (process.env.REACT_APP_USER_LIST !== undefined &amp;&amp; process.env.REACT_APP_USER_LIST.split(',').length &gt; 0) {
                this.props.getUserTweets(process.env.REACT_APP_USER_LIST.split(',')[0])
            }
        }

        _getUserTweets = (userName) =&gt; {
            this.props.getUserTweets(userName)
        }

        render() {
            return(
                &lt;div className=""header_container""&gt;
                    {process.env.REACT_APP_USER_LIST !== undefined
                    &amp;&amp;
                    process.env.REACT_APP_USER_LIST.split(',').length &gt; 0
                    &amp;&amp;
                    process.env.REACT_APP_USER_LIST.split(',')
                    .map((currentValue, index) =&gt; {
                        return (
                            &lt;USER_CARD userName={currentValue} key={`user-card-${index}`}
                                onClickHandler={this._getUserTweets} /&gt;
                        )
                    })}
                &lt;/div&gt;
            )
        }
    }

    export default Header

If the user click on the USER_CARD in Header component then we call an api to get the results.

What are the different unit testing that I can do and how to do it? 
</code></pre>
",https://stackoverflow.com/questions/57395013/how-to-test-onclick-api-call-with-react,"['reactjs', 'jestjs', 'enzyme']",2153,True,0,1
How to mock a module variable with jest and typscript,"<p>I have a map defining some transformation functions like this </p>

<pre><code>export const transformFuncMap: { [key: string]: (args: TransformFunctionArgs) =&gt; Promise&lt;any&gt; } = {
    [TransformationType.UNZIP]: unzipArchiveAndUploadToS3,
    // tslint:disable-next-line: no-empty
    [TransformationType.NOOP]: async () =&gt; {},
};
</code></pre>

<p>Later my in the same module I  have a handle function that calls these based on some seq I provide. </p>

<pre><code>function handle(funcKeys: TransformationType[]) {
   for(const funcKey of funcKey) {
       await transformFuncMap[funcKey](); 
   }
}
</code></pre>

<p>When unit testing handle. All I care is that some function are called in an order I provide. I dont want to run the function implementations. </p>

<p>Is there anyway with jest to just mock out the <code>transformFuncMap</code>, with something like this. </p>

<pre><code>export const transformFuncMap: { [key: string]: (args: TransformFunctionArgs) =&gt; Promise&lt;any&gt; } = {
    [TransformationType.UNZIP]:jest.fn(),
    // tslint:disable-next-line: no-empty
    [TransformationType.NOOP]: jest.fn(),
};
</code></pre>

<p>I would like to be able to do this without resorting to some Java style dependency injection in the parameters. </p>
",https://stackoverflow.com/questions/59383743/how-to-mock-a-module-variable-with-jest-and-typscript,"['javascript', 'typescript', 'jestjs']",338,True,0,1
tns test android hangs after synced to device,"<p>I'm currently trying to setup unit testing on my nativescript project. I'm using mocha with chai as my testing framework and have run <code>tns test init</code> all ok.</p>

<p>When I run <code>tns test android</code> every runs ok and the emulator starts. However, after it has synced the application to my emulator, which also starts ok, it hangs at:</p>

<pre><code>JS: NSUTR: fetching http://***.***.**.*:9876/context.json
JS: NSUTR: fetching http://***.***.*.**:9876/context.json
JS: NSUTR: fetching http://127.0.0.1:9876/context.json
</code></pre>

<p>I've tried a few different things, on being running <code>tns test android --debug-brk</code> to see where it fails. This says that  <code>Error: Could not find device by specified identifier 'undefined'</code> but the emulator is running fine as the command had started it up and I can see the emulator using <code>tns device</code>.</p>

<p>Any help is much appreciated, thanks.</p>
",https://stackoverflow.com/questions/54108116/tns-test-android-hangs-after-synced-to-device,"['typescript', 'mocha.js', 'nativescript']",115,True,0,1
Observe ReactiveObject.Changed of inherited class may or may not work,"<p>I try to create a base class, which inherits from ReactiveObject.
This class needs to check if any property, including properties of further inheritations, has changed.</p>

<p>My main problem is, that I can't get any reliable testresults!
The provided test MAY be green. Running it with VS Live Unit Testing, brings it in red. Moving the classes out of the testproject into a library may or may not get this test green.</p>

<p>So far, the only way to keep it green, is to uncomment this line in the inherited class.</p>

<pre><code>//  Changed.Subscribe(Console.WriteLine);
</code></pre>

<pre><code>   [TestClass]
   public class StateBaseTests
   {
      #region Tests

      [TestMethod]
      public void State_ChangesToChanged_PropertyChanged()
      {
         var _item = new MyTest();

         _item.Surname = ""Testname"";

         Assert.AreEqual(Statetype.Changed, _item.State);
      }

      #endregion

      #region SubClasses

      public enum Statetype
      {
         Added,
         Changed,
         Deleted,
         Detached,
         Unchanged
      }

      public abstract class StateBase : ReactiveObject
      {
         protected StateBase()
         {
            State = Statetype.Unchanged;

            Changed.Select(prop =&gt; prop.PropertyName)
                   .Subscribe(UpdateZustand);
         }

         protected void UpdateZustand(string propertyName)
         {
            if(State == Statetype.Unchanged)
               State = Statetype.Changed;
         }

         [Reactive]
         public Statetype State { get; set; }
      }

      private class MyTest : StateBase
      {
         public MyTest()
         {
            //  Changed.Subscribe(Console.WriteLine);
         }

         [Reactive]
         public string Name { get; set; }

         [Reactive]
         public string Surname { get; set; }
      }
   }
</code></pre>
",https://stackoverflow.com/questions/58292333/observe-reactiveobject-changed-of-inherited-class-may-or-may-not-work,"['c#', 'testing', 'reactiveui']",156,False,0,1
How to use &#39;application object&#39; in androidTest cases? - Android,"<p>I am writing test cases in <strong>androidTest</strong> &amp; my code has <code>Pattern.EMAIL_ADDRESS</code>, as in unit test cases I can't have access to Android framework classes &amp; also I am not using <strong>Roboelectric</strong> for the unit testing.</p>

<p>I am getting <code>NullPointerException</code> for application object, as in my <code>ResetPasswordViewModel</code> I am using this <code>application</code> object to get the String value form <code>string.xml</code>.
Even I have mocked <code>@Mock Application application</code>, but still it returns null. I have tried to use <code>InstrumentationRegistry.getTargetContext()</code> but still nothing's work.</p>

<p>Am I missing something? What could be the issue?</p>

<p>How to use <code>application</code> object in <strong>androidTest</strong> cases?
Please refer the below code:</p>

<pre><code>@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ResetPasswordUnitTestsInt {

ResetPasswordViewModel resetPasswordViewModel;
@Rule
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();
@Mock
Application application;
@Mock
Patterns patterns;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    resetPasswordViewModel = new ResetPasswordViewModel(application);
}

@Test
public void a_testEmailIdFieldNegativeCase() {
    resetPasswordViewModel.userName.setValue("""");
    resetPasswordViewModel.setErrorVisibilityIfBlankField();
    Assert.assertEquals(true, resetPasswordViewModel.userNameErrorVisibility.getValue());
}
}
</code></pre>

<p><a href=""https://i.stack.imgur.com/3rBcL.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/3rBcL.png"" alt=""NulllPointerError""></a></p>

<p><strong>Gradle</strong></p>

<pre><code>apply plugin: 'com.android.application'

android {
compileSdkVersion 28
defaultConfig {
    applicationId ""com.test.newtest""
    minSdkVersion 19
    targetSdkVersion 28
    versionCode 2
    versionName ""1.1""
    multiDexEnabled true
    testInstrumentationRunner 
 ""android.support.test.runner.AndroidJUnitRunner""
}

dataBinding {
    enabled = true
}

testOptions {
    unitTests.returnDefaultValues = true
}

testOptions {
    unitTests {
        includeAndroidResources = true
    }
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android- 
optimize.txt'), 'proguard-rules.pro'
    }
}

}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
def design = ""28.0.0""
implementation ""com.android.support:appcompat-v7:$design""
implementation ""com.android.support:design:$design""
implementation ""com.android.support:recyclerview-v7:$design""

implementation 'com.android.support.constraint:constraint- 
layout:1.1.3'
implementation 'com.android.support:support-v4:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso- 
core:3.0.2'

implementation ""android.arch.core:core-testing:1.1.1""
//testImplementation ""android.arch.core:core-testing:1.1.1""


// reactive
implementation 'io.reactivex.rxjava2:rxjava:2.1.9'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test:rules:1.0.2'
androidTestImplementation 'com.squareup.retrofit2:retrofit-mock:2.0.0'
implementation 'com.squareup.okhttp3:mockwebserver:3.8.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-intents:3.0.2'
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

def daggerVer = 2.16
implementation ""com.google.dagger:dagger:$daggerVer""
annotationProcessor ""com.google.dagger:dagger-compiler:$daggerVer""
compileOnly 'javax.annotation:jsr250-api:1.0'
implementation 'javax.inject:javax.inject:1'

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

//implementation 'com.google.android.material:material:1.0.0'

def lifeCycle = ""1.1.1""
implementation ""android.arch.lifecycle:extensions:$lifeCycle""
/*implementation ""android.arch.lifecycle:runtime:$lifeCycle""
annotationProcessor ""android.arch.lifecycle:compiler:$lifeCycle""*/
implementation ""android.arch.persistence.room:runtime:$lifeCycle""
implementation 'com.mikhaellopez:circularimageview:3.2.0'
annotationProcessor 
""android.arch.persistence.room:compiler:$lifeCycle""

implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.android.support:multidex:1.0.3'

implementation 'commons-beanutils:commons-beanutils:1.9.3'
implementation 'org.mockito:mockito-core:2.23.4'
androidTestImplementation 'org.mockito:mockito-android:2.18.3'
}
</code></pre>
",https://stackoverflow.com/questions/56119881/how-to-use-application-object-in-androidtest-cases-android,"['android', 'mockito', 'android-testing']",474,True,0,1
Spring boot best practises,"<p>I have a spring boot application that reads from an excel document. This is currently being done by a service that my controller uses.</p>

<p>Currently the path of the document is hard coded in the Service class. I would like to know, if this is the best way to do it.</p>

<p>I would also like to know the best practises for unit testing my code. How do I ensure that I have no dependency with the actual file. My helper method is private. I am having troubles mocking it. </p>
",https://stackoverflow.com/questions/58826283/spring-boot-best-practises,"['spring-boot', 'junit', 'mojito']",65,False,-1,2
Need advice on unit testing method which is using &quot;dozer.map&quot; method,"<p>I have an empModel and empDto object. In an spring boot app, I am making a service call to get employee model by Id. In the method, empModel is obtained from database by making a service call. Dozermapper populates the DTO and returns the dto. DozerMapper is injected to the controller . </p>

<p>Facing difficulty in unit testing the method. 
I am able to mock the service using when/thenReturn. However, I am unable to mock the dozerMapper as its a method with void return. What would be the right approach to unit test the method? </p>

<pre><code>  @Inject
  public Controller(DozerBeanMapper dozerBeanMapper, EmployeeService service){
    this.dozerBeanMapper = dozerBeanMapper;
    this.service = service;
  }

  @GetMapping(""/{id}"")
  public EmpDto getEmployeeById(@PathVariable long id){
    EmpModel empModel = service.getEmployeeById(id);
    EmpDto empDto = new EmpDto();
    dozerBeanMapper.map(empModel,empDto);
    return empDto;
  }
</code></pre>
",https://stackoverflow.com/questions/54223042/need-advice-on-unit-testing-method-which-is-using-dozer-map-method,"['unit-testing', 'spring-boot', 'dozer']",616,True,0,1
How best to stub/mock rest API calls in Flutter Integration tests,"<p>I have a Flutter app that displays data after the user logs in.
I have unit and widget tests and now would like to write my first <a href=""https://flutter.dev/docs/cookbook/testing/integration/introduction"" rel=""noreferrer"">Integration</a>/end-to-end test to test an entire 'happy path' workflow where the user logs in and views the data.</p>

<p>When the app goes to call the login API (GET login_api_path) I want to return some predefined JSON for what to show on the screen rather than making a real request to the server.</p>

<p>Is this a sensible approach, and if so what is the best way to do this? Most resources I found were specifically for unit testing.</p>
",https://stackoverflow.com/questions/55143353/how-best-to-stub-mock-rest-api-calls-in-flutter-integration-tests,"['dart', 'flutter', 'flutter-test']",8587,True,10,1
How do you unit test a function that &quot;resets&quot; an object?,"<p>Let's say you have a class that has some arbitrary attributes:</p>

<pre class=""lang-dart prettyprint-override""><code>class Data {
  String a = '';
  int b = 0;
  bool c = false;
  SomeObject d = SomeObject();
}
</code></pre>

<p>Let's also say <em>somewhere</em> you have a function that you want to reset most <em>but not all</em> of this <code>Data</code> object's attributes to those which do not correlate to the object constructor's default values.</p>

<pre class=""lang-dart prettyprint-override""><code>Data data = Data();

...

void resetData() {
  data = data
    ..a='reset'
    ..b=42
    ..c=true;
    // We want to retain [d]'s state, for whatever reason.
}
</code></pre>

<p>How do you go about unit testing this behavior?</p>

<p>You could have a unit test that sets each attribute of <code>Data</code> to something entirely different from whatever the reset's default values are and verify that all of the relevant fields change, but that's 1) incredibly brittle and 2) defeats the purpose of what unit testing is for. If you added another object <code>e</code> that's supposed to be reset as well, but you forgot to add it to the <code>resetData</code> function, you almost certainly forgot to add it to the unit test as well. The unit test would then be providing no value, since the behavior would be broken but you would not be alerted to it.</p>

<p>Using reflection/introspection through <code>dart:mirrors</code> is an option by testing that each of that object's variables are indeed different (other than <code>d</code>), but <code>dart:mirrors</code> does not work with AngularDart so users of that are left high and dry.</p>

<p>I also couldn't find any libraries that could ""fuzz"" objects by seeding the object with garbage values, so not entirely sure how to proceed (or if I should even be wasting my time with this seemingly silly unit test).</p>
",https://stackoverflow.com/questions/55289422/how-do-you-unit-test-a-function-that-resets-an-object,"['unit-testing', 'dart']",431,False,0,1
ts-jest: TypeScript type errors are ignored,"<p>I just started learning TypeScript and tried some simple app with jest unit test (using ts-jest):</p>

<p>simple app.ts module:</p>

<pre><code>function greet(person: string): string {
  return `Hello, ${person}`;
}

exports.greet = greet;
</code></pre>

<p>simple app.spec.ts code:</p>

<pre><code>const greetObject = require('../app');

greetObject.greet(1);

describe('greet function', () =&gt; {
  it('should return greeting', () =&gt; {
    expect(greetObject.greet('Dude')).toEqual('Hello, Dude');
  });
  it('should throw type exception', () =&gt; {
    const spy = jest.spyOn(greetObject, 'greet');
    greetObject.greet(1);
    /** @todo what should happen ? */
  });
});
</code></pre>

<p>and the question is: should I receive type error or not ? In fact, I do not receive any errors here.</p>

<p>But if I call greet with wrong parameter type in app.ts file the whole test suite is failing.</p>

<p>Am I missing something in TypeScript unit testing ?</p>

<p><strong>UPD.</strong> Converted require to ES6 import. TypeScript diagnostics are now working, but I still don't know if I can do anything with wrong types and test those situations. Any advice is appreciated.</p>
",https://stackoverflow.com/questions/55554126/ts-jest-typescript-type-errors-are-ignored,"['typescript', 'unit-testing', 'jestjs', 'ts-jest']",5976,True,4,1
Code coverage concern on promise/asynchronous unit testing using nockjs and jest,"<p>I have written a simple unit test for API call using NockJS and Jest for a react application as bellow:</p>

<p>AjaxService.js</p>

<pre><code>export const AjaxService = {
    post: (url, data, headers) =&gt; {
        return axios({
            method: ""POST"",
            url: url,
            headers: headers || { ""content-type"": ""application/json"" },
            data: data
        });
    },
};
</code></pre>

<p>API Promise:</p>

<pre><code>export const getDashboard = (request) =&gt; {
  return AjaxService.post(API_DASHBOARD_URL + ""/getDashboard"", request
  ).then(
    response =&gt; {
      return response.data;
    },
    (error) =&gt; {
      return error.response.data;
    }
  )
};
</code></pre>

<p>Unit test using NockJS:</p>

<pre><code>nock(baseUrl)
    .post(subUrl, request)
    .reply(200, response);

getDashboard(request)
    .then(resp =&gt; {
        let compareVal = getNestedObject(resp, keyToCompare);
        let actualVal = getNestedObject(response, keyToCompare);
        expect(compareVal).to.equal(actualVal);
    })
    .then(() =&gt; {});
</code></pre>

<p>But when the code-coverage report is generated using Jest <code>--coverage</code> as below:</p>

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

<p>We can see that in promise, <strong>success callback</strong> and <strong>error callback</strong> is <strong>not</strong> called during unit test. How to cover this part of code as it affects code-coverage percentage when an application is having numerous API calls? Or am I not testing is properly? Please help as I am new to unit testing. Thanks in advance. </p>
",https://stackoverflow.com/questions/57656523/code-coverage-concern-on-promise-asynchronous-unit-testing-using-nockjs-and-jest,"['javascript', 'reactjs', 'jestjs', 'code-coverage', 'nock']",2427,True,4,1
How to unit-test a deserialization function used in serde(deserialize_with)?,"<p>I have a struct which implements <code>Deserialize</code> and uses the <code>serde(deserialize_with)</code> on a field:</p>

<pre class=""lang-rust prettyprint-override""><code>#[derive(Debug, Deserialize)]
struct Record {
    name: String,
    #[serde(deserialize_with = ""deserialize_numeric_bool"")]
    is_active: bool,
}
</code></pre>

<p>The implementation of <code>deserialize_numeric_bool</code> deserializes a string ""0"" or ""1"" to the corresponding boolean value:</p>

<pre class=""lang-rust prettyprint-override""><code>pub fn deserialize_numeric_bool&lt;'de, D&gt;(deserializer: D) -&gt; Result&lt;bool, D::Error&gt;
    where D: Deserializer&lt;'de&gt;
{
    struct NumericBoolVisitor;

    impl&lt;'de&gt; Visitor&lt;'de&gt; for NumericBoolVisitor {
        type Value = bool;

        fn expecting(&amp;self, formatter: &amp;mut fmt::Formatter) -&gt; fmt::Result {
            formatter.write_str(""either 0 or 1"")
        }

        fn visit_u64&lt;E&gt;(self, value: u64) -&gt; Result&lt;bool, E&gt;
            where E: DeserializeError
        {
            match value {
                0 =&gt; Ok(false),
                1 =&gt; Ok(true),
                _ =&gt; Err(E::custom(format!(""invalid bool: {}"", value))),
            }
        }
    }

    deserializer.deserialize_u64(NumericBoolVisitor)
}
</code></pre>

<p>(I appreciate comments about code improvements)</p>

<p>I'd like to write unit tests for deserialization functions like <code>deserialize_numeric_bool</code>. Of course, my friendly search box revealed the <code>serde_test</code> crate and a <a href=""https://serde.rs/unit-testing.html"" rel=""noreferrer"">documentation page about unit-testing</a>.
But these resources couldn't help me in my case, as the crate tests a structure directly implementing <code>Deserialize</code>.</p>

<p>One idea I had was to create a newtype which only contains the output of my deserialize functions and test it with it. But this looks like a unnecessary indirection to me.</p>

<pre class=""lang-rust prettyprint-override""><code>#[derive(Deserialize)]
NumericBool {
    #[serde(deserialize_with = ""deserialize_numeric_bool"")]
    value: bool
};
</code></pre>

<p>How do I write idiomatic tests for it?</p>
",https://stackoverflow.com/questions/56985101/how-to-unit-test-a-deserialization-function-used-in-serdedeserialize-with,"['unit-testing', 'rust', 'serde']",1980,True,15,3
How to Mock AutoMapper IConfigurationProvider in x-unit unit testing in asp.net core,"<p>I'm writing unit test for my <code>UserRepository</code> class where I'm using AutoMapper <code>ProjectTo&lt;T&gt;</code> Queryable Extensions for projection. Here is how the class looks like:</p>

<pre><code>public class UserRepository:IUserRepository
    {
        private readonly UserManager&lt;UserEntity&gt; _userManager;
        private readonly IConfigurationProvider _mappingConfiguration;

        public UserRepository(
            UserManager&lt;UserEntity&gt; userManager,
            IConfigurationProvider mappingConfiguration)
        {
            _userManager = userManager;
            _mappingConfiguration = mappingConfiguration;
        }

        public async Task&lt;IEnumerable&lt;User&gt;&gt; GetUsersAsync()
        {
            IQueryable&lt;UserEntity&gt; query = _userManager.Users;

            var size = await query.CountAsync();

            var items = await query
                .ProjectTo&lt;User&gt;(_mappingConfiguration)
                .ToArrayAsync();

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

<p>I'm using x-unit unit test project. Here is my test class,</p>

<pre><code>public class UserRepositoryTests
    {
        [Fact]
        public async void GetUsers_AtleastOne_ReturnOneOrMore()
        {
            // Arrange
            var connectionStringBuilder =
                new SqliteConnectionStringBuilder { DataSource = "":memory:"" };
            var connection = new SqliteConnection(connectionStringBuilder.ToString());

            var options = new DbContextOptionsBuilder&lt;GallaContext&gt;()
                .UseSqlite(connection)
                .Options;

            var mockHttpContextAccessor = new Mock&lt;IHttpContextAccessor&gt;();
            var mockUserManager = new Mock&lt;UserManager&lt;UserEntity&gt;&gt;(new Mock&lt;IUserStore&lt;UserEntity&gt;&gt;().Object,
                    new Mock&lt;IOptions&lt;IdentityOptions&gt;&gt;().Object,
                    new Mock&lt;IPasswordHasher&lt;UserEntity&gt;&gt;().Object,
                    new IUserValidator&lt;UserEntity&gt;[0],
                    new IPasswordValidator&lt;UserEntity&gt;[0],
                    new Mock&lt;ILookupNormalizer&gt;().Object,
                    new Mock&lt;IdentityErrorDescriber&gt;().Object,
                    new Mock&lt;IServiceProvider&gt;().Object,
                    new Mock&lt;ILogger&lt;UserManager&lt;UserEntity&gt;&gt;&gt;().Object);
            var mockAutoMapper = new Mock&lt;IConfigurationProvider&gt;();

            using (var context = new GallaContext(options, mockHttpContextAccessor.Object))
            {
                context.Database.OpenConnection();
                context.Database.EnsureCreated();

                var userRepository = new UserRepository( mockUserManager.Object, mockAutoMapper.Object);

                // Act
                var users = await userRepository.GetUsersAsync();

                // Assert
                users.Should().HaveCountGreaterOrEqualTo(1);
            }
        }
    }
</code></pre>

<p>I'm getting the following error when executing <code>ProjectTo&lt;User&gt;</code> in my repository class.</p>

<blockquote>
  <p>{System.NullReferenceException: Object reference not set to an
  instance of an object.    at
  AutoMapper.QueryableExtensions.ProjectionExpression.ToCore[TResult](Object
  parameters, IEnumerable`1 memberPathsToExpand)</p>
</blockquote>

<p>I'm new to Moq and Unit Testing, I searched a lot but couldn't find a way to Mock this. Please assist on how to properly Mock AutoMapper <code>IConfigurationProvider</code> along with my <code>MappingProfile</code></p>

<p>Here is the Error Details</p>

<pre><code>System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.

  Source=AutoMapper

  StackTrace:
   at AutoMapper.QueryableExtensions.ProjectionExpression.ToCore[TResult](Object parameters, IEnumerable '1 memberPathsToExpand)
   at AutoMapper.QueryableExtensions.Extensions.ProjectTo[TDestination](IQueryable source, IConfigurationProvider configuration, Expression`1[] membersToExpand)
   at Repositories.UserRepository.&lt;GetUsersAsync&gt;d__5.MoveNext() in ..path\:line 46
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter '1.GetResult()
   at Repositories.Test.UserRepositoryTests.&lt;GetUsers_AtleastOne_ReturnOneOrMore&gt;d__0.MoveNext() in ..path\Repositories.Test\UserRepositoryTests.cs:line 53
</code></pre>

<p>Thanks,</p>

<p>Abdul</p>
",https://stackoverflow.com/questions/56890008/how-to-mock-automapper-iconfigurationprovider-in-x-unit-unit-testing-in-asp-net,"['c#', 'unit-testing', 'automapper', 'moq', 'xunit']",2233,True,4,2
How can I get random data generated for scala case classes with the ability to &quot;change some values&quot; for unit testing?,"<p>I'm working with a piece of code that has a broad/deep case class hierarchy. For unit testing, I'd like to have ""random data"" populated in the classes with the ability to change the data for the fields I care about?</p>

<p>Example:</p>

<pre><code>case class Foo(bar: Bar, name: String, value: Int)
case class Bar(baz: Baz, price: Double)
case class Baz(thing: String)
</code></pre>

<p>So something like:</p>

<pre><code>val randomFoo = GenerateRandomData(Foo)
randomFoo.bar.baz = Baz(""custom for testing"")
</code></pre>

<p>I've heard of <code>ScalaCheck</code> and <code>Shapeless</code> and <code>Scalacheck-shapeless</code> and they do provide some sort of random data generation but nothing with customization it seems.</p>

<p>I'm currently using <code>ScalaMock</code> but that builds out <code>null</code> fields and breaks testability for ""other"" tests. I used something similar in .Net like Auto Fixture and was wondering if there was something similar in Scala.</p>
",https://stackoverflow.com/questions/56083851/how-can-i-get-random-data-generated-for-scala-case-classes-with-the-ability-to,"['scala', 'unit-testing', 'scalacheck']",1673,True,4,3
How do I override (or overwrite?) a built-in Javascript function,"<p>For unit-testing purposes, I need to overwrite the <code>Number.prototype.toLocaleString()</code> so that it is always called with <code>en-US</code> rather than default behavior. I understand overwriting a normal built-in function that receives a parameter, but <code>toLocaleString()</code> does not take the Number to convert to string directly as parameter so I am confused here. </p>

<p>I tried the following: </p>

<pre><code>Number.prototype.toLocaleStringTest = Number.prototype.toLocaleString
Number.prototype.toLocaleString = function() { this.toLocaleStringTest('en-US') }
</code></pre>

<p>But the result of this new <code>toLocaleString()</code> function is always <code>undefined</code>. New function is certainly called, by the way, I ensured this via adding a temporary <code>console.log(""I am called!"")</code> in the implementation.</p>

<p>What am I doing wrong -- Or am I trying to achieve something that is not doable?</p>
",https://stackoverflow.com/questions/54513935/how-do-i-override-or-overwrite-a-built-in-javascript-function,"['javascript', 'unit-testing']",419,True,4,1
QApplication instance/qtbot fixture causes travis-ci to abort and core dump,"<p>Working on understanding how to go about automated unit testing for PySide2-based applications. However, whenever I attempt to initialize a <code>QApplication</code> instance within the tests, be it through <code>PySide2</code> itself or through <code>pytest-qt</code>'s qtbot fixture, travis-ci aborts the test. It works locally, however.</p>

<p>I've attempted using the <code>qtbot</code> and <code>qapp</code> fixtures from <code>pytest-qt</code>, trying different <code>travis-ci</code> distros like <code>xenial</code> and <code>trusty</code>, as well as including the <code>pytest-xvfb</code> plugin as I've seen recommended by a similar stackoverflow question's answer, but nothing worked in any combination of the above. </p>

<pre><code># .travis.yml
language: python
python:
  - ""3.6""
cache: pip
dist: xenial
install: pip install -r requirements.txt
# running from top folder level to keep package on the path
script: python -m pytest tests/
</code></pre>

<pre class=""lang-py prettyprint-override""><code># tests/test_central.py
from lysiaa.central import MyWindow

def test_giveBack(qapp):
    window = MyWindow()
    assert window.giveBack(1) == 1
</code></pre>

<pre class=""lang-py prettyprint-override""><code># lysiaa/central.py
class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()

    def giveBack(self, param):
        return param
</code></pre>

<p>When <code>travis-ci</code> tries running this, however, it aborts with a core dump. Could anyone please help me with this issue?</p>

<pre><code>============================= test session starts ==============================
platform linux -- Python 3.6.7, pytest-4.5.0, py-1.8.0, pluggy-0.11.0
PySide2 5.12.3 -- Qt runtime 5.12.3 -- Qt compiled 5.12.3
rootdir: /home/travis/build/robert-clayton/LYSIAA
plugins: xvfb-1.2.0, qt-3.2.2
collected 1 item                                                               
tests/test_central.py /home/travis/.travis/functions: line 104:  4092 Aborted                 (core dumped) python -m pytest tests/
The command ""python -m pytest tests/"" exited with 134.
</code></pre>
",https://stackoverflow.com/questions/56281631/qapplication-instance-qtbot-fixture-causes-travis-ci-to-abort-and-core-dump,"['python-3.6', 'travis-ci', 'pytest', 'pyside2', 'pytest-qt']",731,True,3,2
Unit Testing Firebase Database with Android,"<p>I have created an app that allows users to create a transaction. When this transaction is created it is added to the database (Firebase Realtime Database). Once a transaction is created, a series of approvals have to be made before the transaction is carried out.</p>

<p>In order to approve a transaction, a user must click on the transaction on the transaction requests page which displays the desired transactions. Once a user clicks on this transaction the user is shown the relevant dialog box. When a user clicks the ""approve"" button on this dialog box, the value of the corresponding ""flag"" in the database is set to true.</p>

<p>I am trying to write a test using Mockito to test that this flag is indeed being set to true but I am struggling to do so. I have watched multiple videos on unit testing in android studio on youtube and have read through all the posts on here that involve firebase unit testing with android studio but I have still been unable to carry out my desired test.</p>

<p>As my research has lead me to a dead end I was hoping someone on here could either send me in the right direction to some sample code that I have not yet seen, or better yet help me write my desired test.</p>

<p>The code that I am trying to test is within this class:</p>

<pre><code>public class Request extends AppCompatActivity {

private static final String TAG = ""Request"";

//Firebase Stuff
FirebaseDatabase database;
DatabaseReference start, ref;
DatabaseReference user;

RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;

Dialog custDialog;

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

    final String passedEmail = getIntent().getStringExtra(""Email"");

    //Init Firebase
    database = FirebaseDatabase.getInstance();
    start = database.getReference(""Transaction"");
    ref = database.getReference(""User"");

    //Load Menu
    recycler_menu = findViewById(R.id.recycler_menu);
    recycler_menu.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recycler_menu.setLayoutManager(layoutManager);

    loadMenu();
}

private void loadMenu() {
    FirebaseRecyclerAdapter&lt;Transaction, TransRequestHolder&gt; adapter = new FirebaseRecyclerAdapter&lt;Transaction, TransRequestHolder&gt;(Transaction.class, R.layout.trans_item, TransRequestHolder.class, start) {
        @Override
        protected void populateViewHolder(TransRequestHolder viewHolder, final Transaction model, int position) {
            final String passedUserType= getIntent().getStringExtra(""userType"");
            final String passedEmail= getIntent().getStringExtra(""Email"");
            final String receiver = model.getReceiver().replace('.', ' ');
            final String shopA = model.getShopA().replace('.', ' ');

            //custB
            if(passedEmail.equalsIgnoreCase(model.getReceiver()) &amp;&amp; model.getCustflag() == false) {
                viewHolder.txtTransactionA.setText(model.getAmount());
                viewHolder.txtTransactionC.setText(model.getCurrency());
                viewHolder.txtTransactionR.setText(model.getReceiver());
                final Transaction clickItem = model;
                viewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(android.view.View view, int position, boolean isLongClick) {
                        Toast.makeText(Request.this, ""Receiving: "" + shopA, Toast.LENGTH_SHORT).show();
                        final String key = model.getKey();
                        custDialog = new Dialog(Request.this);
                        custDialog.setContentView(R.layout.dialog_template);
                        final EditText Write = custDialog.findViewById((R.id.write));
                        Button Approve = custDialog.findViewById(R.id.approve);

                        Write.setEnabled(true);
                        Approve.setEnabled(true);

                        Approve.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String newShopB = Write.getText().toString().replace(""."", "" "");
                                start.child(key).child(""custflag"").setValue(true);
                                start.child(key).child(""shopB"").setValue(newShopB);
                                Toast.makeText(Request.this, ""CustB Approval"", Toast.LENGTH_SHORT).show();
                                custDialog.cancel();
                            }
                        });
                        custDialog.show();
                    }
                });
            }
            //shopA
            else if (passedEmail.equalsIgnoreCase(model.getShopA()) &amp;&amp; (model.getCustflag() == true &amp;&amp; model.getShopAflag() == false)) {
                viewHolder.txtTransactionA.setText(model.getAmount());
                viewHolder.txtTransactionC.setText(model.getCurrency());
                viewHolder.txtTransactionR.setText(model.getReceiver());
                final Transaction clickItem = model;
                viewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(android.view.View view, int position, boolean isLongClick) {
                        Toast.makeText(Request.this, ""Receiving: "" + shopA, Toast.LENGTH_SHORT).show();
                        final String key = model.getKey();
                        //Dialog option number one
                        customDialog(""Transaction Approval"", ""Are you sure you want to approve this transaction?"", ""cancel"", ""okMethod2"", passedEmail, key);
                    }
                });
            }
            //shopB
            else if (passedEmail.equalsIgnoreCase(model.getShopB()) &amp;&amp; (model.getShopAflag() == true &amp;&amp; model.getShopBflag() == false)) {
                viewHolder.txtTransactionA.setText(model.getAmount());
                viewHolder.txtTransactionC.setText(model.getCurrency());
                viewHolder.txtTransactionR.setText(model.getReceiver());
                final Transaction clickItem = model;
                viewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(android.view.View view, int position, boolean isLongClick) {
                        Toast.makeText(Request.this, ""Receiving: "" + shopA, Toast.LENGTH_SHORT).show();
                        final String key = model.getKey();
                        //Dialog option number one
                        customDialog(""Transaction Approval"", ""Are you sure you want to approve this transaction?"", ""cancel"", ""okMethod3"", passedEmail, key);
                    }
                });
            }
            else {
                viewHolder.itemView.setVisibility(View.GONE);
            }
        }
    };
    recycler_menu.setAdapter(adapter);
}
</code></pre>

<p>}</p>

<p>I hope I have provided enough information. I would appreciate any help anyone can give me.</p>
",https://stackoverflow.com/questions/55265005/unit-testing-firebase-database-with-android,"['java', 'android', 'firebase', 'mockito']",976,False,4,0
How to unit test RxCocoa BehaviorRelay,"<p>I am starting out with unit testing <code>RxSwift Driver</code>. And I am having issues testing a <code>Driver</code>. </p>

<p>This is the code structure of my <code>ViewModel</code>:</p>

<pre><code>import Foundation
import RxSwift
import RxCocoa

class LoginViewViewModel {

    private let loginService: LoginService

    private let _loading = BehaviorRelay&lt;Bool&gt;(value: false)
    private let _loginResponse = BehaviorRelay&lt;LoginResponse?&gt;(value: nil)
    private let _phoneMessage = BehaviorRelay&lt;String&gt;(value: """")
    private let _pinMessage = BehaviorRelay&lt;String&gt;(value: """")
    private let _enableButton = BehaviorRelay&lt;Bool&gt;(value: false)

    var loginResponse: Driver&lt;LoginResponse?&gt; { return _loginResponse.asDriver() }
    var loading: Driver&lt;Bool&gt; { return _loading.asDriver() }
    var phoneMessage: Driver&lt;String&gt; { return _phoneMessage.asDriver() }
    var pinMessage: Driver&lt;String&gt; { return _pinMessage.asDriver() }
    var enableButton: Driver&lt;Bool&gt; { return _enableButton.asDriver() }

    private let phone = BehaviorRelay&lt;String&gt;(value: """")
    private let pin = BehaviorRelay&lt;String&gt;(value: """")

    private let disposeBag = DisposeBag()

    init(phone: Driver&lt;String&gt;, pin: Driver&lt;String&gt;, buttonTapped: Driver&lt;Void&gt;, loginService: LoginService) {
        self.loginService = loginService
        phone
            .throttle(0.5)
            .distinctUntilChanged()
            .drive(onNext: { [weak self] (phone) in
                self?.phone.accept(phone)
                self?.validateFields()
            }).disposed(by: disposeBag)

        pin
            .throttle(0.5)
            .distinctUntilChanged()
            .drive(onNext: { [weak self] (pin) in
                self?.pin.accept(pin)
                self?.validateFields()
            }).disposed(by: disposeBag)

        buttonTapped
            .drive(onNext: { [weak self] () in
                self?.loginUser(phone: self!.phone.value, pin: self!.pin.value)
            }).disposed(by: disposeBag)
    }

    private func validateFields() {
        guard phone.value.count &gt; 0 else {
            return
        }
        _enableButton.accept(false)

        guard pin.value.count &gt; 0 else {
            return
        }

        _enableButton.accept(true)
        _phoneMessage.accept("""")
        _pinMessage.accept("""")
    }

    private func loginUser(phone: String, pin: String) {
        _loading.accept(true)
        _phoneMessage.accept("""")
        _pinMessage.accept("""")

        loginService.loginUser(phone: phone, pin: pin) { [weak self] (response, error) in
            self?._loading.accept(false)
            if let error = error {
                if error.message! == ""Invalid credentials"" {
                    self?._phoneMessage.accept(""Invalid Phone Number"")
                    self?._pinMessage.accept(""Invalid Pin Provided"")
                }
            } else {
                response?.saveUserInfo()
                self?._loginResponse.accept(response)
            }
        }
    }
}
</code></pre>

<p>And my UnitTest looks like this:</p>

<pre><code>class LoginViewViewModelTest: XCTestCase {

    private class MockLoginService: LoginService {
        func loginUser(phone: String, pin: String, completion: @escaping LoginService.LoginDataCompletion) {
            guard phone == ""+17045674568"", pin == ""1234"" else {
                let loginresponse = LoginResponse(message: ""Login Successfully"", status: true, status_code: 200, data: LoginData(access_token: ""adadksdewffjfwe"", token_type: ""bearer"", expires_in: 3600, expiry_time: ""today"", user: User(id: ""1dsldsdsjkj"", name: ""RandomGuy"", phone: ""12345"", pin_set: true, custom_email: false, email: ""somerandom@email.com"")))
                completion(loginresponse, nil)
                return
            }
            let akuError = AKUError(status: false, message: ""Invalid Credential."", status_code: ""404"")
            completion(nil, akuError)
        }
    }

    var viewModel: LoginViewViewModel!

    var scheduler: SchedulerType!

    var phone: BehaviorRelay&lt;String&gt;!
    var pin: BehaviorRelay&lt;String&gt;!
    var buttonClicked: BehaviorRelay&lt;Void&gt;!

    override func setUp() {
        super.setUp()

        phone = BehaviorRelay&lt;String&gt;(value: """")
        pin = BehaviorRelay&lt;String&gt;(value: """")
        buttonClicked = BehaviorRelay&lt;Void&gt;(value: ())

        let loginService = MockLoginService()

        viewModel = LoginViewViewModel(phone: phone.asDriver(), pin: pin.asDriver(), buttonTapped: buttonClicked.asDriver(), loginService: loginService)

        scheduler = ConcurrentDispatchQueueScheduler(qos: .default)
    }

    override func tearDown() {
        super.tearDown()
    }

    func testLoginButtonClicked_Loading() {
        let loadingObservable = viewModel.loading.asObservable().subscribeOn(scheduler)

        phone.accept(""12345"")
        pin.accept(""12345"")
        buttonClicked.accept(())

        let loadingState = try! loadingObservable.skip(0).toBlocking().first()!
        XCTAssertNotNil(loadingState)
        XCTAssertEqual(loadingState, true)
    }
}
</code></pre>

<p><strong>My question:</strong></p>

<p>I am trying to track the state of the <code>loading</code> driver variable. But, it's always <code>false</code>. Even after writing a debugger for checking the states, it only prints out one value and, it's always <code>false</code>.</p>

<p>I decided to add a break point to the code, and I noticed 
<code>let loadingState = try! loadingObservable.skip(0).toBlocking().first()!</code> only gets called once the function is done executing.</p>

<p>Is there a way to test for the <code>loading</code> state?
Is it necessary to test for the <code>loading</code> state?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/54165009/how-to-unit-test-rxcocoa-behaviorrelay,"['ios', 'xctest', 'rx-swift', 'rx-cocoa']",1846,True,3,1
Active build variant does not have a test artifact,"<p>I have created a new build type called 'bitrise' based on the 'debug' build variant. The instrumented androidTests build and run fine when using the 'debug' build variant however when I switch over to my new 'bitrise' build variant I get the following errors:</p>

<pre><code>Process finished with exit code 1
Class not found: ""com.mycompany.app.ui.race.RaceFragmentUiTest""
</code></pre>

<p>And this warning when I select ""Edit Configurations..."" -> ""Android Instrumented Tests""
<a href=""https://i.stack.imgur.com/0UEv0.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/0UEv0.png"" alt=""Warning: Active build variant &quot;myCompanyBitrise&quot; does not have a test artifact.""></a></p>

<p><strong>Versions</strong></p>

<p>'com.android.tools.build:gradle:3.5.2'</p>

<p>Android Studio 3.5.2</p>

<p>This is an <strong>extract</strong> from my Gradle file:</p>

<pre><code>buildTypes {
    debug {
        debuggable true
        testCoverageEnabled = false
        applicationIdSuffix "".debug""
        buildConfigField(""String"", ""BASE_ENDPOINT"", BASE_ENDPOINT_DEBUG)
    }
    release {
        minifyEnabled true
        zipAlignEnabled true
        shrinkResources true
        buildConfigField(""String"", ""BASE_ENDPOINT"", BASE_ENDPOINT_PROD)
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    bitrise {
        initWith debug
        buildConfigField(""String"", ""BASE_ENDPOINT"", BASE_ENDPOINT_PROD)
    }
}

flavorDimensions ""version""

productFlavors {
    mycompany {
        dimension ""version""
        applicationId ""com.mycompany.app""
    }
    second {
        dimension ""version""
        applicationId ""com.second.app""
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation ""org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version""
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.newrelic.agent.android:android-agent:5.24.1'
    implementation 'com.github.bumptech.glide:glide:4.3.0'
    implementation 'io.supercharge:shimmerlayout:2.0.0'
    implementation 'com.google.firebase:firebase-core:17.2.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    kapt 'androidx.lifecycle:lifecycle-common-java8:2.1.0'
    testImplementation 'org.hamcrest:hamcrest-library:1.3'
    testImplementation 'commons-logging:commons-logging:1.2'

    /**
     * Google architecture components
     */
    implementation 'androidx.lifecycle:lifecycle-viewmodel:2.1.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
    implementation ""androidx.navigation:navigation-fragment-ktx:$nav_version""
    implementation ""androidx.navigation:navigation-ui-ktx:$nav_version""
    testImplementation 'androidx.arch.core:core-testing:2.1.0'
    testImplementation 'androidx.annotation:annotation:1.1.0'
    androidTestImplementation 'androidx.arch.core:core-testing:2.1.0'
    androidTestImplementation 'androidx.annotation:annotation:1.1.0'

    /**
     * AWS IoT
     */
    implementation 'com.amazonaws:aws-android-sdk-iot:2.15.2'
    implementation 'com.amazonaws:aws-android-sdk-mobile-client:2.15.2'
    testImplementation 'com.amazonaws:aws-android-sdk-iot:2.15.2'

    /**
     * Dagger DI dependencies
     */
    implementation 'com.google.dagger:dagger:2.24'
    kapt 'com.google.dagger:dagger-compiler:2.24'

    /**
     * Volley for network communication
     */
    implementation 'com.android.volley:volley:1.1.1'

    /**
     * Unit testing
     */
    testImplementation 'org.json:json:20190722'
    testImplementation 'org.mockito:mockito-core:3.0.0'
    testImplementation ""com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0""
    testImplementation 'junit:junit:4.12'

    /**
     * Instrumentation testing
     */
    androidTestImplementation 'com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0'
    androidTestImplementation 'org.mockito:mockito-android:2.25.0'
    androidTestImplementation 'androidx.test:rules:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    debugImplementation 'androidx.fragment:fragment-testing:1.2.0-rc02'

    /**
     * Json parsing
     */
    implementation 'com.squareup.moshi:moshi:1.9.2'
    kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.9.2'
}
</code></pre>

<p><strong>My unit tests run fine in all configurations, I only have an issue with Android Instrumented Tests</strong></p>

<p>I have tried these steps: <a href=""https://developer.android.com/studio/build/build-variants#sourcesets"" rel=""noreferrer"">https://developer.android.com/studio/build/build-variants#sourcesets</a>, <a href=""https://stackoverflow.com/questions/22241399/testcase-class-not-found-by-android-studio"">TestCase class not found by Android Studio</a>, <a href=""https://stackoverflow.com/questions/22106891/android-studio-unit-testing-unable-to-find-instrumentation-or-class-not-found-e"">Android Studio Unit Testing: unable to find instrumentation OR class not found ex</a></p>
",https://stackoverflow.com/questions/59153826/active-build-variant-does-not-have-a-test-artifact,"['android', 'gradle', 'android-gradle-plugin', 'android-testing', 'android-gradle-3.0']",3921,True,13,2
How to unit test method with TryUpdateModelAsync invovled in ASP.NET CORE Razor Page Web App?,"<p>TryUpdateModelAsync is an internal protected method of abstract class PageModel, which makes it, to my view, unmockable. Is there any approach to unit test any of the action that involves this method? </p>

<p>I saw this solution on the internet: 
<a href=""https://stackoverflow.com/questions/39259025/asp-net-core-mvc-controller-unit-testing-when-using-tryupdatemodel"">asp.net core mvc controller unit testing when using TryUpdateModel</a>.</p>

<p>However, it only applies to ASP.NET Core MVC Web App since TryUpdateModelAsync is a public method, so we can add an adapator to wrap this method and make our adaptor call the actual method. In Razor Page, this TryUpdateModelAsync is inaccessible from outside.</p>

<p>The problem I was having right now is when I was unit testing the OnPostAsync method, <code>TryUpdateModelAsync</code> always throw an exception. I could never pass through that line to check the code logic after it.</p>

<p>So here is the action I want to unit test:</p>

<pre class=""lang-cs prettyprint-override""><code> public class CreateModel : PageModel
    {
     //elided
        [BindProperty]
        public Post Post { get; set; }

        public async Task&lt;IActionResult&gt; OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
            if (await TryUpdateModelAsync&lt;Post&gt;(Post, ""Post"", p =&gt; p.Title, p =&gt; p.SubTitle, p =&gt; p.Author, p =&gt; p.Content, p =&gt; p.CategoryID)){
                //do stuff
                return RedirectToPage(""./Index"");
            }
            //do stuff
            return Page();
        }
</code></pre>

<p>Here's the unit test I wrote for it:</p>

<pre class=""lang-cs prettyprint-override""><code>  [Test]
  public async Task InvokeOnPostAsyncWithInvalidModelState_ShouldReturnPageResultType(){
            //Arrange
            InitPostModelProperties();
            var createModel = new CreateModel(){
                PageContext = _pageContext,
                TempData = _tempData,
                Url = _urlHelper
            };
           //do arrangement

            //Act
            var result = await createModel.OnPostAsync();

            //Assert
        }
</code></pre>

<p><strong>UPDATE</strong>:</p>

<p>Here's the full initialization process I did for this test:</p>

<pre class=""lang-cs prettyprint-override""><code>  public void InitPostModelProperties(){
 _httpContext = new DefaultHttpContext(){
                //RequestServices = services.BuildServiceProvider()
            };
            _modelStateDictionary = new ModelStateDictionary();
            _modelMetaDataProvider = new EmptyModelMetadataProvider();
            _actionContext = new ActionContext(_httpContext, new RouteData(), new PageActionDescriptor(), _modelStateDictionary);
            _viewData = new ViewDataDictionary(_modelMetaDataProvider, _modelStateDictionary);
            _tempData = new TempDataDictionary(_httpContext, Mock.Of&lt;ITempDataProvider&gt;());
            _pageContext = new PageContext(_actionContext){
                ViewData = _viewData
            };
            _urlHelper = new UrlHelper(_actionContext);
        }
</code></pre>

<p>Then I got following exception message:</p>

<pre><code>  Error Message:
   System.ArgumentNullException : Value cannot be null.
Parameter name: metadataProvider
  Stack Trace:
     at Microsoft.AspNetCore.Mvc.ModelBinding.Internal.ModelBindingHelper.TryUpdateModelAsync(Object model, Type modelType, String prefix, ActionContext actionContext, IModelMetadataProvider metadataProvider, IModelBinderFactory modelBinderFactory, IValueProvider valueProvider, IObjectModelValidator objectModelValidator, Func`2 propertyFilter)
   at Microsoft.AspNetCore.Mvc.RazorPages.PageModel.TryUpdateModelAsync[TModel](TModel model, String name, Expression`1[] includeExpressions)
</code></pre>

<p>Then I changed my initialization to the following:</p>

<pre class=""lang-cs prettyprint-override""><code>  public void InitPostModelProperties(){
  var services = new ServiceCollection();
  services.AddTransient&lt;IModelMetadataProvider, ModelMetadataProvider&gt;();
 _httpContext = new DefaultHttpContext(){
                RequestServices = services.BuildServiceProvider()
            };
            _modelStateDictionary = new ModelStateDictionary();
            _modelMetaDataProvider = new EmptyModelMetadataProvider();
            _actionContext = new ActionContext(_httpContext, new RouteData(), new PageActionDescriptor(), _modelStateDictionary);
            _viewData = new ViewDataDictionary(_modelMetaDataProvider, _modelStateDictionary);
            _tempData = new TempDataDictionary(_httpContext, Mock.Of&lt;ITempDataProvider&gt;());
            _pageContext = new PageContext(_actionContext){
                ViewData = _viewData
            };
            _urlHelper = new UrlHelper(_actionContext);
        }
</code></pre>

<p>Then I got new exception message:</p>

<pre><code>Outcome: Failed
    Error Message:
    System.InvalidOperationException : No service for type 'Microsoft.AspNetCore.Mvc.ModelBinding.IModelMetadataProvider' has been registered.
    Stack Trace:
       at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.AspNetCore.Mvc.RazorPages.PageModel.get_MetadataProvider()
   at Microsoft.AspNetCore.Mvc.RazorPages.PageModel.TryUpdateModelAsync[TModel](TModel model, String name, Expression`1[] includeExpressions)
</code></pre>

<p>I followed the exception message and added these lines:</p>

<pre class=""lang-cs prettyprint-override""><code>services.AddSingleton&lt;IModelMetadataProvider, EmptyModelMetadataProvider&gt;();
</code></pre>

<p>Got new exception message:</p>

<pre><code>  Outcome: Failed
    Error Message:
    System.InvalidOperationException : No service for type 'Microsoft.AspNetCore.Mvc.ModelBinding.IModelBinderFactory' has been registered.
    Stack Trace:
       at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.AspNetCore.Mvc.RazorPages.PageModel.get_ModelBinderFactory()
   at Microsoft.AspNetCore.Mvc.RazorPages.PageModel.TryUpdateModelAsync[TModel](TModel model, String name, Expression`1[] includeExpressions)
</code></pre>

<p>I kept adding new lines:</p>

<pre class=""lang-cs prettyprint-override""><code> services.AddSingleton&lt;IModelBinderFactory,ModelBinderFactory&gt;();
</code></pre>

<p>Only to find the service can't be instansiated beause ModelBinderFactory class is an abstract class</p>

<p>I am stuck here.</p>

<p><strong>UPDATE</strong></p>

<p>The whole test code is shown below:</p>

<p><strong>SRC</strong>:</p>

<pre class=""lang-cs prettyprint-override""><code>  public class BaseTests
    {
        private  HugoBlogContext _context;

        public HugoBlogContext Context =&gt; _context;
        public List&lt;Category&gt; CatList;
        public List&lt;Post&gt; PostList;

        public List&lt;Tag&gt; TagList;

        public List&lt;PostTag&gt; PostTagList;

        public BaseTests(){}


 public class PageModelBaseTests: BaseTests
    {
        protected ICategoryRepository _categoryRepository;

        protected IPostRepository _postRepository;

        protected IPostTagRepository _postTagRepository;

        protected ITagRepository _tagRepository;

        protected ISelectTagService _selectTagService;

        protected IDropdownCategoryService _dropdownCategoryService;

        protected HttpContext _httpContext;

        protected ModelStateDictionary _modelStateDictionary;

        protected ActionContext _actionContext;

        protected ModelMetadataProvider _modelMetaDataProvider;

        protected ViewDataDictionary _viewData;

        protected TempDataDictionary _tempData;

        protected PageContext _pageContext;

        protected UrlHelper _urlHelper;



        [SetUp]
        public void Init(){
            _categoryRepository = new CategoryRepository(Context);
            _postRepository = new PostRepository(Context);
            _postTagRepository = new PostTagRepository(Context);
            _tagRepository = new TagRepository(Context);
            _selectTagService = new SelectTagService(_tagRepository, _postRepository, _postTagRepository);
            _dropdownCategoryService = new DropdownCategoryService(_categoryRepository);
        }


        public void InitPostModelProperties(){
            var services = new ServiceCollection();
            services.AddSingleton&lt;IModelMetadataProvider, EmptyModelMetadataProvider&gt;();
            services.AddSingleton&lt;IModelBinderFactory,ModelBinderFactory&gt;();
            _httpContext = new DefaultHttpContext(){
                RequestServices = services.BuildServiceProvider()
            };
            _modelStateDictionary = new ModelStateDictionary();
            _modelMetaDataProvider = new EmptyModelMetadataProvider();
            _actionContext = new ActionContext(_httpContext, new RouteData(), new PageActionDescriptor(), _modelStateDictionary);
            _viewData = new ViewDataDictionary(_modelMetaDataProvider, _modelStateDictionary);
            _tempData = new TempDataDictionary(_httpContext, Mock.Of&lt;ITempDataProvider&gt;());
            _pageContext = new PageContext(_actionContext){
                ViewData = _viewData
            };
            _urlHelper = new UrlHelper(_actionContext);
        }


[TestFixture]
  public class CreateModelTests: PageModelBaseTests
    {

[Test]
    public async Task InvokeOnPostAsyncWithValidModelState_ShouldReturnRedirectPageResultTypeAndCategoryShouldBeUpdated(){
              //Arrange
            InitPostModelProperties();
            var createModel = new CreateModel(_selectTagService, _dropdownCategoryService ,_postRepository){
                PageContext = _pageContext,
                TempData = _tempData,
                Url = _urlHelper,
            };
            createModel.Post = new Post{
                Title = ""Create"",
                SubTitle = ""Create"",
                Content = ""Create"",
                Author = ""Create"",
                CategoryID = CatList.Count + 1,
            };
            var selectedTags = new string[3]{""4"",""5"",""6""};

            //Act
            var result = await createModel.OnPostAsync(selectedTags);

            //Assert
            result.Should().BeOfType&lt;RedirectToPageResult&gt;();
            Context.Posts.Where(c =&gt; c.CategoryID == (CatList.Count + 1)).Should().NotBeNull();
        }
    }
</code></pre>

<p><strong>UPDATE</strong>
After mocking, I got the following Exception Message:</p>

<pre><code>  Outcome: Failed
    Error Message:
    System.NullReferenceException : Object reference not set to an instance of an object.
    Stack Trace:
       at Microsoft.AspNetCore.Mvc.ModelBinding.Internal.ModelBindingHelper.TryUpdateModelAsync(Object model, Type modelType, String prefix, ActionContext actionContext, IModelMetadataProvider metadataProvider, IModelBinderFactory modelBinderFactory, IValueProvider valueProvider, IObjectModelValidator objectModelValidator, Func`2 propertyFilter)
   at Microsoft.AspNetCore.Mvc.RazorPages.PageModel.TryUpdateModelAsync[TModel](TModel model, String name, Expression`1[] includeExpressions)
</code></pre>

<p>FYI: I also mocked <code>IObjectValidator</code> by using <code>services.AddSingleton&lt;IObjectValidator&gt;(Mock.Of&lt;IObjectValidator&gt;())</code></p>
",https://stackoverflow.com/questions/57641311/how-to-unit-test-method-with-tryupdatemodelasync-invovled-in-asp-net-core-razor,"['c#', 'unit-testing', 'asp.net-core', 'razor-pages']",1357,False,3,1
Unit Testing SQLite Repository generating No Such Table Error,"<p>I have recently built a quiz application for Xamarin.Android, and want to dome some Unit Testing on the shared library.</p>

<p>I am using a repository pattern with the following files.</p>

<p>SQLiteMyAppRepository.cs</p>

<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SQLite;

namespace MyApp.DataLayer
{
    public class MyAppRepository : IMyAppRepository
    {
        public static string DatabaseName = ""MyApp.sqlite"";

        private SQLiteConnection _dbConnection;

        public MyAppRepository()
        {
            string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string dbFilePath = Path.Combine(docFolder, DatabaseName);
            _dbConnection = new SQLiteConnection(dbFilePath);
        }
</code></pre>

<p>I have then created a new project to test some of these elements.</p>

<p>The primary issue I am having, is that when I try and run the test, I am getting the following exception:</p>

<pre><code>MyApp.Tests.RepositoryTests.AddQuestion threw 
exception: 
SQLite.SQLiteException: no such table: Questions
</code></pre>

<p>I have been messing about with it for a few hours now and can't seem to find what is wrong, any help would be appreciated. I thought Mocking the repository would get around any issues like this. </p>
",https://stackoverflow.com/questions/56823628/unit-testing-sqlite-repository-generating-no-such-table-error,"['c#', '.net', 'moq', 'repository-pattern']",737,True,2,1
during wct test: Failed to load resource: the server responded with a status of 404 (Not Found),"<p>I am struggling to find someway approach to test my vanilla webcomponents. I found someone trying the same and I try to reproduce exactly his steps and the answer accepted (<a href=""https://stackoverflow.com/questions/53463201/web-component-htmlelement-unit-testing"">Web Component / HtmlElement : unit testing</a>).</p>

<p>I can't imagine a reason for not finding the test. It seems it looks in wrong place. If so, maybe the answer to my question will be how to edit the path to in wct.conf.js to find the real test (I am not sure it is the root cause but it is my best in front of the error provided).</p>

<p>wct.conf.js</p>

<pre><code>module.exports = {
    npm:true,
    verbose: true,
    plugins: {
        local: {
            browsers: [""chrome""]
        }
    },
    configuration: { suites:
        [ 'test/hello-world-test.html']},
    wctPackageName: ""wct-browser-legacy""
};
</code></pre>

<p>hello-world-test.html</p>

<pre><code>&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset=""utf-8""&gt;
    &lt;script src=""../node_modules/web-component-tester/browser.js""&gt;&lt;/script&gt;
    &lt;script src=""../src/hello-world.js""&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;test-fixture id=""helloWorldFixture""&gt;
        &lt;template&gt;
            &lt;hello-world&gt;
            &lt;/hello-world&gt;
        &lt;/template&gt;
    &lt;/test-fixture&gt;
    &lt;script&gt;
        suite('&lt;hello-world&gt;', () =&gt; {
            let component;
            setup(() =&gt; {
                component = fixture('helloWorldFixture');
            });

            test('contains hello world string ?', () =&gt; {
                let index = component.innerText.indexOf('Hello');
                assert.isAtLeast(index, 0);
            });
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>console:</p>

<pre><code>resource@DESKTOP-AKCNE7F C:\_d\WSs\basic-vanilla-webcomponent
# wct --npm -wct-package-name=wct-browser-legacy
step: loadPlugins
step: configure
hook: configure
Expanded local browsers: [ 'chrome' ] into capabilities: [ { browserName: 'chrome',
    version: '75',
    chromeOptions:
     { binary:
        'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
       args: [Array] } } ] with browserOptions: undefined
configuration: { suites: [ 'test/hello-world-test.html' ],
  verbose: true,
  quiet: false,
  expanded: false,
  testTimeout: 90000,
  persistent: false,
  extraScripts: [],
  clientOptions:
   { root: '/components/',
     verbose: true,
     environmentScripts:
      [ 'stacky/browser.js',
        'wct-browser-legacy/node_modules/async/lib/async.js',
        'wct-browser-legacy/node_modules/lodash/index.js',
        'wct-browser-legacy/node_modules/mocha/mocha.js',
        'chai/chai.js',
        '@polymer/sinonjs/sinon.js',
        'sinon-chai/lib/sinon-chai.js',
        'accessibility-developer-tools/dist/js/axs_testing.js',
        'wct-browser-legacy/node_modules/@polymer/test-fixture/test-fixture.js' ] },
  compile: 'auto',
  activeBrowsers:
   [ { browserName: 'chrome', version: '75', chromeOptions: [Object] } ],
  browserOptions: {},
  plugins:
   { local:
      { disabled: false,
        browsers: [Array],
        seleniumArgs: [],
        javaArgs: [],
        skipSeleniumInstall: false },
     sauce: { disabled: false } },
  registerHooks: [Function: registerHooks],
  enforceJsonConf: false,
  webserver:
   { hostname: 'localhost',
     _generatedIndexContent:
      '&lt;!doctype html&gt;\n&lt;html&gt;\n\n&lt;head&gt;\n  &lt;meta charset=""utf-8""&gt;\n  &lt;script&gt;\n    window.WCT = {""root"":""/components/"",""verbose"":true,""environmentScripts"":[""stacky/browser.js"",""wct-browser-legacy/node_modules/async/lib/async.js"",""wct-browser-legacy/node_modules/lodash/index.js"",""wct-browser-legacy/node_modules/mocha/mocha.js"",""chai/chai.js"",""@polymer/sinonjs/sinon.js"",""sinon-chai/lib/sinon-chai.js"",""accessibility-developer-tools/dist/js/axs_testing.js"",""wct-browser-legacy/node_modules/@polymer/test-fixture/test-fixture.js""]};\n    window.__generatedByWct = true;\n  &lt;/script&gt;\n  \n    &lt;script src=""../wct-browser-legacy/browser.js""&gt;&lt;/script&gt;\n  \n  \n&lt;/head&gt;\n\n&lt;body&gt;\n  &lt;script&gt;\n    WCT.loadSuites([""test/hello-world-test.html""]);\n  &lt;/script&gt;\n&lt;/body&gt;\n\n&lt;/html&gt;\n' },
  moduleResolution: 'node',
  npm: true,
  configuration: { suites: [ 'test/hello-world-test.html' ] },
  wctPackageName: 'wct-browser-legacy',
  root: 'C:\\_d\\WSs\\basic-vanilla-webcomponent',
  ttyOutput: true,
  _: [],
  origSuites: [ 'test/' ] }
hook: prepare
hook: prepare:selenium
Installing and starting Selenium server for local browsers
----------
selenium-standalone installation starting
----------

---
selenium install:
from: https://selenium-release.storage.googleapis.com/3.141/selenium-server-standalone-3.141.59.jar
to: C:\_d\WSs\basic-vanilla-webcomponent\node_modules\selenium-standalone\.selenium\selenium-server\3.141.59-server.jar
---
chrome install:
from: https://chromedriver.storage.googleapis.com/2.43/chromedriver_win32.zip
to: C:\_d\WSs\basic-vanilla-webcomponent\node_modules\selenium-standalone\.selenium\chromedriver\2.43-x64-chromedriver
---
ie install:
from: https://selenium-release.storage.googleapis.com/3.12/IEDriverServer_x64_3.12.0.zip
to: C:\_d\WSs\basic-vanilla-webcomponent\node_modules\selenium-standalone\.selenium\iedriver\3.12.0-x64-IEDriverServer.exe
---
firefox install:
from: https://github.com/mozilla/geckodriver/releases/download/v0.20.1/geckodriver-v0.20.1-win64.zip
to: C:\_d\WSs\basic-vanilla-webcomponent\node_modules\selenium-standalone\.selenium\geckodriver\0.20.1-x64-geckodriver
---
edge install:
from: https://download.microsoft.com/download/F/8/A/F8AF50AB-3C3A-4BC4-8773-DC27B32988DD/MicrosoftWebDriver.exe
to: C:\_d\WSs\basic-vanilla-webcomponent\node_modules\selenium-standalone\.selenium\edgedriver\17134-MicrosoftEdgeDriver.exe
---
File from https://selenium-release.storage.googleapis.com/3.12/IEDriverServer_x64_3.12.0.zip has already been downloaded
---
File from https://selenium-release.storage.googleapis.com/3.141/selenium-server-standalone-3.141.59.jar has already been downloaded
---
File from https://chromedriver.storage.googleapis.com/2.43/chromedriver_win32.zip has already been downloaded
---
File from https://github.com/mozilla/geckodriver/releases/download/v0.20.1/geckodriver-v0.20.1-win64.zip has already been downloaded


-----
selenium-standalone installation finished
-----
16:22:38.752 INFO [GridLauncherV3.parse] - Selenium server version: 3.141.59, revision: e82be7d358
16:22:38.872 INFO [GridLauncherV3.lambda$buildLaunchers$3] - Launching a standalone Selenium Server on port 59287
2019-07-16 16:22:38.970:INFO::main: Logging initialized @682ms to org.seleniumhq.jetty9.util.log.StdErrLog
16:22:39.638 INFO [WebDriverServlet.&lt;init&gt;] - Initialising WebDriverServlet
16:22:40.476 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 59287
Selenium server running on port 59287
hook: define:webserver
hook: prepare:webserver
step: runTests
chrome 75                CALL init({""browserName"":""chrome"",""version"":""75"",""chromeOptions"":{""binary"":""C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"",""args"":[""start-maximized""]},""variant"":""""})
chrome 75                POST /session {""desiredCapabilities"":{""browserName"":""chrome"",""version"":""75"",""chromeOptions"":{""binary"":""C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"",""args"":[""start-maximized""]},""variant"":"""",""javascriptEnabled"":true,""platform"":""ANY""}}
16:22:44.347 INFO [ActiveSessionFactory.apply] - Capabilities are: {
  ""browserName"": ""chrome"",
  ""chromeOptions"": {
    ""binary"": ""C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"",
    ""args"": [
      ""start-maximized""
    ]
  },
  ""javascriptEnabled"": true,
  ""variant"": """",
  ""version"": ""75""
}
16:22:44.349 INFO [ActiveSessionFactory.lambda$apply$11] - Matched factory org.openqa.selenium.grid.session.remote.ServicedSession$Factory (provider: org.openqa.selenium.chrome.ChromeDriverService)
Starting ChromeDriver 2.43.600210 (68dcf5eebde37173d4027fa8635e332711d2874a) on port 2488
Only local connections are allowed.
16:22:47.850 INFO [ProtocolHandshake.createSession] - Detected dialect: OSS
chrome 75                RESPONSE init({""browserName"":""chrome"",""version"":""75"",""chromeOptions"":{""binary"":""C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"",""args"":[""start-maximized""]},""variant"":""""})
chrome 75                CALL get(""http://localhost:8081/components/undefined/generated-index.html?cli_browser_id=0"")
chrome 75                POST /session/:sessionID/url {""url"":""http://localhost:8081/components/undefined/generated-index.html?cli_browser_id=0""}
16:22:48.253 INFO [RemoteSession$Factory.lambda$performHandshake$0] - Started new session a21a3321683b76d725efa872eeb59d5b (org.openqa.selenium.chrome.ChromeDriverService)
[BABEL] Note: The code generator has deoptimised the styling of undefined as it exceeds the max of 500KB.
Test client opened sideband socket
chrome 75                Beginning tests via http://localhost:8081/components/undefined/generated-index.html?cli_browser_id=0
chrome 75                CALL maximize()
chrome 75                POST /session/:sessionID/window/function(err)%20%7B%0A%20%20%20%20%20%20if(err)%20%7B%0A%20%20%20%20%20%20%20%20err.message%20=%20%27[%27%20+%20name%20+%20niceArgs(fargs.all)%20+%20%22]%20%22%20+%20err.message;%0A%20%20%20%20%20%20%20%20if(fargs.callback)%20%7B%20fargs.callback(err);%20%7D%0A%20%20%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20var%20cbArgs%20=%20__slice.call(arguments,%200);%0A%20%20%20%20%20%20%20%20_this.emit(%27command%27,%20%22RESPONSE%22%20,%20name%20+%20niceArgs(fargs.all),%0A%20%20%20%20%20%20%20%20%20%20niceResp(_.drop(cbArgs)));%0A%20%20%20%20%20%20%20%20if(fargs.callback)%20%7B%20fargs.callback.apply(null,%20cbArgs);%20%7D%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%7D/maximize
chrome 75                RESPONSE get(""http://localhost:8081/components/undefined/generated-index.html?cli_browser_id=0"")
chrome failed to maximize
chrome 75                CALL title()
chrome 75                GET /session/:sessionID/title
chrome 75                RESPONSE title()
chrome 75                ✖ test/hello-world-test.html

  Timed out loading http://localhost:8081/components/undefined/test/hello-world-test.html
    &lt;unknown&gt; at   &lt;unknown&gt; at /components/wct-browser-legacy/browser.js:733:0

chrome 75                Tests failed: 1 failed tests
chrome 75                CALL quit()
chrome 75                DELETE /session/:sessionID
chrome 75                RESPONSE quit()
chrome 75                BrowserRunner complete
Test run ended in failure: 1 failed tests
hook: cleanup

chrome 75 (0/0/1)


Error: 1 failed tests
</code></pre>

<p><a href=""https://i.stack.imgur.com/2SFSk.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2SFSk.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/57064334/during-wct-test-failed-to-load-resource-the-server-responded-with-a-status-of,"['unit-testing', 'polymer', 'web-component', 'wct']",573,True,2,1
How to run a Unit-Test for ESP32 without flashing it?,"<p>Knowing from other languages and platforms we want to use Unit-Testing during the Build-Process BEFORE the code is flashed to the hardware. This should be possible for simple functions tests which have no need for the ESP32 hardware.</p>

<p>But as we understand yet the C++ code is compiled (and linked) for the ESP32 chip and shall not run on the developing system or in a CI/CD pipeline.</p>

<p>Is there any way to emulate ESP32 (for C++) or run Unit-Tests on any other way on another systems?</p>

<hr>

<p>note: We are using 'platformio' for the build.</p>
",https://stackoverflow.com/questions/58710050/how-to-run-a-unit-test-for-esp32-without-flashing-it,"['c++', 'unit-testing', 'arduino', 'esp32', 'platformio']",726,True,2,1
How can I mock a method which is not defined in the interface?,"<p>In my php file I am using <code>Zend\Cache\Storage\StorageInterface</code>. I have bind this interface with <code>Zend\filesystem</code> cache. I have to unit test the main php file. Problem is <strong>StorageInterface</strong> does not define flush method. <strong>Filesystem</strong> have flush method from different interface.</p>

<p>In my unit testing I am trying to mock the <strong>StorageInterface</strong> but problem is it gives an error stating that flush is not defined. How can I stub the flush method?</p>

<p>Binding:</p>

<pre class=""lang-php prettyprint-override""><code>$container-&gt;bindIf(
            ""Zend\\Cache\\Storage\\StorageInterface"",
            function () {
                $directoryPath = ""/tmp/zend_report_cache"";
                if (!file_exists($directoryPath) &amp;&amp; !mkdir($directoryPath)) {
                    throw new Exception(""Failed to create directory [directoryPath=$directoryPath]"");
                }
                return \Zend\Cache\StorageFactory::factory(array(
                    'adapter' =&gt; array(
                        'name' =&gt; 'filesystem',
                        'options' =&gt; array(
                            'cache_dir' =&gt; $directoryPath
                        ),
                    ),
                    'plugins' =&gt; array('serializer'),
                ));
            }
        );
</code></pre>

<p>Main.php (only showing relevant code</p>

<pre class=""lang-php prettyprint-override""><code>use Zend\Cache\Storage\StorageInterface;

public function __destruct()
{
    $this-&gt;cache-&gt;flush();
}
</code></pre>

<p>unit test file</p>

<pre class=""lang-php prettyprint-override""><code>private function getCacheMock()
    {
$cacheMock = $this-&gt;setMethods(['execute'])-&gt;createMock(StorageInterface::class);
        $cacheMock-&gt;expects($this-&gt;at(0))-&gt;method('setItem')-&gt;with(CsvReport::HEADER_CACHE_KEY, []);
        $cacheMock-&gt;expects($this-&gt;at(1))-&gt;method('getItem')-&gt;with(CsvReport::HEADER_CACHE_KEY)-&gt;willReturn([]);
        $cacheMock-&gt;expects($this-&gt;at(2))-&gt;method('setItem')-&gt;with(CsvReport::HEADER_CACHE_KEY, ['key1', 'key2', 'key3']);
        $cacheMock-&gt;expects($this-&gt;at(3))-&gt;method('setItem')-&gt;with(0, $this-&gt;getMockRow(0));
        $cacheMock-&gt;expects($this-&gt;at(4))-&gt;method('getItem')-&gt;with(CsvReport::HEADER_CACHE_KEY)-&gt;willReturn(['key1', 'key2', 'key3']);
        $cacheMock-&gt;expects($this-&gt;at(5))-&gt;method('setItem')-&gt;with(CsvReport::HEADER_CACHE_KEY, ['key1', 'key2', 'key3', 'key4']);
        $cacheMock-&gt;expects($this-&gt;at(6))-&gt;method('setItem')-&gt;with(1, $this-&gt;getMockRow(1));
        $cacheMock-&gt;expects($this-&gt;at(7))-&gt;method('getItem')-&gt;with(CsvReport::HEADER_CACHE_KEY)-&gt;willReturn(['key1', 'key2', 'key3', 'key4']);
        $cacheMock-&gt;expects($this-&gt;at(8))-&gt;method('setItem')-&gt;with(CsvReport::HEADER_CACHE_KEY, ['key1', 'key2', 'key3', 'key4', 'key5']);
        $cacheMock-&gt;expects($this-&gt;at(9))-&gt;method('setItem')-&gt;with(2, $this-&gt;getMockRow(2));
        return $cacheMock;
    }
</code></pre>

<p>Error: Trying to configure method ""flush"" which cannot be configured because it does not exist, has not been specified, is final, or is static</p>
",https://stackoverflow.com/questions/56767698/how-can-i-mock-a-method-which-is-not-defined-in-the-interface,"['php', 'phpunit']",337,False,2,0
Function that returns a struct pointer as function that returns an interface,"<p>I have a package exporting a function that returns a struct pointer that I can't control. I'd like to wrap that function to provide a dependency seam so that I can do some unit testing. The idea is that I want a fake rather than what the external package is giving me. </p>

<p>An example looks like:</p>

<pre><code>/////////////////////////////////////
// External Package I can't control.
/////////////////////////////////////
package ex
type Foo struct {
    v int
}

func (f *Foo) GetV() int {
    return f.v
}

func CreateFoo(v int) *Foo {
    return &amp;Foo{v: v}
}

////////////////////////////////////
// Local Package I'm testing.
////////////////////////////////////
type IFoo interface {
    GetV() int
}

type factory = func(v int) IFoo
var factoryFn factory = ex.CreateFoo
</code></pre>

<p>This results in the error:
<code>cannot use CreateFoo (type func(int) *Foo) as type func(int) IFoo in assignment</code></p>

<p>Since I think that <code>*Foo</code> is an <code>IFoo</code>, why not? What am I missing? Is there a way to achieve what I'm trying to do, giving myself a hook like that?</p>

<p>Playground link to example: <a href=""https://play.golang.org/p/FDckAQGNRgA"" rel=""nofollow noreferrer"">https://play.golang.org/p/FDckAQGNRgA</a></p>
",https://stackoverflow.com/questions/55367797/function-that-returns-a-struct-pointer-as-function-that-returns-an-interface,['go'],315,True,2,1
Dart Mockito: spies?,"<p>I don't see any mentions of spies support in Mockito for dart in the latest versions.</p>

<p>In the changelog:</p>

<blockquote>
  <p>2.0.0-dev #
  Remove export of spy and any dart:mirrors based API from mockito.dart. Users may import as package:mockito/mirrors.dart going forward.
  Deprecated mockito_no_mirrors.dart; replace with mockito.dart.
  Require Dart SDK >=1.21.0 &lt;2.0.0 to use generic methods.</p>
  
  <p>0.11.1 #
  Move the reflection-based spy code into a private source file. Now package:mockito/mockito.dart includes this reflection-based API, and a new package:mockito/mockito_no_mirrors.dart doesn't require mirrors.</p>
  
  <p>0.10.0 #
  Added support for spy.</p>
</blockquote>

<p>Is there any support for spies in the context of unit-testing in Dart?</p>
",https://stackoverflow.com/questions/55834733/dart-mockito-spies,"['unit-testing', 'dart', 'spy']",338,False,2,0
Ruby on Rails Fixtures in sub-directories,"<p>I'm using Rails unit testing and fixtures framework. Unless there's a configuration I haven't seen, I can't use the ""Advanced Fixtures"" (no id objects) from fixtures in sub-directories:</p>

<p>fixtures/people.yml</p>

<pre><code>_fixture:
  model_class: Person

myself:
  first_name: Me
  last_name: Myself
</code></pre>

<p>The following call will pass as expected:</p>

<pre><code>fixtures :people
assert(people(:myself)))
</code></pre>

<p>while this one will not (after I move people.yml to subdir):</p>

<pre><code>fixtures ""subdir/people""
assert(people(:myself)))
</code></pre>

<p>In the later case, the error I get is this:</p>

<pre><code>NoMethodError: undefined method `people'
</code></pre>

<p>Using Advanced Fixtures seem valuable but having all of my fixture files in the root of /fixtures seems missing something. I have a few test files and I'd like to have various tests use different fixtures directories.</p>

<p>Any input will be appreciated.</p>
",https://stackoverflow.com/questions/58205691/ruby-on-rails-fixtures-in-sub-directories,['ruby-on-rails'],823,True,2,2
Is it possible to execute test cases sequentially in Android?,"<p>I have written multiple test cases in an Android project but I want to execute test cases one after another. That means sequential execution need to occur. </p>

<blockquote>
  <p>When the first test case is complete then another test case will be
  executed
  For example if we have two screens Login and Home Page then after the successful test case of the Login it should execute test case for Home Page</p>
</blockquote>

<p>I am a beginner for the Unit testing. I have tried <a href=""https://stackoverflow.com/questions/10127052/how-to-programmatically-execute-a-test-suite-using-junit4"">this</a> but not working.</p>

<p>How this will be possible? Here is my code:</p>

<p><strong>MainActivity</strong></p>

<pre><code>class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        supportFragmentManager.beginTransaction().add(R.id.container, ListFragment()).commitAllowingStateLoss()
    }
}
</code></pre>

<p>Test Case for Main screen</p>

<p><strong>MainActivityTest</strong></p>

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

    @get: Rule
    var signInActivityTestRule = ActivityTestRule(MainActivity::class.java)

    private var signInActivity: MainActivity? = null

    @Test
    fun testEventFragment() {
        signInActivity = signInActivityTestRule.activity
        val container = signInActivity!!.findViewById&lt;FrameLayout&gt;(R.id.container)
        Assert.assertNotNull(container)

        val fragment: Fragment = ListFragment()
        signInActivity!!.supportFragmentManager.beginTransaction().add(container.id, fragment).commitAllowingStateLoss()

        getInstrumentation().waitForIdleSync()
        val jUnitCore = JUnitCore()
        val computer = Computer()
        jUnitCore.run(computer, ListFragmentTest::class.java)
    }
}
</code></pre>
",https://stackoverflow.com/questions/54320930/is-it-possible-to-execute-test-cases-sequentially-in-android,"['android', 'unit-testing', 'testing', 'kotlin', 'instrumentation']",344,False,2,0
Which is better for Android MVVM package by feature or package by layer?,"<p>Another ""which is better"" question, I know these are highly subjective.  My definition for better would be:</p>

<ol>
<li>Being used by the best dev teams</li>
<li>Best for unit testing</li>
<li>Most modular / easiest to build out a prod app</li>
<li>What Google recommends (this is where I'm most confused)</li>
</ol>

<p>All of the Android blueprints use package-by-feature:</p>

<p><a href=""https://github.com/googlesamples/android-architecture"" rel=""noreferrer"">https://github.com/googlesamples/android-architecture</a></p>

<pre><code>/tasks
/addedittask
/taskdetail
</code></pre>

<p>and all of the architecture components samples using package by layer:</p>

<p><a href=""https://github.com/googlesamples/android-architecture-components"" rel=""noreferrer"">https://github.com/googlesamples/android-architecture-components</a></p>

<pre><code>/db
/model
/ui
/persistence
</code></pre>

<p>I'm confused because at the bottom of the Architecture Components site, it actually has links to the Android MVP and MVVM blueprint samples, which seems to me to be contradictory.  </p>
",https://stackoverflow.com/questions/54508117/which-is-better-for-android-mvvm-package-by-feature-or-package-by-layer,"['android', 'mvvm', 'android-architecture-components']",2901,True,7,2
How to write unit testable bash shell code?,"<p>In the OOP universum, there is a lot of <a href=""https://stackoverflow.com/questions/1007458/writing-unit-testable-code"">information</a> on how to desgin and refactor code to make it unit testing friendly. But I wonder, how to apply/translate those principles/practices (make <a href=""https://stackoverflow.com/questions/36219223/shell-script-unit-testing-how-to-mockup-a-complex-utility-program"">mocking</a> easier etc.) to shell scripting, which is obviously different programming.</p>

<p>I have to tackle a very huge code base; many executable and non-executable procedures, large functions, big global state, many environment variables, and everywhere (unnecessary) interprocess communication and file handling through redirection/pipelines and (unnecessary) use of external utilities.</p>

<p>How to refactor shell code (or design it in the beginning) to be able to make ""good"" automated unit tests with a framework like bats and a mocking-plugin?</p>
",https://stackoverflow.com/questions/54529245/how-to-write-unit-testable-bash-shell-code,"['bash', 'shell', 'unit-testing', 'mocking', 'bats-core']",2615,True,12,3
TempData can only be accessed once?,"<p>Mt textbook says TempData persists until it is read, which means it will get destroy after it has been read, but I do see some code in a view like this:</p>

<pre><code>@if (TempData[""message""] != null)
{
   &lt;div class=""alert alert-success""&gt;@TempData[""message""]&lt;/div&gt;
}
</code></pre>

<p>so I'm confused, isn't that <code>TempData[""message""] != null</code> already access TempData, how come it can still be accessed in the <code>&lt;div&gt;</code>?</p>

<p>another question is that, let's say we have a XXXController and one of action method uses TempData as:</p>

<pre><code>[HttpPost]
public IActionResult Edit(Product product)
{
   ...
    TempData[""message""] = $""{product.Name} has been saved"";
   ...
}
</code></pre>

<p>when doing unit testing using Xunit and Moq,code is like this:</p>

<pre><code>Mock&lt;ITempDataDictionary&gt; tempData = new Mock&lt;ITempDataDictionary&gt;();
XXXController target = new XXXController(mock.Object)
{
   TempData = tempData.Object
}
</code></pre>

<p>why do I need to initial the TempData, isn't that when controller instanced is created, we can assign TempData immediately?</p>
",https://stackoverflow.com/questions/57157757/tempdata-can-only-be-accessed-once,"['c#', 'asp.net-core-mvc', 'razorengine']",1208,True,1,1
How can I solve problem with vuex and unit-testing?,"<p>I am trying to write and run unit-testing first time with mocha and faced some problem.
I have a component <code>Table.vue</code> wrote with vuetify</p>

<pre><code>    &lt;v-container&gt;
        &lt;h1&gt;Table&lt;/h1&gt;
        &lt;v-layout
                text-center
                wrap
        &gt;
            &lt;v-simple-table v-if=""table.length""&gt;
                &lt;template v-slot:default&gt;
                    &lt;thead&gt;
                    &lt;tr&gt;
                        &lt;th class=""text-left""&gt;Id&lt;/th&gt;
                        &lt;th class=""text-left""&gt;Name&lt;/th&gt;
                        &lt;th class=""text-left""&gt;Description&lt;/th&gt;
                        &lt;th class=""text-left""&gt;Action&lt;/th&gt;
                    &lt;/tr&gt;
                    &lt;/thead&gt;
                    &lt;tbody&gt;
                    &lt;tr v-for=""(item, index) in table"" :key=""index""&gt;
                        &lt;td&gt;{{ item.id }}&lt;/td&gt;
                        &lt;td&gt;{{ item.name }}&lt;/td&gt;
                        &lt;td&gt;{{ item.description }}&lt;/td&gt;
                        &lt;td&gt;
                            &lt;v-btn
                                    color=""blue""
                                    :to=""{name: 'create', params: { item: item, id: item.id }}""
                            &gt;
                                Update
                            &lt;/v-btn&gt;
                            &lt;v-btn
                                    color=""red""
                                    @click=""show(item)""
                            &gt;
                                Delete
                            &lt;/v-btn&gt;
                        &lt;/td&gt;
                    &lt;/tr&gt;
                    &lt;/tbody&gt;
                &lt;/template&gt;
            &lt;/v-simple-table&gt;
        &lt;/v-layout&gt;
        &lt;v-btn
                :to=""{name: 'create'}""
                color=""primary""
        &gt;
            &lt;span class=""mr-2""&gt;Create&lt;/span&gt;
        &lt;/v-btn&gt;
        &lt;modal name=""hello-world""&gt;
            &lt;v-container&gt;
                &lt;v-layout
                        text-center
                        wrap
                &gt;
                    Are you sure you eant to remove this item?
                &lt;/v-layout&gt;
                &lt;v-layout
                        text-center
                        wrap
                &gt;
                    &lt;v-btn
                            color=""red""
                            @click=""deleteItem""
                    &gt;
                        Yes
                    &lt;/v-btn&gt;
                    &lt;v-btn
                            color=""primary""
                            @click=""hide""
                    &gt;
                        No
                    &lt;/v-btn&gt;
                &lt;/v-layout&gt;
            &lt;/v-container&gt;
        &lt;/modal&gt;
    &lt;/v-container&gt;
&lt;/template&gt;

&lt;script&gt;
    import { mapState, mapActions } from 'vuex'
    export default {
        name: ""Table"",
        data() {
            return {
                itemToRemove: null
            }
        },
        methods: {
            ...mapActions([
                'removeItem'
            ]),
            show (item) {
                this.$modal.show('hello-world');
                this.itemToRemove = item
            },
            hide () {
                this.$modal.hide('hello-world');
                this.itemToRemove = null
            },
            deleteItem () {
                this.removeItem(this.itemToRemove)
                this.hide()
            }
        },
        computed:
            mapState({
            table: state =&gt; state.table.table
        })
    }
&lt;/script&gt;

&lt;style scoped&gt;

&lt;/style&gt;
</code></pre>

<p>And I want to run test there. I have file <code>table.spec.js</code> inside <code>tests/unit</code> folder</p>

<pre><code>import { expect } from 'chai'
import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import Table from '@/components/Table.vue'
const localVue = createLocalVue()
localVue.use(Vuex)
const store = new Vuex.Store({
    state: {}
})

describe('Table.vue', () =&gt; {
    it('renders h1 tag', () =&gt; {
    const wrapper = shallowMount(Table, {localVue, store})
    expect(wrapper.find('h1').text().equal('Table'))
})
})
</code></pre>

<p>When I run command <code>npm run test:unit</code> I have error <code>1) Table.vue
       renders h1 tag:
     TypeError: Cannot read property 'table' of undefined</code>
previously it was error with text <code>Cannot read property 'state' of undefined</code></p>

<p>I tried to include vuex inside tests, but it is my first time with unit-test and looks like I do something wrong</p>

<p>I need my test to be passed and maybe someone can help me to write new test for some event, for example click button and call action. Thanks in advance</p>
",https://stackoverflow.com/questions/58475075/how-can-i-solve-problem-with-vuex-and-unit-testing,"['unit-testing', 'vue.js', 'mocha.js', 'vuex']",147,True,1,1
any idea why sinon is not producing an xml response object?,"<p>that I use mocha+sinonjs for unit testing. So far it worked well, but now I try to run a unit test which should produce an xml response on an ajax request. This works up until the point where I want to query the request.responseXML object, which is always null, despite having passed all needed parameters for Sinon to parse the xml. I have added a small typescript based unit test to show the problem.</p>

<pre class=""lang-js prettyprint-override""><code>describe('Sinon XML Problem', function () {
    it(""must work with xml"", function () {
        let FakeXMLHTTPequest = sinon.useFakeXMLHttpRequest();

        var requests = this.requests = [];
        FakeXMLHTTPequest.onCreate = function (xhr) {
            requests.push(xhr);
        };
        let xhr: any = new FakeXMLHTTPequest();
        requests[0].responseType = 'document';
        requests[0].open('GET', '/xmlhttprequest/xml', false);

        requests[0].onreadystatechange = function () {
            if (requests[0].readyState == 4) {
                expect(requests[0].responseXML != null).to.be.true;
            }
        };

        requests[0].send();

        requests[0].respond(200, {'Content-Type': 'text/xml'}, `
    &lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
    &lt;partial-response&gt;
        &lt;changes&gt;
            &lt;update id=""value_1""&gt;&lt;![CDATA[&lt;span id=""out1""&gt;2&lt;/span&gt;]]&gt;&lt;/update&gt;
            &lt;update id=""javax.faces.ViewState""&gt;&lt;![CDATA[j_id1:j_id3]]&gt;&lt;/update&gt;
        &lt;/changes&gt;
    &lt;/partial-response&gt;
    `);

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

<p>the result from requests[0].responseXML should be anything but null, but the test fails with a null on the responseXML. Does anyone know why?</p>
",https://stackoverflow.com/questions/58371848/any-idea-why-sinon-is-not-producing-an-xml-response-object,"['typescript', 'unit-testing', 'xmlhttprequest', 'sinon', 'sinon-chai']",87,False,1,0
Firebase functions: How to stub firebase-admin functions when testing offline,"<p>Trying to follow along with the docs for testing Firease functions here <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing</a> but its not clear on how to stub the firebase-admin.database using sinon. I've provided the function code, mocha test, and console output for this error below. From the error output it seems like when the function is called <code>admin.initializeApp();</code> is being called but has not been stubbed correctly beforehand in the test. </p>

<p>Function code: </p>

<pre><code>const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();   

// add new users to the database
exports.account = functions.auth.user().onCreate(event =&gt; {
  // console.log('addAccount()', event);
  const { uid, providerData } = event;
  const email = providerData[0].email;

  return admin
    .database()
    .ref('/users/' + uid)
    .set({ email, uid });
});
</code></pre>

<p>Test to reproduce the issue: </p>

<pre><code>const sinon = require('sinon');
const chai = require('chai');
const assert = chai.assert;
const admin = require('firebase-admin');
const test = require('firebase-functions-test')();

describe('Cloud Functions', () =&gt; {
  let myFunctions, adminInitStub, adminDatabaseStub;

  before(() =&gt; {
    adminInitStub = sinon.stub(admin, 'initializeApp');
    adminDatabaseStub = sinon.stub(admin, 'database');
    myFunctions = require('../index');
  });

  after(() =&gt; {
    adminInitStub.restore();
    adminDatabaseStub.restore();
    test.cleanup();
  });

  describe('account', () =&gt; {
    it('should write to /users', () =&gt; {
      // given
      const setParam = { email: 'test@test.com', uid: 1234 };

      const setStub = sinon.stub();
      setStub.withArgs(setParam).returns(true);

      const refStub = sinon.stub();
      refStub.withArgs('/users/1234').returns({ set: setStub });

      adminDatabaseStub.returns({ ref: refStub });

      const wrapped = test.wrap(myFunctions.account);

      const event = {
        uid: 1234,
        providerData: [{
          email: 'test@test.com'
        }]
      };

      // when
      const actual = wrapped(event);

      // then
      return assert.equal(actual, true);
    });
  });
});
</code></pre>

<p>Error in console</p>

<pre><code>Cloud Functions
    account
      1) should write to /users


  0 passing (53ms)
  1 failing

  1) Cloud Functions
       account
         should write to /users:
     Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
      at FirebaseAppError.FirebaseError [as constructor] (node_modules/firebase-admin/lib/utils/error.js:42:28)
      at FirebaseAppError.PrefixedFirebaseError [as constructor] (node_modules/firebase-admin/lib/utils/error.js:88:28)
      at new FirebaseAppError (node_modules/firebase-admin/lib/utils/error.js:122:28)
      at FirebaseNamespaceInternals.app (node_modules/firebase-admin/lib/firebase-namespace.js:101:19)
      at FirebaseNamespace.app (node_modules/firebase-admin/lib/firebase-namespace.js:402:30)
      at FirebaseNamespace.ensureApp (node_modules/firebase-admin/lib/firebase-namespace.js:418:24)
      at FirebaseNamespace.fn (node_modules/firebase-admin/lib/firebase-namespace.js:280:30)
      at Function.exports.account.functions.auth.user.onCreate.event [as run] (index.js:65:21)
      at wrapped (node_modules/firebase-functions-test/lib/main.js:68:30)
      at Context.it (test/index.test.js:45:22)
</code></pre>

<p>Solution</p>

<p>Update the <code>adminDatabaseStub.get()</code> to return a <code>getterFn()</code> function which then returns the <code>ref</code> stub. Thanks @hiranya-jayathilaka</p>

<p>Before </p>

<pre><code>      adminDatabaseStub.returns({ ref: refStub });
</code></pre>

<p>After</p>

<pre><code>adminDatabaseStub.get(function getterFn() {
        return () =&gt; {
          return { ref: refStub };
        };
      });
</code></pre>
",https://stackoverflow.com/questions/57574610/firebase-functions-how-to-stub-firebase-admin-functions-when-testing-offline,"['javascript', 'firebase', 'mocha.js', 'google-cloud-functions', 'firebase-admin']",1746,True,1,1
How to test a callback of a mocked function with jasmine?,"<p>A method of a third party service that I am using has a callback as the second argument. This callback is executed in real life when the response is received from the server.</p>

<p>I want to mock the third party method for unit testing, and supply different response arguments to the callback to ensure that its logic executes correctly. For example to check that the promise is rejected when the status is NOT 'success', or that on success just the saved record is returned and not the whole response.</p>

<p>I am using jasmine for testing.</p>

<pre><code>function save() {
  var deferred = $q.defer();

  thirdPartyService.doSave(record, function callback(response) {
    // How to test the code in here when doSave is mocked?
    if(response.status === 'success') {
      deferred.resolve(response.savedRecord);
    } else {
      deferred.reject(response);
    }
  });

  return deferred.promise;
}
</code></pre>

<p>Example of a test I'd like to run:</p>

<pre><code>// Setup
const successResponse = {
  status: 'success',
  savedRecord: { Id: 'test-id' }
};
// Somehow config the mocked thirdParty.doSave() to use successResponse for the callback.

// Test
myService.save()
  .then(function(response) {
    expect(response.Id).toBe('test-id');
  });;
</code></pre>
",https://stackoverflow.com/questions/59037019/how-to-test-a-callback-of-a-mocked-function-with-jasmine,['jasmine'],809,True,1,1
Electron-Angular: Running Karma errors because of undefined ipcRenderer inside angular component,"<p>I have an Electron application that uses Angular (8) as a front end framework.
I am trying to implement unit testing but keep getting the following error when i start the test:</p>

<pre><code>Chrome 77.0.3865 (Windows 10.0.0) FooterComponent should create FAILED
        TypeError: Cannot read property 'on' of undefined
         ......
</code></pre>

<p>My spec file looks like this:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FooterComponent } from './footer.component';
import { TranslateModule } from '@ngx-translate/core';
import { ElectronService } from '../services';


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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ 
        FooterComponent
      ],
      providers: [ElectronService ],
      imports: [
        TranslateModule.forRoot()
      ]
    })
    .compileComponents();
  }));

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

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

});
</code></pre>

<p>Inside the Angular component i subscribe to an Electron event:</p>

<pre><code>constructor(private electronService: ElectronService) {
   this.electronService.ipcRenderer.on('appVersion', (event, arg) =&gt; {
      this.appVersion = arg;
   });
}
</code></pre>

<p>This is what causes the test to fail, the ipcRenderer is undefined. Does anyone know how i can unit test an Angular component that has Electrons IPC used inside of it ?</p>

<p>The electronservice that is used in the component has been added to the providers inside the spec file.</p>
",https://stackoverflow.com/questions/58447470/electron-angular-running-karma-errors-because-of-undefined-ipcrenderer-inside-a,"['angular', 'unit-testing', 'electron', 'karma-jasmine', 'ipcrenderer']",420,True,1,1
"What is done(), and where is it documented?","<p>I'm working to understand unit testing in JavaScript, using Mocha/Sinon/Chai. I have seen the function <code>done()</code> used. But I cannot seem to find documentation for this function. It does not seem to be a part of the JavaScript language. If it were, I would expect to see it in the Mozilla documentation under <code>[something].prototype.done()</code>. But it's not there. I don't see it under jQuery's documentation, nor under Mocha's. </p>

<p><a href=""https://stackoverflow.com/questions/21175123/how-do-i-use-mocha-to-do-asynchronous-tests-using-done"">On another thread</a>, I see this example of <code>done()</code>:</p>

<pre><code>it('should have data.', function () {
    db.put(collection, key, json_payload)
        .then(function (result) {
            result.should.exist;
            done();
        })
        .fail(function (err) {
            err.should.not.exist;
            done();
        })
})
</code></pre>

<p>What is <code>done()</code>, what language or tooling is it a part of, and where is the documentation for it? <strong>Is <code>done()</code> just a naming convention for a callback function?</strong></p>
",https://stackoverflow.com/questions/57541209/what-is-done-and-where-is-it-documented,"['javascript', 'unit-testing', 'mocha.js', 'sinon']",180,True,1,1
JUnit: best strategy for placing test-methods,"<p>I started a project and using JUnit for the 1st time.</p>

<p>Whats the best practice of putting testcases?</p>

<ul>
<li><p>1 testclass for every ""real"" class.</p></li>
<li><p>1 testclass for every package or even the complete project.</p></li>
<li><p>Testmethods in the ""real"" class without a testclass.</p></li>
</ul>

<p>As far I see I can technically do every 3 ways but I do not have experience in that so I ask for some guidance to do it right from the very beginning.</p>

<p><strong>EDIT</strong></p>

<p>I am talking about code unit testing. I am using maven too but I think that is not important for my question.</p>
",https://stackoverflow.com/questions/55839228/junit-best-strategy-for-placing-test-methods,"['java', 'junit']",122,True,1,4
Share the same encoder setting for different appenders in logback xml,"<p>I have an encoder using <code>net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder</code> to configure the log content via a mix of stock providers, patterns and custom providers. The same is to be used in different appenders, e.g. console, file, rolling file and a custom one for unit testing. I don't want to repeat the same configuration in every appender as it is exactly the same, so I wonder if there is a way to share it across different appenders?</p>

<p>e.g.</p>

<pre><code>&lt;configuration&gt;
  &lt;appender name=""FILE_LOG"" class=""ch.qos.logback.core.FileAppender""&gt;
    &lt;encoder class=""net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder""&gt;
      ... configuration can be shared ...
    &lt;/encoder&gt;
  &lt;/appender&gt;
  &lt;appender name=""CONSOLE"" class=""ch.qos.logback.core.ConsoleAppender""&gt;
    &lt;encoder class=""net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder""&gt;
      ... repeated the exact same configuration ...
    &lt;/encoder&gt;
  &lt;/appender&gt;
</code></pre>

<p>I know there is this ""include"" feature, but it seems it has to start from the root level (i.e. <code>appender</code>) for inclusion. Is there a way to ""include"" at the <code>encoder</code> level?</p>
",https://stackoverflow.com/questions/58404301/share-the-same-encoder-setting-for-different-appenders-in-logback-xml,"['spring', 'spring-boot', 'logging', 'logback', 'logstash-logback-encoder']",1205,True,1,1
skcuda.fft not the same as numpy.fft.rfft?,"<p>I was trying to test the output of an fft against a numpy fft for unit testing, I realized soon after when it failed, it wasn't because I had done something wrong, but skcuda literally doesn't produce the same answer. I knew they were going to be different by a bit, but at least one of the numbers is several orders of magnitude off of what numpy produces, and both <code>allclose</code> and <code>almost_equal</code> return massive errors (33% and 25% for <code>rtol=1e-6</code>, 16% for <code>atol=1e-6</code>).  What am I doing wrong here? Can I fix this?</p>

<p>Test file:</p>

<pre><code>import pycuda.autoinit
from skcuda import fft
from pycuda import gpuarray
import numpy as np

def test_skcuda():
    array_0 = np.array([[1, 2, 3, 4, 5, 4, 3, 2, 1, 0]], dtype=np.float32)
    array_1 = array_0 * 10
    time_domain_signal = np.array([array_0[0], array_1[0]], dtype=np.float32)
    fft_point_count = 10
    fft_plan = fft.Plan(fft_point_count, np.float32, np.complex64,
                        batch=2)
    fft_reserved = gpuarray.empty((2, fft_point_count // 2 + 1), dtype=np.complex64)
    fft.fft(gpuarray.to_gpu(time_domain_signal), fft_reserved, fft_plan)

    np.testing.assert_array_almost_equal(
        np.fft.rfft(time_domain_signal, fft_point_count), fft_reserved.get())

test_skcuda()
</code></pre>

<p>Assertion failure:</p>

<pre><code>AssertionError: 
Arrays are not almost equal to 6 decimals

(mismatch 25.0%)
 x: array([[ 2.500000e+01+0.000000e+00j, -8.472136e+00-6.155367e+00j,
        -1.193490e-15+2.331468e-15j,  4.721360e-01-1.453085e+00j,
         2.664535e-15+0.000000e+00j,  1.000000e+00+0.000000e+00j],...
 y: array([[ 2.500000e+01+0.000000e+00j, -8.472136e+00-6.155367e+00j,
         8.940697e-08+5.960464e-08j,  4.721359e-01-1.453085e+00j,
         0.000000e+00+0.000000e+00j,  1.000000e+00+0.000000e+00j],...
</code></pre>

<p>printed output:</p>

<pre><code>#numpy
[[ 2.50000000e+01+0.00000000e+00j -8.47213595e+00-6.15536707e+00j
  -1.19348975e-15+2.33146835e-15j  4.72135955e-01-1.45308506e+00j
   2.66453526e-15+0.00000000e+00j  1.00000000e+00+0.00000000e+00j]
 [ 2.50000000e+02+0.00000000e+00j -8.47213595e+01-6.15536707e+01j
  -1.11022302e-14+2.39808173e-14j  4.72135955e+00-1.45308506e+01j
   3.55271368e-14+7.10542736e-15j  1.00000000e+01+0.00000000e+00j]]

#skcuda
[[ 2.5000000e+01+0.0000000e+00j -8.4721355e+00-6.1553669e+00j
   8.9406967e-08+5.9604645e-08j  4.7213593e-01-1.4530852e+00j
   0.0000000e+00+0.0000000e+00j  1.0000000e+00+0.0000000e+00j]
 [ 2.5000000e+02+0.0000000e+00j -8.4721359e+01-6.1553673e+01j
   1.4305115e-06-4.7683716e-07j  4.7213597e+00-1.4530851e+01j
   0.0000000e+00+1.9073486e-06j  1.0000000e+01+0.0000000e+00j]]
</code></pre>
",https://stackoverflow.com/questions/56811521/skcuda-fft-not-the-same-as-numpy-fft-rfft,"['python', 'numpy', 'fft', 'pycuda', 'cufft']",395,True,1,3
Grails 4.0 Mock service method in controller test,"<p>I have a controller like this:</p>

<pre><code>class NotificationApiController {

    def countService

    def getCount() {
        def results = countService.getCount()

        render results as JSON
    }
}
</code></pre>

<p>And the controller test like this:</p>

<pre><code>Closure doWithSpring() {{ -&gt;
        countService(CountService)
    }}

CountService countService

def setup() {
}

def cleanup() {
}

void ""test getCount method""() {
        given:
        def countService = Mock(CountService) {
            1 * getCount(_) &gt;&gt; [count: 2]
        }
        when:
        def y = controller.getCount()

        then:
        y == [count: 2]
    }
</code></pre>

<p>It appears it always calls into the actual CountService injected in Closure doWithSpring(), not my mock countService, but without the definition of Closure doWithSpring()..., I will get this error </p>

<pre><code>Cannot invoke method getCount() on null object
java.lang.NullPointerException: Cannot invoke method getCount() on null object
</code></pre>

<p>The documentation on unit testing in 4.0 is really limited and I am not exactly sure how should I do this. I see some samples in Grails 2.3 or 3.3. version, but they all seems not working for me, mostly due to the difference of Spock and Mixin framework I guess. Any suggestions on how to do this?</p>
",https://stackoverflow.com/questions/59242388/grails-4-0-mock-service-method-in-controller-test,"['unit-testing', 'grails', 'spock', 'grails-4']",539,True,1,1
Enzyme/Jest React Testing - Shallow connected component with react-redux &gt; 6,"<p>We use Enzyme and Jest for testing.
Updated to the latest version of react-redux in our code base, and all of the connected component test cases started failing (Version 6).
Using </p>

<pre><code>import { createMockStore } from 'redux-test-utils';
</code></pre>

<p>to create store</p>

<p>Test cases that worked with older version:</p>

<pre><code>const wrapper = shallow(&lt;SomeConnectedComponent /&gt;, {context: { store }});
</code></pre>

<p>This fails giving error</p>

<p><em>Invariant Violation: Could not find ""store"" in the context of ""Connect(SomeConnectedComponent )"".</em></p>

<p>Reading few posts, got a suggestion to mount and wrap with provider wrapper</p>

<pre><code>const wrapper = mount(&lt;Provider store={store}&gt;&lt;SomeConnectedComponent /&gt;&lt;/Provider&gt;);
</code></pre>

<p>Above code works, but I want it to work with swallow for unit testing. </p>

<p>Edit : </p>

<pre><code>const wrapper = shallow(&lt;Provider store={store}&gt;
&lt;SomeConnectedComponent /&gt;
&lt;/Provider&gt;)
</code></pre>

<p>Above code returns empty shallowWraper object. </p>

<p>What is the best way to swallow connected component with react-redux version > 6</p>
",https://stackoverflow.com/questions/59191129/enzyme-jest-react-testing-shallow-connected-component-with-react-redux-6,"['reactjs', 'unit-testing', 'react-redux', 'jestjs', 'enzyme']",4927,True,6,2
Silverstrip unit test fixture_file is not working,"<p>I am learning SilverStripe and meanwhile trying to integrate unit testing into my simple project as well. I am trying to use $fixture_file to seed the data. But it is not working.</p>

<p>This is my phpunit.xml</p>

<pre><code>&lt;phpunit bootstrap=""vendor/silverstripe/framework/tests/bootstrap.php"" colors=""true""&gt;
    &lt;testsuite name=""Default""&gt;
        &lt;directory&gt;app/tests&lt;/directory&gt;
    &lt;/testsuite&gt;
    &lt;groups&gt;
        &lt;exclude&gt;
            &lt;group&gt;sanitychecks&lt;/group&gt;
        &lt;/exclude&gt;
    &lt;/groups&gt;
&lt;/phpunit&gt;
</code></pre>

<p>This is my PageTest.php</p>

<p>

<pre><code>use SilverStripe\Dev\SapphireTest;

class PageTest extends SapphireTest
{
    static $fixture_file = 'fixtures.yml';

    public function testMyMethod()
    {
        $this-&gt;assertEquals(2, Page::MyMethod());
    }
}
</code></pre>

<p>This is my fixtures.yml</p>

<pre><code>ContactFormSubmission:
    wai:
        Name: Wai
        Email: iljimae.ic@gmail.com
        Message: ThisIsAMessage
</code></pre>

<p>This is my ContactFormSubmission.php</p>

<pre><code>&lt;?php

namespace {

    use SilverStripe\ORM\DataObject;

    class ContactFormSubmission extends DataObject
    {
        private static $db = [
            'Name' =&gt; 'Varchar',
            'Email' =&gt; 'Varchar',
            'Message' =&gt; 'Text',
        ];
    }
}
</code></pre>

<p>When I run the test, I got this error.</p>

<pre><code>Time: 1.06 seconds, Memory: 16.00MB

There was 1 error:

1) PageTest::testMyMethod
SilverStripe\ORM\Connect\DatabaseException: Couldn't run query:

CREATE DATABASE ""ss_tmpdb_1558273911_5783864"" DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci

42000-1044: Access denied for user 'wai'@'%' to database 'ss_tmpdb_1558273911_5783864'

/var/www/vendor/silverstripe/framework/src/ORM/Connect/DBConnector.php:64
/var/www/vendor/silverstripe/framework/src/ORM/Connect/PDOConnector.php:398
/var/www/vendor/silverstripe/framework/src/ORM/Connect/PDOConnector.php:287
/var/www/vendor/silverstripe/framework/src/ORM/Connect/Database.php:143
/var/www/vendor/silverstripe/framework/src/ORM/Connect/Database.php:228
/var/www/vendor/silverstripe/framework/src/ORM/Connect/Database.php:144
/var/www/vendor/silverstripe/framework/src/ORM/Connect/MySQLDatabase.php:381
/var/www/vendor/silverstripe/framework/src/ORM/Connect/DBSchemaManager.php:120
/var/www/vendor/silverstripe/framework/src/ORM/Connect/MySQLSchemaManager.php:231
/var/www/vendor/silverstripe/framework/src/ORM/Connect/Database.php:830
/var/www/vendor/silverstripe/framework/src/ORM/Connect/TempDatabase.php:190
/var/www/vendor/silverstripe/framework/src/Dev/State/FixtureTestState.php:44
/var/www/vendor/silverstripe/framework/src/Dev/State/SapphireTestState.php:68
/var/www/vendor/silverstripe/framework/src/Dev/SapphireTest.php:274
/var/www/vendor/phpunit/phpunit/phpunit:52
</code></pre>

<p>I found out that it cannot connect to the database. I try to override the database configuration in phpunit.xml like this.</p>

<pre><code>&lt;env name=""SS_DATABASE_NAME"" value=""test""/&gt;
</code></pre>

<p>But it is still trying to connect to the temporary database. How can I define the database for unit test in Silverstripe?</p>
",https://stackoverflow.com/questions/56208509/silverstrip-unit-test-fixture-file-is-not-working,"['php', 'phpunit', 'silverstripe', 'functional-testing', 'silverstripe-4']",160,False,1,0
VS Code Python unittest: No tests discovered even when following the tutorial,"<p>I am trying to follow the Python tutorial as per <a href=""https://code.visualstudio.com/docs/python/unit-testing#_create-tests"" rel=""nofollow noreferrer"">https://code.visualstudio.com/docs/python/unit-testing#_create-tests</a>. But every time no tests are discovered and neither I can execute the test file manually: 0 tests are run.</p>

<p><a href=""https://i.stack.imgur.com/E3bz7.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/E3bz7.png"" alt=""the workspace structure and files content""></a>
I have tried doing that on my working workspace and then attempted to start everything from scratch but both times the results are the same. Also, I have tried using Remote - WSL on VS Code Insiders and the classic VS Code:</p>

<blockquote>
<pre><code>Version: 1.34.0-insider (user setup)
Commit: 473af338e1bd9ad4d9853933da1cd9d5d9e07dc9
Date: 2019-05-01T00:22:05.899Z
Electron: 3.1.8
Chrome: 66.0.3359.181
Node.js: 10.2.0
V8: 6.6.346.32
OS: Windows_NT x64 10.0.17134

Version: 1.33.1 (user setup)
Commit: 51b0b28134d51361cf996d2f0a1c698247aeabd8
Date: 2019-04-11T08:27:14.102Z
Electron: 3.1.6
Chrome: 66.0.3359.181
Node.js: 10.2.0
V8: 6.6.346.32
OS: Windows_NT x64 10.0.17134
</code></pre>
</blockquote>

<p><strong>basic.py</strong></p>

<pre class=""lang-py prettyprint-override""><code>
    def just_method(number):
        return number

    if __name__ == ""__main__"":
        print just_method(42)
</code></pre>

<p><strong>basictest.py</strong></p>

<pre class=""lang-py prettyprint-override""><code>    import unittest
    import basic

    class MyBasicTests(unittest.TestCase):

        def default_number(self):
            number = 42
            self.assertEqual(basic.just_method(number), number)

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

<p><strong>settings.json</strong> content:</p>

<pre class=""lang-py prettyprint-override""><code>    {
        ""python.testing.unittestArgs"": [
            ""-v"",
            ""-s"",
            ""."",
            ""-p"",
            ""*test.py""
        ],
        ""python.testing.pyTestEnabled"": false,
        ""python.testing.nosetestsEnabled"": false,
        ""python.testing.unittestEnabled"": true,
        ""python.pythonPath"": ""/usr/bin/python""
    }
</code></pre>

<p>Could you please help to identify the problem? I am pretty sure it is located somewhere on my side.</p>
",https://stackoverflow.com/questions/55969313/vs-code-python-unittest-no-tests-discovered-even-when-following-the-tutorial,"['python', 'visual-studio-code']",1295,True,1,2
Having issue with Symfony 3 Unit testing that has session enabled,"<p>I am new in unit testing. I have Symfony 3 console command application which is using symfony session for temporary data store.</p>

<p>In my unit test class I extend KernelTestCase which give me error while I tested it but if I extend <code>Symfony\Component\HttpKernel\EventListener\TestSessionListener</code> class then the error gone and passed the test.</p>

<p>After some time I realize that it always passed test no mater what I write inside the test case.</p>

<h3>My Console class</h3>

<pre><code>protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Retrieve the argument value using getArgument()
        $csv_name = $input-&gt;getArgument('file');

        // Check file name
        if ($csv_name == 'input.csv') {
            // Get input file from filesystem
            $csvData = array_map('str_getcsv', file($this-&gt;base_path.'/../web/'.$csv_name));
            $formatData = Helpers::formatInputData($csvData);

            // Start session
            $session = new Session();
            $session-&gt;start();

            foreach ($csvData as $key =&gt; $data) {
                if (!empty($data[0])) {
                    $validation = Validator::getInformationData($data, $formatData[$data[1]]);
                    if (!empty($validation)) {
                        $output-&gt;writeln($validation);
                    } else {
                        $output-&gt;writeln('valid');
                    }
                }
            }
        } else {
            $output-&gt;writeln('Invalid file!');
        }
    }
</code></pre>

<h3>My test case</h3>

<pre><code>use Symfony\Component\HttpKernel\EventListener\TestSessionListener as BaseTestSessionListener;

class DocumentCommandTest extends BaseTestSessionListener
{
    /**
     * Test Execute
     *
     */
    public function testExecute()
    {
        $kernel = static::createKernel();
        $kernel-&gt;boot();

        $application = new Application($kernel);
        $application-&gt;add(new DocumentCommand($kernel-&gt;getContainer()));

        $command = $application-&gt;find('identification-requests:process');
        $commandTester = new CommandTester($command);
        $commandTester-&gt;execute(array(
            'command' =&gt; $command-&gt;getName(),
            'file' =&gt; 'input.csv'
        ));

        $output = $commandTester-&gt;getOutput();
        $this-&gt;assertContains('valid',$output);
    }
}
</code></pre>

<p>After that I also tried to extend <code>Symfony\Bundle\FrameworkBundle\Tests\Functional\SessionTest</code></p>

<pre><code>use Symfony\Bundle\FrameworkBundle\Tests\Functional\SessionTest;

class DocumentCommandTest extends SessionTest
{
</code></pre>

<p>but it give me the following error</p>

<pre><code>E.........                                                        10 / 10 (100%)

Time: 4.72 seconds, Memory: 20.00MB

There was 1 error:

1) Tests\AppBundle\Command\DocumentCommandTest::testExecute
InvalidArgumentException: The option ""test_case"" must be set.
</code></pre>

<p>My expected output from console is the following that needs to be tested</p>

<pre><code>$ php bin/console identification-requests:process input.csv
valid
valid
valid
document_number_length_invalid
request_limit_exceeded
valid
document_is_expired
valid
document_type_is_invalid
valid
valid
document_number_invalid
valid
document_issue_date_invalid
</code></pre>
",https://stackoverflow.com/questions/57699632/having-issue-with-symfony-3-unit-testing-that-has-session-enabled,"['php', 'unit-testing', 'session', 'console-application', 'symfony-3.4']",303,True,1,2
How do I save test results from Test Explorer in Visual Studio 2017?,"<p>I have an issue with Visual Studio 2017. I generally run a set of tests locally on my own computer using Test Explorer and using Microsoft's own Unit Testing tools in the Visual Studio library. This can take quite sometime. Problem is, if I close visual studio at any point, the results of these tests are lost forever: the pass, the fail, the output, everything. </p>

<p>I need a way to save the results of my tests in case this happens. I'd love it if VS didn't just wipe my test results like this. </p>

<p>I have to run many tests in different windows, using the command prompt to do this is incredibly laborious.</p>
",https://stackoverflow.com/questions/56958300/how-do-i-save-test-results-from-test-explorer-in-visual-studio-2017,['visual-studio'],10509,True,11,2
How to test small snippets of javascript code without a web browser?,"<p>I am trying to teach beginners javascript. Here is what I am trying to do:</p>

<p>I will give them a snippet of code such as a function with something incorrect:</p>

<pre><code>const square = function(x) {
   return x + x; // Wrong! This will double the number, not square them.
}; 
</code></pre>

<p>They will submit the code back to me.
I would like to write some test cases which would run on their code and evaluate if they are correct.</p>

<p>Does it make sense for them to submit their code as js files, and then I have a node.js project which reads their files and passes values to their functions and tests the response ?</p>

<p>Or does it make more sense to use a unit testing framework like mocha and chai etc ?</p>
",https://stackoverflow.com/questions/58230529/how-to-test-small-snippets-of-javascript-code-without-a-web-browser,"['javascript', 'node.js']",283,True,6,1
How to write a unit test to check if modal shows up after clicking some link,"<p>I am just learning unit testing with Jest/Enzyme - specifically for React/Redux.
I am trying to write a test to check from user perspective (is this correct approach?...) if modal shows up after clicking some link.
Next I want to test if clicking on <code>shade</code> wrapper over <code>modal</code> closes <code>modal</code>.</p>

<p>Modal state (open/closed) is controlled by Redux.</p>

<p>Based on current state from Redux - modal gets appropriate style: <code>modal</code> or <code>invisibleModal</code>.</p>

<p>I have tried to do it by mocking Redux store but I feel it should be done without it - I suppose it would be better to test unconnected component, but please correct me if I'm wrong.</p>

<p>Test so far:</p>

<pre><code>const mockFn = jest.fn();

describe('Contact components', ()=&gt;{
    it('&lt;ContactModal /&gt; renders correctly', ()=&gt;{
        shallow(&lt;ContactModal /&gt;)
    })

    it('&lt;ContactForm /&gt; renders correctly', ()=&gt;{
        shallow(&lt;ContactForm toggleContactModal={mockFn} /&gt;)
    })

});

describe('In contact form link',()=&gt;{
    const link = shallow(&lt;ContactForm toggleContactModal={mockFn}/&gt;)
    const modalWrapper = shallow(&lt;ContactModal /&gt;);

    it('toggleContactModal function is called upon clicking ContactForm',()=&gt;{
        expect(modalWrapper.find('#modal').hasClass('modal')).toBe(false);
        link.simulate('click');

        expect(mockFn.mock.calls.length).toBe(1);
    })
})
</code></pre>

<p>Modal component:</p>

<pre><code>export const ContactModal = props =&gt; {
    return (
        &lt;&gt;
            &lt;div 
                id='modal' 
                className={props.contactModal ? styles.modal : styles.invisibleModal}
            &gt;
                hello from modal
            &lt;/div&gt;
            &lt;div 
                id='shade' 
                className={props.contactModal ? styles.shade : styles.invisibleShade} 
                onClick={props.toggleContactModal}
                onKeyDown={props.toggleContactModal}
            /&gt;
        &lt;/&gt;
    );
};

const mapStateToProps =state=&gt; {
    return {
        contactModal: state.contactModal
    }
}

const mapDispatchToProps = {
    toggleContactModal
}

export default connect(mapStateToProps, mapDispatchToProps)(ContactModal);
</code></pre>

<p>Reducer:</p>

<pre><code>export const contactModal = (state=false, action) =&gt; {
    switch (action.type){
        case TOGGLE_CONTACT_MODAL:
            return !state;
        default:
            return state
    }
}
</code></pre>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/55660127/how-to-write-a-unit-test-to-check-if-modal-shows-up-after-clicking-some-link,"['reactjs', 'redux', 'jestjs', 'enzyme']",18634,True,11,1
How to fix &quot;SVG Not defined&quot; in JEST unit testing,"<p>I'm trying to setup an unit test case for a function defined in a typescript class.  This class is dependent on svg.js.
Now when I am trying to unit test the function with jest, it throws error
SVG.extend or SVG is not a function.</p>

<p>We have tried ways in jest.config.js file for the testEnvironment to be node to jsdom.</p>

<p>Code for ts is as follows
    import SVG from 'svg.js';</p>

<pre><code>export class DrawManager {
  private static _drawingStage : SVG.Nested|undefined;
  private static _canvas : SVG.Doc|undefined;
}

static start(div: string) {
    this._canvas = SVG(div)
    this._drawingStage = this._canvas.nested();
}
</code></pre>

<p>code for unit testing is as follows</p>

<pre><code>import { DrawManager } from './drawmanager';
describe('Test for Draw Manager', () =&gt; {
    it('should process task loader method', () =&gt; {
    DrawManager.start('drawing');
 });
});
</code></pre>

<p>We are expecting output pass to test case without any SVG dependency problem and run the test case with the initiated svg class</p>

<p>Help would be appreciated</p>
",https://stackoverflow.com/questions/54037495/how-to-fix-svg-not-defined-in-jest-unit-testing,"['typescript', 'unit-testing', 'webpack', 'jestjs', 'svg.js']",2233,True,1,1
How do I wire up the firestore emulator with my firebase functions tests?,"<p>Currently we are using 'firebase-functions-test' in online mode to test our firebase functions (as described here <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""noreferrer"">https://firebase.google.com/docs/functions/unit-testing</a>), which we setup like so:</p>

<pre class=""lang-js prettyprint-override""><code>//setupTests.ts
import * as admin from 'firebase-admin';

const serviceAccount = require('./../test-service-account.json');

export const testEnv = require('firebase-functions-test')({
    projectId: 'projectId',
    credential: admin.credential.cert(serviceAccount),
    storageBucket: 'projectId.appspot.com'
});
const testConfig = {
    dropbox: {
        token: 'dropboxToken',
        working_dir: 'someFolder'
    }
};

testEnv.mockConfig(testConfig);

// ensure default firebase app exists:
try {
    admin.initializeApp();
} catch (e) {}
</code></pre>

<p>We would like to move away from testing against an actual firestore instance in our tests, and use the emulator instead.</p>

<p>The docs, issues, and examples I've been able to find on the net are either outdated, or describe how to set up the emulator for testing security rules, or the web frontend.</p>

<p>Attempts using <code>firebase.initializeAdminApp({ projectId: ""my-test-project"" });</code> did not do the trick.</p>

<p>I also tried setting <code>FIRESTORE_EMULATOR_HOST=[::1]:8080,127.0.0.1:8080</code></p>

<p>So the question is: How can I initialise the firebaseApp in my tests, so that my functions are wired up to the firestore emulator?</p>
",https://stackoverflow.com/questions/57191497/how-do-i-wire-up-the-firestore-emulator-with-my-firebase-functions-tests,"['firebase', 'google-cloud-firestore', 'google-cloud-functions', 'firebase-tools']",1655,True,11,1
How to setup a firebase firestore and cloud function test suit with firebase Emulator for JS development,"<p>According to the following google I/O (2019) post of the firebase team the new emulator allows us to combine firebase/database plus cloud function to fully simulate our firebase server codes. That should also mean we should be able to write tests for it.</p>

<blockquote>
  <p>we’re releasing a brand new Cloud Functions emulator that can also
  communicate with the Cloud Firestore emulator. So if you want to build
  a function that triggers upon a Firestore document update and writes
  data back to the database you can code and test that entire flow
  locally on your laptop (Source: <a href=""https://firebase.googleblog.com/2019/05/whats-new-Google-IO-2019.html"" rel=""noreferrer"">Firebase Blog Entry</a>)</p>
</blockquote>

<p>I could find multiple resources looking/describing each individual simulation, but no all together</p>

<ol>
<li><a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""noreferrer"">Unit Testing Cloud Function</a></li>
<li><a href=""https://firebase.google.com/docs/database/security/test-rules-emulator"" rel=""noreferrer"">Emulate Database writes</a></li>
<li><a href=""https://firebase.google.com/docs/firestore/security/test-rules-emulator"" rel=""noreferrer"">Emulate Firestore writes</a></li>
</ol>
",https://stackoverflow.com/questions/56236348/how-to-setup-a-firebase-firestore-and-cloud-function-test-suit-with-firebase-emu,"['firebase', 'google-cloud-firestore', 'google-cloud-functions']",7266,True,15,2
How do I test a function&#39;s logic but ignore the method calls?,"<p>I'm writing a Rspec test for existing code that I've added some logic to that I want to ensure is working properly. I do not care about the returned values, just that the logic works on an object that I pass to it. For simplicity here is an example of very a basic function from within a class I have built:</p>

<pre class=""lang-rb prettyprint-override""><code>def function_I_want_to_test(thing)
  if thing &gt; 0
    function_a(thing)
  else
    function_b(thing)
  end
end
</code></pre>

<p><code>function_a</code> and <code>function_b</code> already have spec tests, so I don't really care what the return values are, but both <code>function_a</code> and <code>function_b</code> make API calls which I feel would make the rspec test a lot more complicated for testing only the logic contained within <code>function_I_want_to_test</code>.</p>

<p>I've gone through this page (<a href=""https://blog.codeship.com/unit-testing-in-ruby/"" rel=""nofollow noreferrer"">https://blog.codeship.com/unit-testing-in-ruby/</a>) reviewing the unit testing approach, and the explanations make sense, but when attempting to use <code>allow</code> and <code>receive</code>, it appears that the function is still wanting to be called so I'm assuming I'm not utilizing the functions correctly. </p>

<p>Essentially I want to treat my code as such, and have it return something arbitrary so it doesn't even call the function. </p>

<pre class=""lang-rb prettyprint-override""><code>def function_I_want_to_test(thing)
  if thing &gt; 0
    pp ""a""
  else
    pp ""b""
  end
end
</code></pre>

<p>From my research, it appears the allow/expect is the way to go, but I'm assuming I'm not fully understanding the concept. </p>

<p>I guess the main question I have is, how does my rspec test know to ""override"" the functions (<code>function_a</code> and <code>function_b</code>) when testing <code>function_I_want_to_test</code>?</p>

<p>I know there are a few similar asked questions, but they didn't seem to answer how I was anticipating.</p>
",https://stackoverflow.com/questions/56492493/how-do-i-test-a-functions-logic-but-ignore-the-method-calls,['ruby'],117,False,1,0
"Unable to update data by Eloquent in Laravel, phpunit","<p>I am developing an application using Laravel, Eloquent as ORM, phpunit for unit testing. But i am not able to update data in database. Though there is no exception, warning or error. If the object of the model class checked in laravel, before update and after update, it is showing that data has been changed in the model class but when checking the database, found that data is not being changed. </p>

<p><strong>Model Class</strong></p>

<pre><code>class Post extends Model
{
    protected $table = ""posts"";

    protected $fillable = [
        'id',
        'user_id',
        'title',
        'description',
        'total_needed',
        'total_collected',
        'total_expanse',
        'start_date',
        'end_date',
        'active',
        'updated_at',
        'created_at',
    ];
}//class
</code></pre>

<p><strong>Repository Code</strong></p>

<pre><code>class Post_Repo_Impl implements Post_Repo_I
{
    public function update(Post $postUpdate)
    {
        $raedOld = false;
        $updateStatus = false;
        try {
            $psot_id = $postUpdate-&gt;id;
            $postOrgin = Post::find($psot_id);
            $raedOld = true;
        } catch (Exception $e) {
            error_log(""Post Update : failed to read existig post."");
        }
        if ($raedOld) {
            try {
                 //line 1
                echo ""\n"" . $postOrgin-&gt;title . ""\n"";
                $this-&gt;setPostValues($postOrgin, $postUpdate)-&gt;update();
                 //line 2
                echo ""\n"" . $postOrgin-&gt;title . ""\n"";
                $updateStatus = true;
            } catch (Exception $e) {
                error_log(""Post Update : Failed to save updated post."" . ""\n\n"" . $e);
            }
        }
        return  $updateStatus;
    } //update
}
</code></pre>

<p>Line 1 and Line 2, not printing same value. Line 2 printing the changed value. </p>

<p><strong>Unit Test code</strong></p>

<pre><code>class RepoPost extends TestCase
{
    public function testMain()
    {
        echo ""\n &gt;----------- Test Main : ---------&gt; \n"";
        $this-&gt;postUpdate();
    } //mother test

    public function postUpdate()
    {
        $postDummyUpdate = new Post();
        $postDummyUpdate-&gt;id = '2';
        $postDummyUpdate-&gt;user_id = 'Tst';
        $postDummyUpdate-&gt;title = 'Post Updated Repo Test........';
        $postDummyUpdate-&gt;description = 'UnitTesting of URLs';
        $postDummyUpdate-&gt;total_needed = '2000';
        $postDummyUpdate-&gt;total_collected = '1000';
        $postDummyUpdate-&gt;total_expanse = '500';
        $postDummyUpdate-&gt;start_date = '22-09-2019';
        $postDummyUpdate-&gt;end_date = '22-10-2019';
        $postDummyUpdate-&gt;active = '1';
        $postDummyUpdate-&gt;updated_at = '2019-09-24';
        $postDummyUpdate-&gt;created_at = '2019-09-22';

        echo '\n----PostUpdate----\n';
        $postRepoSave = $this-&gt;getRepoPostImpl();
        dd($postRepoSave-&gt;update($postDummyUpdate));
        if ($postRepoSave == false) {
            error_log(""\n\nTest : Data Save Failed."");
        } else {
            error_log(""Saved Post ID : "" . $postRepoSave);
        }
    }

    public function getRepoPostImpl()
    {
        return new Post_Repo_Impl();
    }
}
</code></pre>

<p>In the test code it is returning true.</p>
",https://stackoverflow.com/questions/58068431/unable-to-update-data-by-eloquent-in-laravel-phpunit,"['php', 'laravel', 'eloquent']",82,False,0,0
Why does my async unit test throw an InvalidOperationException while the same sync test doesn&#39;t?,"<p>I'm unit testing a part of my WPF project that uses <code>async</code> code and <code>Application.Current.MainWindow</code> to set the title of the main window.</p>

<pre><code>public class ClassUnderTest
{
    // Get and apply title async
    public async Task GetAndApplyWindowTitleFromDbAsync()
    {
        string windowTitle = await GetWindowTitleFromDbAsync();
        Application.Current.MainWindow.Title = windowTitle;
    }

    public async Task&lt;string&gt; GetWindowTitleFromDbAsync()
    {
        await Task.Delay(2000);
        return ""Async Window Title"";
    }

    // Get and apply title sync
    public void GetAndApplyWindowTitleFromDb()
    {
        Application.Current.MainWindow.Title = ""Sync Window Title"";
    }
}
</code></pre>

<p>The unit test with the synchronous method succeeds while the async method throws the following exception when accessing <code>Application.Current.MainWindow</code> after the <code>await</code>:</p>

<blockquote>
  <p>System.InvalidOperationException: The calling thread cannot access
  this object because a different thread owns it.</p>
</blockquote>

<pre><code>[TestClass]
public class TestClass
{

    [TestMethod]
    public void SyncMethodWithUICodeTest()
    {
        InitializeApplication();

        Assert.AreEqual(""Window Title"", Application.Current.MainWindow.Title);

        var classUnderTest = new ClassUnderTest();

        classUnderTest.GetAndApplyWindowTitleFromDb();

        // Test succeeds
        Assert.AreEqual(""Sync Window Title"", Application.Current.MainWindow.Title);
    }

    [TestMethod]
    public async Task AsyncMethodWithUICodeTest()
    {
        InitializeApplication();

        Assert.AreEqual(""Window Title"", Application.Current.MainWindow.Title);

        var classUnderTest = new ClassUnderTest();

        await classUnderTest.GetAndApplyWindowTitleFromDbAsync();

        // throws InvalidOperationException
        Assert.AreEqual(""Async Window Title"", Application.Current.MainWindow.Title);
    }

    private void InitializeApplication()
    {
        if (Application.Current == null)
        {
            var app = new Application();
            var window = new Window();
            app.MainWindow = window;
        }

        Application.Current.MainWindow.Title = ""Window Title"";
    }
}
</code></pre>

<p>I was under the impression that the statement after <code>await</code> returns to the ""original"" context (where <code>Application.Current.MainWindow</code> was known).</p>

<p>Why does the <code>async</code> unit test throw an exception?
Is the reason unit test specific or can the same exception be thrown in my WPF application too?</p>
",https://stackoverflow.com/questions/59394674/why-does-my-async-unit-test-throw-an-invalidoperationexception-while-the-same-sy,"['c#', 'wpf', 'unit-testing', 'async-await']",445,True,-1,1
Integration test in Spring application using Flowable,"<p>I need to write some integration tests for my Spring application using Flowable. My tests must include the application BPMN workflow logic.</p>

<p>My question is - should I start and deploy normal Flowable engine during my tests as I do in the application? In <a href=""https://www.flowable.org/docs/userguide/index.html#springUnitTest"" rel=""nofollow noreferrer"">official documentation</a> I see some Flowable classes prepared for unit testing but nothing for integration. </p>

<p>Won't starting real Flowable engine cause performance issues during running IT? I'm afraid that they will take long time if I will need to run this with every test separately. How do you deal with this in your applications?</p>
",https://stackoverflow.com/questions/55647265/integration-test-in-spring-application-using-flowable,"['java', 'spring', 'activiti', 'flowable']",1047,True,0,1
Is it a good practice to assign atributes to the tester class that will be used by other tests,"<p>I'm writing unit tests for my python app with pytest.</p>

<p>The module I'm testing has many methods that will be called in sequence and their returns are to be used as arguments to the other ones. In short what I have is something like this:</p>

<pre><code>def foo_1():
    #load file and do stuff
    return bar_1

def foo_2(arg1):
    #do stuff with arg1
    return bar_2

def foo_3(arg1, arg2):
    #do stuff with arg1 and arg2
    return bar_3

x = foo_1()
y = foo_2(x)
z = foo_3(x,y)
</code></pre>

<p>Pretty basic stuff, and this are the tests I'm running:</p>

<pre><code>import foo_app

class TestClass:

    def test_foo_1(self):
        self.x = foo_app.foo_1()

        #never mind the assertions
        assert 0 == self.x

    def test_foo_2(self):
        self.y = foo_app.foo_2(self.x)

        #never mind the assertions
        assert 1 == self.y

    def test_foo_3(self):
        self.z = foo_app.foo_3(self.x, self.y)

        #never mind the assertions
        assert 3 == self.z
</code></pre>

<p>However, I'd like to know if this is a good practice on unit testing, and if not what is the best way to deal with this kind of scenario where I depend on the executions of previous methods to achieve my result?</p>
",https://stackoverflow.com/questions/54155709/is-it-a-good-practice-to-assign-atributes-to-the-tester-class-that-will-be-used,"['python', 'unit-testing', 'testing', 'pytest']",37,False,-1,1
"Unit testing with Jest, expect problem receiving empty/undefined object","<p>i am new to unit testing and i am trying to test the length of a navigation bar, below you can see the nav bar component which is within a class</p>

<pre><code>&lt;AppBar className={classes.appBar} position=""static""&gt;
        &lt;Toolbar className={classes.toolbar}&gt;
            {authenticated &amp;&amp; this.state.layoutMode ==='desktop' ? (
                &lt;Grid container
                    direction =""row""
                    justify=""flex-end""
                    alignItems=""center""&gt;
                    &lt;div className={classes.root}&gt;
                        &lt;Tabs id=""Tab"" className = {classes.tabBar} value={value} onChange={this.handleChange}&gt;
                            &lt;Tab label=""example"" alt=""example"" onClick={() =&gt; Router.push('/example')}/&gt;
                            &lt;Tab label=""example"" alt=""example"" onClick={() =&gt; Router.push('/example')}/&gt;
                            &lt;Tab label=""example"" alt=""example"" onClick={() =&gt; Router.push('/example')}/&gt;
                            &lt;Tab label=""example"" alt=""example"" onClick={() =&gt; Router.push('/example')}/&gt;
                            &lt;Tab label=""example"" alt=""example"" onClick={() =&gt; Router.push('/example')}/&gt;
                            &lt;Tab label=""example"" alt=""example"" onClick={() =&gt; Router.push('/example')}/&gt;
                        &lt;/Tabs&gt;
                    &lt;/div&gt;
                &lt;/Grid&gt;
            ) : (
                authenticated &amp;&amp; &lt;BurgerMenu/&gt;
            )}
</code></pre>

<p>Below is the test i have written so far</p>

<pre><code>describe('NavBar', () =&gt; {
const intialState = {
    ui: { width: 1361 },
    auth: { authenticated: true }
}

let container;
beforeEach(() =&gt; {
    container = shallow(&lt;Nav /&gt;);
});

it('should render self and subcomponents', () =&gt; {
    expect(container).toMatchSnapshot();
});

it('should contain an AppBar', () =&gt; {
    console.log(container.find(AppBar));
    expect(container.find(AppBar)).toHaveLength(1);
});
</code></pre>

<p>})</p>

<p>however my problem is that the .find(AppBar) doesnt seem to be found, when using a console log(container.find(AppBar)) it shows the following ""ShallowWrapper {}"" this would mean that the object is empty and therefore not equal to 1, however i do not know where to point the find to correctly find the tabs to test</p>
",https://stackoverflow.com/questions/55007479/unit-testing-with-jest-expect-problem-receiving-empty-undefined-object,"['reactjs', 'unit-testing', 'testing', 'jestjs', 'sinon']",1856,False,0,1
Laravel Virgin: Disable/mock database connection when testing model mutators that utilize relationships,"<p>I have the following models:</p>

<ul>
<li><code>Grid.php</code></li>
</ul>

<pre><code>namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\Rover;

class Grid extends Model
{
    /**
     * Table Name
     */
    protected $table='grid';

    public function rovers()
    {
        return $this-&gt;hasMany(Rover::class);
    }
}
</code></pre>

<ul>
<li><code>Rover.php</code></li>
</ul>

<pre><code>namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\Grid;

class Rover extends Model
{

    /**
     * Table Name
     */
    protected $table='rover';

    public function grid()
    {
        return $this-&gt;belongsTo(Grid::class);
    }

    public function setGridPosXValue($value)
    {
        $Grid = $this-&gt;grid()-&gt;first();
        $width = $Grid-&gt;width;
        if($value &lt; 0 || $value &gt; $width){
            throw new \InvalidArgumentException(""X is out of grid bounds"");
        }

        $this-&gt;attributes['x']=$value;
    }

    public function setGridPosYValue($value)
    {
        $Grid = $this-&gt;grid()-&gt;first();
        $height = $Grid-&gt;height;

        if($value &lt; 0 || $value &gt; $height){
            throw new \InvalidArgumentException(""Y is out of grid bounds"");
        }

        $this-&gt;attributes['y']=$value;
    }
}

</code></pre>

<p>And I want to test the Rover's mutator with theese tests:</p>

<pre><code>namespace Tests\Unit;

use Tests\TestCase;
use App\Model\Rover;
use App\Model\Grid;
use Mockery;

define(""TEST_ROVEL_SUCCESS_VAL"",3);
define(""TEST_ROVEL_NEGATIVE_VAL"",-1);


class RoverModelTest extends TestCase
{
    public function testSetGridPosXValueThrowsExceptionWhenNegative(){
        $this-&gt;markTestSkipped('To be implemented');
    }

    public function testSetGridPosXValueThrowsExceptionWhenOverWidth(){
        $rover = new Rover();
        $grid = new Grid();
        $grid-&gt;width=5;
        $grid-&gt;height=5;
        $rover-&gt;grid=$grid;

        $this-&gt;expectException(\InvalidArgumentException::class);
        $rover-&gt;setGridPosXValue(TEST_ROVEL_NEGATIVE_VAL);

    }

    public function testSetGridPosXValueThorwsExceptionOnNormal(){
        $rover = new Rover();
        $grid = new Grid();

        $grid-&gt;width=5;
        $grid-&gt;height=5;

        $rover-&gt;grid=$grid;
        try {
            $rover-&gt;setGridPosXValue(TEST_ROVEL_SUCCESS_VAL);
            $this-&gt;assertEquals($rover-&gt;x,TEST_ROVEL_SUCCESS_VAL);
        } catch(\Exception $e) {
            $this-&gt;fail(""No exception should be thrown when setting a correct value."");
        }
    }
}
</code></pre>

<p>So when I run the tests I get the following error:</p>

<pre><code>PHPUnit 7.5.13 by Sebastian Bergmann and contributors.

SFF                                                                 3 / 3 (100%)

Time: 125 ms, Memory: 18.00 MB

There were 2 failures:

1) Tests\Unit\RoverModelTest::testSetGridPosXValueThrowsExceptionWhenOverWidth
Failed asserting that exception of type ""Illuminate\Database\QueryException"" matches expected exception ""InvalidArgumentException"". Message was: ""SQLSTATE[08006] [7] FATAL:  password authentication failed for user ""laravel"" (SQL: select * from ""grid"" where ""grid"".""id"" is null limit 1)"" at
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:46
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/PostgresConnector.php:33
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectionFactory.php:182
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:918
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:943
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:399
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:325
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:657
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:624
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:333
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2124
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2112
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2598
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2113
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:521
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:505
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php:77
/var/www/html/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:23
/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php:386
/var/www/html/app/Model/Rover.php:23
/var/www/html/tests/Unit/RoverModelTest.php:28
.

2) Tests\Unit\RoverModelTest::testSetGridPosXValueThorwsExceptionOnNormal
No exception should be thrown when setting a correct value.

/var/www/html/tests/Unit/RoverModelTest.php:44

FAILURES!
Tests: 3, Assertions: 2, Failures: 2, Skipped: 1.

</code></pre>

<p>Meaning that the tests hit a misconfigured database connection.</p>

<p>So how I can set a ""fake"" database connection in order not to use any database at all when testing? The reason why is because I want to do a unit testing instead of an integration testing.</p>

<p>In my case I want the code not to hit the db connection and test the logic that the mutator has without writing into the database at all.</p>
",https://stackoverflow.com/questions/56734032/laravel-virgin-disable-mock-database-connection-when-testing-model-mutators-tha,"['php', 'laravel', 'unit-testing', 'phpunit']",650,True,0,1
StepBuilder.chunk() returning null with mockito,"<p>I have a Spring batch configuration class MyConfig with my reader, writer, step and Job beans. Below is my Step bean.</p>

<pre><code>@Bean
public Step myStep() {
    return stepBuilderFactory.get(STEP_NAME).&lt;MyType, MyType&gt;chunk(getMinimumChunkSize())
            .reader(myReader)
            .writer(myWriter)
            .build();

}
</code></pre>

<p>When I try unit testing it with the below class</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(classes = {MyConfig.class})
@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class,
                StepScopeTestExecutionListener.class })
public class MyConfigTest {

    @Mock
    private StepBuilderFactory stepBuilderFactory;

    @Mock
    private StepBuilder stepBuilder;

    @Mock
    private SimpleStepBuilder simpleStepBuilder;

    @Mock
    FlatFileItemWriter myWriter;

    @Mock
    JdbcCursorItemReader myReader;

    @InjectMocks
    private MyConfig myConfig;

    @Before
    public void setUp() {
        when(stepBuilderFactory.get(anyString())).thenReturn(stepBuilder);
        when(stepBuilder.chunk(any())).thenReturn(simpleStepBuilder);
        when(simpleStepBuilder.reader(myReader)).thenReturn(simpleStepBuilder);
        when(simpleStepBuilder.writer(myWriter)).thenReturn(simpleStepBuilder);
    }

    @Test
    public void testChecklistStep() {
        final Step step = myConfig.checklistStep();
        assertNotNull(step);
    }      
}
</code></pre>

<p>On debug I get <code>stepBuilderFactory.get(STEP_NAME)</code> gives the mock as expected shown below</p>

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

<p>but the <code>stepBuilderFactory.get(STEP_NAME).&lt;MyType, MyType&gt;chunk(getMinimumChunkSize())</code> is returning null instead of SimpleStepBuilder mock. This looks pretty straight forward, I am new to mockito and spring batch. Why is the thenReturn not working in this case?</p>

<p>I tried reading <a href=""https://docs.spring.io/spring-batch/4.0.x/reference/html/testing.html"" rel=""nofollow noreferrer"">official documentation</a> but this was of less help to what i am trying to do. Please suggest if my approach is wrong or if I'm missing anything?</p>
",https://stackoverflow.com/questions/58372774/stepbuilder-chunk-returning-null-with-mockito,"['java', 'junit', 'mockito', 'spring-batch']",1157,True,0,1
QuarkusTest: Inject the correct instance,"<p>I am using Quarkus for a little project and I got stuck in unit testing my classes using the tools that Quarkus offers.</p>

<p>The problem is, I used the following approach to mock som classes:
<a href=""https://quarkus.io/guides/getting-started-testing#mock-support"" rel=""nofollow noreferrer"">https://quarkus.io/guides/getting-started-testing#mock-support</a></p>

<p>Mocking my Dao or Service class would be a nice way in my opinion.
However Mocking my classes leads to the effect that when I inject my Service/Dao class that has to be tested, the container for sure injects the Mock implementation.</p>

<p>Is there a way to prevent that and use the real implementation class?</p>

<pre class=""lang-java prettyprint-override""><code>@ApplicationScoped
public class ExpenseDaoImpl implements ExpenseDao {

}

@Mock
@ApplicationScoped
public class ExpenseDaoMock implements ExpenseDao {

}

@QuarkusTest
class ExpenseDaoTest {

    @Inject
    private ExpenseDao expenseDao;  //injects the mocked implementation

}
</code></pre>
",https://stackoverflow.com/questions/57761735/quarkustest-inject-the-correct-instance,"['java', 'junit', 'quarkus']",486,False,0,0
Oracle to Postgres Conversion trouble shooting,"<p>Converted a Standalone Procedure from Oracle to Postgres but not sure why there is an run error even the code is successfully compiled</p>

<p>Converted the below code from Oracle to Postgres</p>

<pre><code>CREATE OR REPLACE FUNCTION ssp2_pcat.pop_hoa_contracts_for_prod(
)
RETURNS void
LANGUAGE 'plpgsql'

COST 100
VOLATILE 
AS $BODY$

DECLARE 
C1 CURSOR for
SELECT MARKET_CODE, CONTRACT_COMBO_ID, COUNT(*) FROM 
ssp2_pcat.VPF_HOA_CONTRACTS_FOR_PROD A
WHERE start_Date IN
  (SELECT MAX(start_date)
  FROM VPF_HOA_CONTRACTS_FOR_PROD b
  WHERE A.MARKET_CODE     = b.MARKET_CODE
  AND A.CONTRACT_COMBO_ID = b.CONTRACT_COMBO_ID
  AND A.CONTRACT_ID       = B.CONTRACT_ID
  AND b.start_date       &lt;= current_date
  AND b.end_date          &gt; current_date )
  GROUP BY MARKET_CODE, CONTRACT_COMBO_ID 
  ORDER BY MARKET_CODE, CONTRACT_COMBO_ID; 

C2 CURSOR(iMktCode VARCHAR, iCombo integer) for
SELECT MARKET_CODE, CONTRACT_COMBO_ID, CONTRACT_ID 
FROM ssp2_pcat.VPF_HOA_CONTRACTS_FOR_PROD A
WHERE start_Date IN
  (SELECT MAX(start_date)
  FROM ssp2_pcat.VPF_HOA_CONTRACTS_FOR_PROD b
  WHERE A.MARKET_CODE     = b.MARKET_CODE
  AND A.CONTRACT_COMBO_ID = b.CONTRACT_COMBO_ID
  AND A.CONTRACT_ID       = B.CONTRACT_ID
  AND b.start_date       &lt;= current_date
  AND b.end_date          &gt; current_date  )
  AND MARKET_CODE       = iMktCode
  AND CONTRACT_COMBO_ID = iCombo
  ORDER BY MARKET_CODE, CONTRACT_COMBO_ID, START_DATE;
Contracts     VARCHAR(32000);
Contract_Val1 VARCHAR(4000) := NULL;
Contract_Val2 VARCHAR(4000) := NULL;
Contract_Val3 VARCHAR(4000) := NULL;
Contract_Val4 VARCHAR(4000) := NULL;
Contract_Val5 VARCHAR(4000) := NULL;
Contract_Val6 VARCHAR(4000) := NULL;
Contract_Val7 VARCHAR(4000) := NULL;
Contract_Val8 VARCHAR(4000) := NULL;
Num           INTEGER;
Cont_Num      INTEGER;
l_start TIMESTAMP :=  clock_timestamp();
l_end TIMESTAMP :=  clock_timestamp();
Time_Taken    VARCHAR(20);
                    i record;
                    j record;

BEGIN
l_start  :=  clock_timestamp();
DELETE FROM ssp2_pcat.HOA_CONTRACTS_KH; 
 FOR i IN C1 LOOP 
 BEGIN
 Num       := 0;
  Contracts := NULL;
  Cont_Num  := 1;        
 FOR j IN C2 (i.MARKET_CODE, i.CONTRACT_COMBO_ID) LOOP 
    Num         := Num + 1;
    IF Num       = 1 THEN
      Contracts := '|' || j.CONTRACT_ID || '|';
    ELSE
      IF LENGTH(Contracts || j.CONTRACT_ID || '|') &gt; 4000 THEN
 PERFORM ssp2_pcat.Assign (Cont_Num, SUBSTRING(Contracts, 1, 
 LENGTH(Contracts)-1));
        Num       := 1;
        Contracts := '|' || j.CONTRACT_ID || '|';
        Cont_Num  := Cont_Num + 1;
      ELSE
        Contracts := Contracts || j.CONTRACT_ID || '|';
      END IF;
    END IF;
  END LOOP;                        
  PERFORM ssp2_pcat.Assign (Cont_Num, Contracts);
  IF Cont_Num &gt; 5 THEN
    raise notice'%', ('MARKET_CODE: ' || i.MARKET_CODE || ', CONTRACT_COMBO_ID: ' || i.CONTRACT_COMBO_ID || ' has more than 32K in size. These Contracts are left out: ' || Contracts);
  END IF;
  INSERT INTO HOA_CONTRACTS_KH
    (
      MARKET_CODE,
      CONTRACT_COMBO_ID,
      CONTRACT_ID,
      CONTRACT_ID2,
      CONTRACT_ID3,
      CONTRACT_ID4,
      CONTRACT_ID5,
      LAST_UPDATED
    )
    VALUES
    (
      i.MARKET_CODE,
      i.CONTRACT_COMBO_ID,
      Contract_Val1,
      Contract_Val2,
      Contract_Val3,
      Contract_Val4,
      Contract_Val5,
      CURRENT_TIMESTAMP::TIMESTAMP(0)
    );
  Contract_Val1 := NULL;
  Contract_Val2 := NULL;
  Contract_Val3 := NULL;
  Contract_Val4 := NULL;
  Contract_Val5 := NULL;
  Contract_Val6 := NULL;
  Contract_Val7 := NULL;
  Contract_Val8 := NULL;

EXCEPTION
WHEN OTHERS THEN
  ROLLBACK;
  raise notice'%', ('1) POP_HOA_CONTRACTS_FOR_PROD: ' || SQLERRM);

END;
END LOOP;           
RAISE NOTICE 'Function excution time Took: %', l_start;
RAISE NOTICE 'Function excution time Took: %',l_end-l_start;
SELECT l_end-l_start INTO Time_Taken;
raise notice'%',('POP_HOA_CONTRACTS_FOR_PROD Took: ' || Time_Taken );
EXCEPTION
 WHEN OTHERS THEN
 raise notice'%', ('2) POP_HOA_CONTRACTS_FOR_PROD: ' || SQLERRM);

END;
$BODY$;
</code></pre>

<p>The code is compiled successfully, but giving a run time error as follows,</p>

<p>NOTICE:  2) POP_HOA_CONTRACTS_FOR_PROD: cannot begin/end transactions in PL/pgSQL</p>

<p>Debugged the whole code and looks like still I'm unable to identify the issue, can any one help me in making me understand more about Postgres as I'm new to this Database. Found out in unit testing that its not calling the assign function mentioned in the code, </p>
",https://stackoverflow.com/questions/54084522/oracle-to-postgres-conversion-trouble-shooting,"['plpgsql', 'postgresql-9.5']",62,False,0,0
How to unit test methods using Neo4JClient,"<p>I have been working on implementing a .NET Core API using Neo4J as the data storage and Neo4JClient (<a href=""https://github.com/Readify/Neo4jClient"" rel=""nofollow noreferrer"">https://github.com/Readify/Neo4jClient</a>) to build the data layer of the application. Things are going pretty well but I'm at a loss for strategies on how to test methods using the client in a way that adequately verifies that the code is doing what it's expected to do.</p>

<p>Example method using Neo4JClient:</p>

<pre><code>private readonly IGraphClient _graphClient;
protected IGraphClient GraphClient =&gt; _graphClient;

public BaseRepository(GraphClient client)
{
    _graphClient = client;
    _graphClient.Connect();
}

public async Task&lt;IList&lt;TModel&gt;&gt; GetAllAsync()
{
    var results = await GraphClient.Cypher.Match($""(e:{typeof(TModel).Name})"")
        .Return(e =&gt; e.As&lt;TModel&gt;())
        .ResultsAsync;
    return results.ToList();
}
</code></pre>

<p>Is there existing documentation for mocking and unit testing methods that operate on the <code>GraphClient</code> like this? I haven't been able to find anything in Google searches on the subject.</p>
",https://stackoverflow.com/questions/54935824/how-to-unit-test-methods-using-neo4jclient,"['c#', 'unit-testing', 'neo4j', '.net-core', 'neo4jclient']",647,True,0,1
How to let a unit test ignore a middleware in Laravel,"<p>I'm testing an endpoint in my Laravel app. However, I have a middleware that does complex logic to determine the location of the user (using ip reverse look up etc such as this code:</p>

<pre><code>public function getOpCityByIP()
{
    // Get the client's remote ip address
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) &amp;&amp; $_SERVER['HTTP_X_FORWARDED_FOR']) {
        $clientIpAddress = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    } else {
       $clientIpAddress = $_SERVER['REMOTE_ADDR'];
    }
    $opCityArray = OpCityIP::get($clientIpAddress);
    return $opCityArray;
}
</code></pre>

<p>I'm not interested in going inside the guts of such methods in said middleware and having to mock them etc. I'd rather simply skip the entire middleware during the unit testing, or at least mock its entire operations and instead hardcode the result to something predetermined. How do I do that?</p>

<p>I'm using Laravel 5.4</p>

<h1>update</h1>

<p>i need it to ignore a specific middleware, not all of them</p>
",https://stackoverflow.com/questions/57400086/how-to-let-a-unit-test-ignore-a-middleware-in-laravel,"['laravel', 'laravel-5', 'phpunit', 'mockery']",2679,True,0,3
Is it possible to write Jest unit tests for Node.js fs.readFile()?,"<p>I am new to Jest unit testing and was wondering if Jest can be used to test Node.js file system modules. </p>

<p>I currently have a text file that contains a short poem, and the viewText function console logs the poem on my terminal.</p>

<p>Using Jest, I my goal is to write a test that checks if <code>viewText</code> function is indeed working.</p>

<pre><code>const viewText = () =&gt; {
  fs.readFile('poem.txt', 'utf8', (err, data) =&gt; {
    if (err) throw err;
    console.log(data);
  });
};
</code></pre>

<p>With Jest, I have tried :</p>

<pre><code>jest.spyOn(global.console, 'log');

const mockPoem = 'Some say the world will end in fire, Some say in ice. From what I’ve tasted of desire I hold with those who favor fire ... And would suffice.';

describe('viewText', () =&gt; {
  const mockReadFile = jest.fn();
  mockReadFile.mockReturnValue(mockPoem);

  it('prints poem to console', () =&gt; {
    viewText();
    expect(global.console.log).toHaveBeenCalledWith(mockPoem);
  });
});
</code></pre>

<p>With the test, all I want to do check if my <code>viewText</code> function passes the test - be able to view the <code>mockPoem</code>. I'm really confused as to how I should approach writing unit tests for functions using the file system module.</p>
",https://stackoverflow.com/questions/58810079/is-it-possible-to-write-jest-unit-tests-for-node-js-fs-readfile,"['javascript', 'node.js', 'unit-testing', 'jestjs']",12039,True,5,1
"Mockito, TooManyActualInvocations when testing conditions Spek Framework","<p>For a scenario unit testing a user entering a password and password confirmation. when i try to verify the same method being called in a different <code>on()</code> block, i get the following error on the 2nd <code>on()</code>block. </p>

<pre><code>org.mockito.exceptions.verification.TooManyActualInvocations: 
activationPasswordView.disableButton();
Wanted 1 time:
But was twice
</code></pre>

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

<pre><code> given(""user set password ""){

        on(“password is null”){
         presenterImpl.validatePassword(null, null)

            it(""done button should be disabled""){
                verify(view).disableButton()
            }
        }

        on(""input only one password""){
          presenterImpl.validatePassword(""Password"", """")

            it(""done button should be disabled""){
                verify(view).disableButton()
            }
        }
    }
</code></pre>

<p>But if i call a different method, it works correctly. I assume this was not how Spek framework was intended to be used as all the examples i have seen always use an Assert. Is there a way i can write the following conditions in Spek without the error?. Even a different <code>given()</code> still causes the error. </p>
",https://stackoverflow.com/questions/56019643/mockito-toomanyactualinvocations-when-testing-conditions-spek-framework,"['unit-testing', 'kotlin', 'spek']",272,False,0,1
Unit testing with multi-step user inputs,"<p>I'm unit testing a part of code which asks for one argument at a time before bringing them back.
I'd like to write a test that the prompt is what it should be, but I'm unsure how to test each stage of the prompt.
Say the prompt is: 
""what is variable 1""
--user input--
""what is variable 2""
--user input--</p>

<p>Then the unit test would be something like..</p>

<pre><code>with self.subTest(args=args):
                    result = _run(args)
                    self.assertRegex(result.stdout,r'(?m)^'what is variable 1?""
</code></pre>

<p>But when I try to submit just one variable at a time to 'args' then the test hangs. But when I try to submit all variables at once, the code fails and says <code>""'what is variable 1' not found in ''""</code></p>
",https://stackoverflow.com/questions/57446100/unit-testing-with-multi-step-user-inputs,"['python', 'unit-testing']",54,True,-1,1
Separate package.json for angular e2e tests?,"<p>I am using Angular 8 in my project. Is it possible to have a separate <code>package.json</code> file for e2e tests? I am using <code>jest</code> for unit testing and <code>protractor+jasmine</code> for e2e. Because of this, I can't completely remove <code>jasmine</code> from my <code>package.json</code>. And, therefore, I often have problems with typings</p>

<p>What I want to get:</p>

<ol>
<li><p>when i am in the <code>.spec</code> file that is inside main project
<code>expect(someFuncCall()).toMatchSnapshot()</code> should works correct and <code>jasmine</code> should not work</p></li>
<li><p>when i am in the <code>.spec</code> file that is inside e2e folder
<code>toMatchSnapshot()</code> should give an error and <code>jest</code> should not work</p></li>
</ol>

<p>Of course, all IDE intellisense for tests should differ depends on project type: e2e/main</p>
",https://stackoverflow.com/questions/59076703/separate-package-json-for-angular-e2e-tests,"['angular', 'jasmine', 'jestjs', 'e2e-testing', 'angular-e2e']",862,True,0,1
JMockit - Mock REST client object,"<p>I am using JMockit to do the unit testing. For one test cases, I want to create the mock of the third party REST client. The client object is of Apache Solr exposed REST service. When I record the test case using Expectations, this object does not get initialized and the test case fails due to NullPointerException.</p>

<p>The REST client is supposed to be created like this:</p>

<pre><code>HttpSolrClient.Builder(solrUrl).withConnectionTimeout(10000).withSocketTimeout(60000).build()
</code></pre>

<p>To mock the client I did like this:</p>

<pre><code>@Mocked SolrClient solrClient
</code></pre>

<p>I could not find, how can I create the mock object. What will be the correct way to create the client object?</p>
",https://stackoverflow.com/questions/55528245/jmockit-mock-rest-client-object,['jmockit'],166,False,0,0
xUnit Abstract Test Class with virtual test methods with parameters,"<p>I just started with Unit Testing and I'm using xUnit framework. I have an AbstractTest class that defines some abstract test methods which I'll use in every test class. <strong>The problem is in the static field - InsertData</strong>. MemberData in this case InsertData must be static. I can't assign some value to InsertData in the inherited class (TestClass) because I got the error before debugger touch both constructors.</p>

<pre><code>public abstract class AbstractTest&lt;TModel&gt; where TModel : class
{
   public IRepository&lt;TModel&gt; repo;
   public static IEnumerable&lt;object[]&gt; InsertData;

   [Theory]
   [MemberData(nameof(InsertData))]
   public virtual void AbsTestInsert(TModel model)
   {
       try
       {
           repo.AddUpdate(model);
           Assert.True(true);
       }
       catch (Exception ex)
       {
           Assert.True(false, ex.Message);
       }
   }
}

public class TestClass : AbstractTest&lt;TestModel&gt;
{
    public TestClass()
    {
        repo = TestRepository();
    }
}
</code></pre>

<p>Because I inherit the AbstractTest class I'll have the test.
<a href=""https://i.stack.imgur.com/ylOYq.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/ylOYq.png"" alt=""Test class""></a></p>

<p>I can't find a solution to InsertData remain static but to override its value in the inherited class.</p>

<p>I have idea with something like this: </p>

<pre><code>public static IEnumerable&lt;object[]&gt; InsertData() =&gt; Data;
public abstract/virtual IEnumerable&lt;object[]&gt; Data()
{
    return ...;
}
</code></pre>

<p>But to do this Data also must me static...</p>
",https://stackoverflow.com/questions/55004351/xunit-abstract-test-class-with-virtual-test-methods-with-parameters,"['c#', 'unit-testing', 'asp.net-core', 'xunit']",2214,True,5,1
Unable to assert constraints related to the screen bounds,"<p>Im trying to do unit testing on my UI elements in a Swift application.</p>

<p>Here is the code I have defining the constraints :</p>

<pre><code>container.topAnchor.constraint(equalTo: contentView.topAnchor, constant:7).isActive = true
container.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant:34).isActive = true
container.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant:-34).isActive = true
container.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant:-7).isActive = true
container.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height * 0.062).isActive = true
</code></pre>

<p>And here my attempt to assert the geometry of the view : </p>

<pre><code>XCTAssertTrue(subject.container.frame.origin.y - 7 == subject.contentView.frame.origin.y)
XCTAssertTrue(subject.container.frame.origin.x - 34  == subject.contentView.frame.origin.x)
XCTAssertTrue(subject.container.frame.origin.x + subject.container.frame.size.width + 34 == subject.contentView.frame.origin
            .x + subject.contentView.frame.size.width)
XCTAssertTrue(subject.container.frame.origin.y + subject.container.frame.size.height + 7 == subject.contentView.frame.origin
        .y + subject.contentView.frame.size.height)
XCTAssertTrue(subject.container.frame.size.height == floor(UIScreen.main.bounds.height * 0.062) )
</code></pre>

<p>All of them work fine except for the last one. The last one fails and If I print the corresponding values I get : </p>

<pre><code>print(""----&gt;"",subject.container.frame.size.height)
print(""----&gt;"",floor((UIScreen.main.bounds.height) * 0.062))
</code></pre>

<p>Result :</p>

<pre><code>----&gt; 30.0
----&gt; 55.0
</code></pre>

<p>I dont get why the values are different. This is a constant issue with all my views. I can assert all the constraints but as soon as I get the screen bounds into play then the values differ between the constraint and the assertion.</p>
",https://stackoverflow.com/questions/57418425/unable-to-assert-constraints-related-to-the-screen-bounds,"['swift', 'constraints']",228,True,0,1
RxJS testing: marble test confusing case,"<p>I'm adding unit testing to my angular/rxjs project, and I'm using the <code>marble test</code> solution. And since I'm using the newer version of rxjs, so I used the build-in ""TestScheduler"" module.  <br></p>

<p>I'm following this post: <a href=""https://brianflove.com/2018/06/28/ngrx-testing-effects/"" rel=""nofollow noreferrer"">https://brianflove.com/2018/06/28/ngrx-testing-effects/</a>, And it gave an example as following: </p>

<pre><code>export class UserEffects {
  @Effect()
  addUser: Observable&lt;Action&gt; = this.actions$
    .ofType&lt;AddUser&gt;(UserActionTypes.AddUser)
    .pipe(
      map(action =&gt; action.payload),
      exhaustMap(payload =&gt; this.userService.addUser(payload.user)),
      map(user =&gt; new AddUserSuccess({ user })),
      catchError(error =&gt; of(new AddUserFail({ error })))
    );

  constructor(private actions$: Actions, private userService: UserService) {}

}
</code></pre>

<p>and the unit test is below:</p>

<pre><code>describe('addUser', () =&gt; {
    it('should return an AddUserSuccess action, with the user, on success', () =&gt; {
    const user = generateUser();
    const action = new AddUser({ user });
    const outcome = new AddUserSuccess({ user });

    actions.stream = hot('-a', { a: action });
    const response = cold('-a|', { a: user });
    const expected = cold('--b', { b: outcome });
    userService.addUser = jest.fn(() =&gt; response);

    expect(effects.addUser).toBeObservable(expected);
  });
});
</code></pre>

<p>I  can understand the logic(marble string) here expect one confusing point: </p>

<pre><code>cold('--b', { b: outcome })
</code></pre>

<p>why not <code>--b|</code>? Since the response observable has a completion event <code>|</code> in  <code>cold('-a|', { a: user });</code>. </p>

<p>Btw, in this post, it will third-party library, but I use native <code>TestScheduler</code> and have the same result. </p>
",https://stackoverflow.com/questions/58388868/rxjs-testing-marble-test-confusing-case,"['rxjs', 'jasmine-marbles', 'rxjs-marbles']",422,True,0,1
Is there anyway to test Postgres with WPF by using Moq?,"<p>I have try to take a look from <a href=""https://developerhandbook.com/unit-testing/writing-unit-tests-with-nunit-and-moq/"" rel=""nofollow noreferrer"">https://developerhandbook.com/unit-testing/writing-unit-tests-with-nunit-and-moq/</a> as an example, but i can't figure out how to do moq with WPF and Postgres for testing upload file function.</p>

<p>** What i want to do is - using uploading function in WPF without touching db to do Moq.**
Right now, i stuck on upload function in WPF class which contain upload method that come up with connection to db.</p>

<p>Here is Some Source Code</p>

<pre><code>public static async Task&lt;IDeviceFileViewModel&gt; WriteDeviceFilesAsync(IDeviceFileViewModel device)
    {            

        IDeviceFileViewModel deviceResult = device;

        //check file storage path
        var filestoragepath = FileSystemEngine.CheckFileSystemStoragePath(device);

        //delete log file
        //Trace.WriteLine(device.DeviceId);
        DeleteLog(""Logs"", device);

        foreach (var deviceFile in device.DeviceFileStatisticsModel.DeviceFiles)
        {

            //Start modified by Prin Sooksong 08/13/2017
            //check corrupted file
            MediaFile fileStats = new MediaFile(deviceFile);

            var deviceFileExt = Path.GetExtension(deviceFile);
            if (deviceFileExt.Equals("".WAV"") || deviceFileExt.Equals("".wav""))
            {
                var audioStat = fileStats.Audio.FirstOrDefault();

                if (audioStat != null)
                {
                    device.DeviceFileStatisticsModel.DeviceFile = new FileInfo(deviceFile);
                    var tuple = await Task.Run(() =&gt; WriteDeviceAudioFileAsync(device, filestoragepath));

                    deviceResult.DeviceFileStatisticsModel.DeviceFileToCheckSums.Add(tuple.Item1, tuple.Item2);
                }
                else
                {
                    //write log file
                    //var taskWriteLog = Task.Run(() =&gt; WriteLog(""Logs"", device, device.DeviceFileStatisticsModel.DeviceFile.Name + ""\tSkipped! Corrupt File""));
                    WriteLog(""Logs"", device, device.DeviceFileStatisticsModel.DeviceFile.Name + ""\tSkipped! Corrupt File"");
                }
            }
            if (deviceFileExt.Equals("".MOV"") || deviceFileExt.Equals("".mov"") || deviceFileExt.Equals("".MP4"") || deviceFileExt.Equals("".mp4""))
            {
                var videoStat = fileStats.Video.FirstOrDefault();

                if (videoStat != null)
                {

                    device.DeviceFileStatisticsModel.DeviceFile = new FileInfo(deviceFile);
                    var tuple = await Task.Run(() =&gt; WriteDeviceVideoFileAsync(device, filestoragepath));

                    deviceResult.DeviceFileStatisticsModel.DeviceFileToCheckSums.Add(tuple.Item1, tuple.Item2);
                }
                else
                {
                    //write log file
                    //var taskWriteLog = Task.Run(() =&gt; WriteLog(""Logs"", device, device.DeviceFileStatisticsModel.DeviceFile.Name + ""\tSkipped! Corrupt File""));
                    WriteLog(""Logs"", device, device.DeviceFileStatisticsModel.DeviceFile.Name + ""\tSkipped! Corrupt File"");
                }
            }
            if (deviceFileExt.Equals("".JPG"") || deviceFileExt.Equals("".jpg""))
            {
                var pictureStat = fileStats.Image.FirstOrDefault();

                if (pictureStat != null)
                {
                    device.DeviceFileStatisticsModel.DeviceFile = new FileInfo(deviceFile);
                    var tuple = await Task.Run(() =&gt; WriteDevicePictureFileAsync(device, filestoragepath));

                    deviceResult.DeviceFileStatisticsModel.DeviceFileToCheckSums.Add(tuple.Item1, tuple.Item2);
                }
                else
                {

                    //write log file
                    //var taskWriteLog = Task.Run(() =&gt; WriteLog(""Logs"", device, device.DeviceFileStatisticsModel.DeviceFile.Name + ""\tSkipped! Corrupt File""));
                    WriteLog(""Logs"", device, device.DeviceFileStatisticsModel.DeviceFile.Name + ""\tSkipped! Corrupt File"");
                }
            }
            //End modified by Prin Sooksong 08/13/2017



        }            

        deviceResult.DeviceActiveStatus = false;


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

<p>Another Method that is tricked when WPF can identify file extension </p>

<pre><code> internal static async Task&lt;Tuple&lt;string, byte[]&gt;&gt; WriteDeviceAudioFileAsync(IDeviceFileViewModel device, string FileStoragePath)
    {
        var config = configurationManager.GetConfiguration&lt;ExtractorConfiguration&gt;();


        NpgsqlConnection.MapEnumGlobally&lt;ActivityTypes.Action&gt;();
        using (NpgsqlConnection connection = new NpgsqlConnection(""Server="" + config.DatabaseSetting.Host + "";"" +
                                                                  ""Port="" + config.DatabaseSetting.Port + "";"" +
                                                                  ""Database="" + config.DatabaseSetting.Database + "";"" +
                                                                  ""User Id="" + config.DatabaseSetting.UserName + "";"" +
                                                                  ""Password="" + config.DatabaseSetting.Password + "";"")
        )
        {

            try
            {
                await connection.OpenAsync();
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.Message);
                throw e;
            }

            try
            {

                    //var fileOid = await WriteFileOid(connection, device, device.DeviceFileStatisticsModel.DeviceFile);
                    //convert .wav to .mp3 file
                    Tuple&lt;FileInfo, DirectoryInfo&gt; transcoded = StreamEngine.TranscodeDeviceAudioFile(device.DeviceFileStatisticsModel.DeviceFile);
                    device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded = transcoded.Item1;
                    device.DeviceFileStatisticsModel.DeviceAudioTranscodedDirectory = transcoded.Item2;


                    //write raw file to ubuntu file system
                    var filestoreRaw = FileStoragePath + @""\"" + device.DeviceFileStatisticsModel.DeviceFile.Name;
                    await WriteFile(device, device.DeviceFileStatisticsModel.DeviceFile, FileStoragePath);                       

                    //var transcodedAudioFileOid = await WriteFileOid(connection, device, device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded);

                    //write mp3 file to ubuntu file system
                    var filestoreMp3 = FileStoragePath + @""\"" + device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded.Name;
                    await WriteFileMP3(device, device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded, FileStoragePath);

                    var fileChecksum = SecurityEngine.WriteFileCheckSum(device,device.DeviceFileStatisticsModel.DeviceFile);

                    MediaFile fileStats = new MediaFile(device.DeviceFileStatisticsModel.DeviceFile.FullName);
                    //MediaFile fileStats = new MediaFile(device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded.FullName);
                    var audioStat = fileStats.Audio.FirstOrDefault();

                    //var audioSize = audioStat.Size;
                    var audioSize = fileStats.General.Size;

                var durationTime = audioStat.Duration;
                    TimeSpan t = TimeSpan.FromMilliseconds(durationTime);
                    TimeSpan fileDuration = new TimeSpan(t.Hours, t.Minutes, t.Seconds);

                    var fileCreated = device.DeviceFileStatisticsModel.DeviceFile.CreationTime;
                    var fileChanged = device.DeviceFileStatisticsModel.DeviceFile.LastWriteTime;

                    if (fileCreated.Kind == DateTimeKind.Local)
                    {
                        fileCreated = fileCreated.ToUniversalTime();
                    }
                    else if (fileCreated.Kind == DateTimeKind.Unspecified)
                    {
                        fileCreated = fileCreated.ToLocalTime().ToUniversalTime();
                    }

                    if (fileChanged.Kind == DateTimeKind.Local)
                    {
                        fileChanged = fileChanged.ToUniversalTime();
                    }
                    else if (fileChanged.Kind == DateTimeKind.Unspecified)
                    {
                        fileChanged = fileChanged.ToLocalTime().ToUniversalTime();
                    }

                    //Trace.WriteLine(fileCreated.Kind);
                    //Trace.WriteLine(fileChanged.Kind);

                    //var fileMimeType = System.Web.MimeMapping.GetMimeMapping(device.DeviceFileStatisticsModel.DeviceFile.FullName);
                    var fileMimeType = getFileMimeType(device.DeviceFileStatisticsModel.DeviceFile.FullName.ToUpper());

                    Guid deviceUserUuid = Guid.Parse(device.DeviceUserUuId.ToString());
                    Guid deviceIDUuid = Guid.Parse(device.DeviceIdUuid.ToString());
                    Guid id = Guid.Parse(Guid.NewGuid().ToString());

                    byte[] bytes = Encoding.Default.GetBytes(device.DeviceId);
                    var deviceId = Encoding.ASCII.GetString(bytes);

                    Guid activityId = Guid.Parse(Guid.NewGuid().ToString());

                    var fileTitle = getMediaTitle(device);

                    var metadatainfo = MetaDataEngine.getMetaDataInfo(device);


                //DoEvents();

                if (metadatainfo != null)
                {

                    var sqlInsertGrp = ""INSERT INTO "" +
                                                ""audios (id, created, duration, device_id, user_id, modified, checksum, file_path, file_extension, file_size,prev_file_path,mime_type,title, classification, description) "" +
                                                    "" VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12::mime,@p13,@p14::classification,@p15);"" +
                                       ""INSERT INTO "" +
                                                ""activity (id, user_id, entity_id, user_ip, action, entity_type) "" +
                                                    "" VALUES (@a1, @a2, @a3, @a4, @a5, @a6);"";

                    using (var sqlGrp = new NpgsqlCommand(sqlInsertGrp, connection))
                    {
                        //Audio part
                        sqlGrp.Parameters.AddWithValue(""@p1"", NpgsqlDbType.Uuid, id);
                        sqlGrp.Parameters.AddWithValue(""@p2"", NpgsqlDbType.Timestamp, fileCreated);
                        sqlGrp.Parameters.AddWithValue(""@p3"", NpgsqlDbType.Interval, fileDuration);
                        sqlGrp.Parameters.AddWithValue(""@p4"", NpgsqlDbType.Uuid, deviceIDUuid);
                        sqlGrp.Parameters.AddWithValue(""@p5"", NpgsqlDbType.Uuid, deviceUserUuid);
                        sqlGrp.Parameters.AddWithValue(""@p6"", NpgsqlDbType.Timestamp, fileChanged);
                        sqlGrp.Parameters.AddWithValue(""@p7"", NpgsqlDbType.Bytea, fileChecksum);
                        sqlGrp.Parameters.AddWithValue(""@p8"", NpgsqlDbType.Text, filestoreRaw);
                        sqlGrp.Parameters.AddWithValue(""@p9"", NpgsqlDbType.Text, ""WAV"");
                        sqlGrp.Parameters.AddWithValue(""@p10"", NpgsqlDbType.Text, audioSize);
                        sqlGrp.Parameters.AddWithValue(""@p11"", NpgsqlDbType.Text, filestoreMp3);
                        sqlGrp.Parameters.AddWithValue(""@p12"", NpgsqlDbType.Text, fileMimeType);

                        //audio file meta data                            
                        sqlGrp.Parameters.AddWithValue(""@p13"", NpgsqlDbType.Text, metadatainfo.Title);
                        sqlGrp.Parameters.AddWithValue(""@p14"", NpgsqlDbType.Text, metadatainfo.ClassificationData);
                        sqlGrp.Parameters.AddWithValue(""@p15"", NpgsqlDbType.Text, metadatainfo.Note);

                        //Activity part
                        sqlGrp.Parameters.AddWithValue(""@a1"", NpgsqlDbType.Uuid, activityId);
                        sqlGrp.Parameters.AddWithValue(""@a2"", NpgsqlDbType.Uuid, deviceUserUuid);
                        sqlGrp.Parameters.AddWithValue(""@a3"", NpgsqlDbType.Uuid, id);

                        //IPAddress ip = Dns.GetHostEntry(Dns.GetHostName())
                        //                                  .AddressList.(f =&gt; f.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);

                        IPAddress ip = GetIP();

                        var ipStr = Utf16ToUtf8(ip.ToString());
                        sqlGrp.Parameters.AddWithValue(""@a4"", NpgsqlDbType.Text, ipStr);
                        sqlGrp.Parameters.AddWithValue(""@a5"", NpgsqlDbType.Enum, ActivityTypes.Action.upload_audio);
                        //Start modified by Prin Sooksong 08/07/2017                    
                        sqlGrp.Parameters.AddWithValue(""@a6"", NpgsqlDbType.Text, ""audios"");
                        //End modified by Prin Sooksong 08/07/2017

                        sqlGrp.Prepare();
                        await sqlGrp.ExecuteNonQueryAsync();

                    }
                }
                else
                {

                    var sqlInsertGrp = ""INSERT INTO "" +
                                                ""audios (id, created, duration, device_id, user_id, modified, checksum, file_path, file_extension, file_size,prev_file_path,mime_type,title) "" +
                                                    "" VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12::mime,@p13);"" +
                                       ""INSERT INTO "" +
                                                ""activity (id, user_id, entity_id, user_ip, action, entity_type) "" +
                                                    "" VALUES (@a1, @a2, @a3, @a4, @a5, @a6);"";

                    using (var sqlGrp = new NpgsqlCommand(sqlInsertGrp, connection))
                    {
                        //Audio part
                        sqlGrp.Parameters.AddWithValue(""@p1"", NpgsqlDbType.Uuid, id);
                        sqlGrp.Parameters.AddWithValue(""@p2"", NpgsqlDbType.Timestamp, fileCreated);
                        sqlGrp.Parameters.AddWithValue(""@p3"", NpgsqlDbType.Interval, fileDuration);
                        sqlGrp.Parameters.AddWithValue(""@p4"", NpgsqlDbType.Uuid, deviceIDUuid);
                        sqlGrp.Parameters.AddWithValue(""@p5"", NpgsqlDbType.Uuid, deviceUserUuid);
                        sqlGrp.Parameters.AddWithValue(""@p6"", NpgsqlDbType.Timestamp, fileChanged);
                        sqlGrp.Parameters.AddWithValue(""@p7"", NpgsqlDbType.Bytea, fileChecksum);
                        sqlGrp.Parameters.AddWithValue(""@p8"", NpgsqlDbType.Text, filestoreRaw);
                        sqlGrp.Parameters.AddWithValue(""@p9"", NpgsqlDbType.Text, ""WAV"");
                        sqlGrp.Parameters.AddWithValue(""@p10"", NpgsqlDbType.Text, audioSize);
                        sqlGrp.Parameters.AddWithValue(""@p11"", NpgsqlDbType.Text, filestoreMp3);
                        sqlGrp.Parameters.AddWithValue(""@p12"", NpgsqlDbType.Text, fileMimeType);
                        sqlGrp.Parameters.AddWithValue(""@p13"", NpgsqlDbType.Text, fileTitle);


                        //Activity part
                        sqlGrp.Parameters.AddWithValue(""@a1"", NpgsqlDbType.Uuid, activityId);
                        sqlGrp.Parameters.AddWithValue(""@a2"", NpgsqlDbType.Uuid, deviceUserUuid);
                        sqlGrp.Parameters.AddWithValue(""@a3"", NpgsqlDbType.Uuid, id);

                        //IPAddress ip = Dns.GetHostEntry(Dns.GetHostName())
                        //                                  .AddressList.(f =&gt; f.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);

                        IPAddress ip = GetIP();

                        var ipStr = Utf16ToUtf8(ip.ToString());
                        sqlGrp.Parameters.AddWithValue(""@a4"", NpgsqlDbType.Text, ipStr);
                        sqlGrp.Parameters.AddWithValue(""@a5"", NpgsqlDbType.Enum, ActivityTypes.Action.upload_audio);
                        //Start modified by Prin Sooksong 08/07/2017                    
                        sqlGrp.Parameters.AddWithValue(""@a6"", NpgsqlDbType.Text, ""audios"");
                        //End modified by Prin Sooksong 08/07/2017

                        sqlGrp.Prepare();
                        await sqlGrp.ExecuteNonQueryAsync();

                    }
                }

                //write file to ubuntu file system
                //var filestoreRaw = FileStoragePath + @""\"" + device.DeviceFileStatisticsModel.DeviceFile.Name;
                //await WriteFile(device, device.DeviceFileStatisticsModel.DeviceFile, FileStoragePath);
                //write file to ubuntu file system
                //var filestoreMp3 = FileStoragePath + @""\"" + device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded.Name;
                //await WriteFile(device, device.DeviceFileStatisticsModel.DeviceAudioFileTranscoded, FileStoragePath);

                //delete temp mp3 file
                await StreamEngine.DeleteMP3File(transcoded.Item1);

                    disconnected = false;
                //write log file
                //var taskWriteLog = Task.Run(() =&gt; WriteLog(""Logs"", device, device.DeviceFileStatisticsModel.DeviceFile.Name + ""\tUploaded successfully""));
                    WriteLog(""Logs"", device, device.DeviceFileStatisticsModel.DeviceFile.Name + ""\tUploaded successfully"");

                    var tupleChecksum = new Tuple&lt;string, byte[]&gt;(device.DeviceFileStatisticsModel.DeviceFile.FullName, fileChecksum);
                    return tupleChecksum;

            }
            catch (Exception e)
            {
                if (e.Message.Contains(""duplicate key value""))
                {
                    device.DuplicateFileErrorCount++;

                    disconnected = false;
                    //write log file
                    //var taskWriteLog = Task.Run(() =&gt; WriteLog(""Logs"", device, device.DeviceFileStatisticsModel.DeviceFile.Name + ""\tSkipped! File already exists""));
                    WriteLog(""Logs"", device, device.DeviceFileStatisticsModel.DeviceFile.Name + ""\tSkipped! File already exists"");

                    //delete duplicate file on samba server
                    FileSystemEngine.DeleteFile(device, FileStoragePath);

                    //Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =&gt;
                    //{
                    //    MessageBox.Show(Application.Current.MainWindow, ""Duplicate file '"" + device.DeviceFileStatisticsModel.DeviceFile.Name + ""' found in camera '"" + device.DeviceId + ""'.\r\nClick OK to continue."", """", MessageBoxButton.OK, MessageBoxImage.Warning);
                    //}));
                }
                else
                {
                    device.UnknownErrorCount++;

                    disconnected = true;

                    //write log file
                    //var taskWriteLog = Task.Run(() =&gt; WriteLog(""Logs"", device, device.DeviceFileStatisticsModel.DeviceFile.Name + ""\t"" + e.Message));
                    WriteLog(""Logs"", device, device.DeviceFileStatisticsModel.DeviceFile.Name + ""\t"" + e.Message);

                    //Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =&gt;
                    //{
                    //    MessageBox.Show(Application.Current.MainWindow, ""Error with camera '"" + device.DeviceId + ""'.\r\nDescription : "" + e.Message + "".\r\nClick OK to continue."", """", MessageBoxButton.OK, MessageBoxImage.Error);
                    //}));

                }

                var tupleChecksum = new Tuple&lt;string, byte[]&gt;(device.DeviceFileStatisticsModel.DeviceFile.FullName, new byte[] { });
                return tupleChecksum;
            }

        }
    }
</code></pre>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/55448824/is-there-anyway-to-test-postgres-with-wpf-by-using-moq,"['c#', 'wpf', 'nunit', 'moq']",658,False,0,1
"How to make a set up for unit testing with the bot framework (Echobot, using ITurnContext)","<p>I'm trying to make unit tests for an Echobot (just to understand how it works so I can use it for my actual bot), but there is one problem I'm unable to fix. The problem that I'm facing is that I'm using ITurnContext and every example I've come across is using DialogContext (with IWaitable to send the message).<br/>
ITurnContext is only readable so I can't set anything into it, unless I do it in the SetUp class which isn't that pretty - but it worked so I continued just to see what would happen and I got an error:<br/></p>

<pre><code>Message: Moq.MockException : 
Expected invocation on the mock at least once, but was never performed: c =&gt; c.PostAsync(Mock&lt;Microsoft.Bot.Builder.ITurnContext:00000001&gt;.Object, ""You sent 'test'"")
No setups configured.
No invocations performed.
</code></pre>

<p>To begin I used this guide to start: <a href=""https://medium.com/@createdincode/simple-unit-testing-in-microsofts-c-bot-framework-with-nunit-and-moq-345b805ecd1b"" rel=""nofollow noreferrer"">https://medium.com/@createdincode/simple-unit-testing-in-microsofts-c-bot-framework-with-nunit-and-moq-345b805ecd1b</a><br />
After I ran into some problems I tried searching online and came across this thread: <a href=""https://stackoverflow.com/questions/41348791/auto-testing-for-microsoft-bot-framework"">Auto testing for Microsoft Bot Framework</a> => but the links provided in the top answer all give me a 404..<br/>
Same goes for this one <a href=""https://stackoverflow.com/questions/50358031/unit-testing-bot-framework"">Unit Testing Bot Framework</a>, sadly :(<br/></p>

<p>The Test class is currently this:</p>

<pre><code>namespace EchoBot.UnitTest
{
    [TestFixture]
    class EchoTest
    {
        private Mock&lt;IChatHelper&gt; _chat;
        private EchoBotBot _echobot;
        private Mock&lt;ITurnContext&gt; _context;

        [SetUp]
        public void SetUp()
        {
            _chat = new Mock&lt;IChatHelper&gt;();
            _echobot = new EchoBotBot(_chat.Object);

            var activity = new Activity(ActivityTypes.Message);
            activity.Text = ""test"";

            _context = new Mock&lt;ITurnContext&gt;();

            _context.Setup(c =&gt; c.Activity).Returns(activity);
        }

        [Test]
        public async Task echoBackTest()
        {

            await _echobot.OnTurnAsync(_context.Object);

            _chat.Verify(c =&gt; c.PostAsync(_context.Object, ""You sent 'test'""));

        }

    }
}
</code></pre>

<p>And the Helper class is the same as the guide I send, except that I changed DialogContext to ITurnContext.
I don't know how to fix this error and I'm afraid of trapping myself inside a Moq hole (if you get what I mean).</p>

<p>I hope I described everything good enough and that somebody can help me! Thanks in advance (:</p>

<p><strong>EDIT: the code of the EchoBot</strong> </p>

<pre><code>public class EchoBotBot : IBot
    {
        private readonly EchoBotAccessors _accessors;
        private readonly ILogger _logger;

        private IChatHelper _chat;

        public EchoBotBot(IChatHelper chat)
        {
            _chat = chat;
        }

        public EchoBotBot(ConversationState conversationState)
        {
            if (conversationState == null)
            {
                throw new System.ArgumentNullException(nameof(conversationState));
            }

        }


        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {

                var responseMessage = $""You sent '{turnContext.Activity.Text}'\n"";
                await turnContext.SendActivityAsync(responseMessage);
            }
            else
            {
                await turnContext.SendActivityAsync($""{turnContext.Activity.Type} event detected"");
            }
        }
    }
</code></pre>
",https://stackoverflow.com/questions/55807092/how-to-make-a-set-up-for-unit-testing-with-the-bot-framework-echobot-using-itu,"['c#', 'unit-testing', 'botframework', 'moq']",1254,True,1,1
Unable to test a deserialization class using JUnit and Mockito,"<p>Purpose: To build a stickynote application using TDD (which I recently learned and now actively regretting)</p>

<p>Problem: I expect all the ""Note""s to be serialized and deserialized by thier own individual classes. And I wish to use the TDD approach, but I am unable to even test the happy path of the NoteReader class (deserializer) let alone the corner cases.</p>

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

<pre><code>package com.domainname.applicationname;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

public class NoteReader {
    private final FileInputStream fileInputStream;

    public NoteReader(FileInputStream fileInputStream) {
        this.fileInputStream = fileInputStream;
    }

    @SuppressWarnings(""unchecked"")
    public List&lt;Note&gt; load() {
        ObjectInputStream objectInputStream = null;
        List&lt;Note&gt; output = null;
        try {
            objectInputStream = new ObjectInputStream(fileInputStream);
            output = (List&lt;Note&gt;) objectInputStream.readObject();
            objectInputStream.close();
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
        return output;
    }
}
</code></pre>

<p>and here is the unit testing code:</p>

<pre><code>package com.domainname.applicationname;

import org.junit.*;
import org.mockito.Mockito;

import java.io.*;
import java.util.Arrays;
import java.util.List;

public class NoteReaderTest {
    private FileInputStream dummyFileInputStream;
    private NoteReader noteReaderDummy;

    private List&lt;Note&gt; expectedOutput = Arrays.asList(
            new Note(""some written text""),
            new Note(""some other written text"", NoteColor.lightGreen)
    );

    private ByteArrayOutputStream byteArrayOutputStream;
    private ObjectOutputStream objectOutputStream;
    private byte[] bytesToBeDeserialized;

    @Before
    public void setUp() throws IOException {
        dummyFileInputStream = Mockito.mock(FileInputStream.class);
        noteReaderDummy = new NoteReader(dummyFileInputStream);

        byteArrayOutputStream = new ByteArrayOutputStream();
        objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
    }

    @After
    public void tearDown() throws IOException {
        noteReaderDummy = null;
        byteArrayOutputStream.flush();
        objectOutputStream.flush();
        objectOutputStream.close();
    }

    @Test
    public void shouldLoadTheListOfNotes() throws IOException {
        //given
        objectOutputStream.writeObject(expectedOutput);
        bytesToBeDeserialized = byteArrayOutputStream.toByteArray();
        int intValueOfByteArray = dummyFileInputStream.read(bytesToBeDeserialized);
        //when
        Mockito.when(
                dummyFileInputStream.read()
        ).thenReturn(
                intValueOfByteArray
        );

        //then
        Assert.assertEquals(
                ""the notes have not been loaded"",
                expectedOutput,
                noteReaderDummy.load()
        );
    }
}
</code></pre>

<p>This has b/me an infinite loop and it's driving me nuts.</p>

<p>Question: How do I test a deserialization class? What am I doing wrong in the above code?</p>
",https://stackoverflow.com/questions/54184125/unable-to-test-a-deserialization-class-using-junit-and-mockito,"['java', 'unit-testing', 'mockito', 'junit4']",949,True,0,2
How to spy/stub with mocha/chai on ajax .fail() and .done()?,"<p>I am new to mocha/chai unit testing. I have following ajax call which is making a service call. I have added <code>.fail()</code> and <code>.done()</code> as a part of ajax call. </p>

<p>So I am not sure what I am missing here. Sorry if I am missing basic things here. Can someone please describe what's wrong here?</p>

<pre><code>function searchAPIcall(endPointurl, method, search_headers, search_identifier) {
    $.ajax({
        type: method,
        contentType: ""application/json; charset=utf-8"",
        dataType: ""json"",
        url: endPointurl,
        headers: search_headers,
        xhrFields: {
            withCredentials: true
        },
        success: function success(results, xhr, XMLHttpRequest) {
            successCallback();
        },
        error: function (xhr, textStatus, error) {
           callErrorFunc();
        }
    }).fail(function (xhr, textStatus, errorThrown) {
       callFailFunc();
    }).done(function () {
        callDoneFunction();
    });
}
</code></pre>

<p>I have written following unit test:</p>

<pre><code>describe.only('Testing searchdoctorAPIcall function', function () {
    var testurl = 'https://abc.serve.org/getData';
    beforeEach(function() {
        sinon.stub($, 'ajax');
    });

    afterEach(function() {
        $.ajax.restore();
    });

    it('should make an ajax call', function(done) {
        searchAPIcall(testurl, ""GET"", {""Content-Type"":""application-json;charset=utf-8"",X-Id"":""1da9b0c8-bb52""}, ""baseSearch"");
        expect($.ajax.calledOnce).to.be.true; 
        done(); 
    });
});
</code></pre>

<p>I am always getting the following error while executing unit test.</p>

<pre><code>undefined is not an object (near '...} }).fail(function (xhr,...')
</code></pre>

<p>But When I change my searchAPIcall function and remove the .dail() and .done() unit test is passing.</p>

<pre><code>function searchAPIcall(endPointurl, method, search_headers, search_identifier) {
    $.ajax({
        type: method,
        contentType: ""application/json; charset=utf-8"",
        dataType: ""json"",
        url: endPointurl,
        headers: search_headers,
        xhrFields: {
            withCredentials: true
        },
        success: function success(results, xhr, XMLHttpRequest) {
            successCallback();
        },
        error: function (xhr, textStatus, error) {
           callErrorFunc();
        }
    })
}
</code></pre>

<p>Now if I run the unit test then it is passing.</p>

<pre><code>should make an ajax call (passed)
</code></pre>
",https://stackoverflow.com/questions/54136247/how-to-spy-stub-with-mocha-chai-on-ajax-fail-and-done,"['javascript', 'ajax', 'unit-testing', 'mocha.js', 'sinon']",357,False,0,1
How to ensure that unit test doctrine is attempting to load to the same database as dev?,"<p>I would like to do some unit-testing in Symfony and am attempting to test something that already works, like this:</p>

<pre><code>&lt;?php namespace App\Tests\Api\Controller;

use Symfony\Component\HttpFoundation\Request;
use App\Controller\Admin\ProductAdminController;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * Class ProductsAdminControllerTest
 * @package App\Tests\Api\Controller
 */
class ProductsAdminControllerTest extends WebTestCase
{

    protected function setUp()
    {
        $kernel = static::createKernel();
        $kernel-&gt;boot();
        static::$container = $kernel-&gt;getContainer();
        /*$this-&gt;_em = $kernel-&gt;getContainer()-&gt;get('doctrine.orm.entity_manager');
        $this-&gt;_em-&gt;beginTransaction();*/
    }

    public function testSearchProductsEmpty()
    {
        $request = new Request([], [
            ""product_name"" =&gt; """"
        ]);
        $controller = new ProductsAdminController();
        $controller-&gt;setContainer(static::$container);
        $controller-&gt;getProducts($request);
        //$products = json_decode($controller-&gt;getProducts($request));
        $this-&gt;assertEquals(1, 1);
    }
}
</code></pre>

<p>Of course this will be modified after I overcome my current problem, which is that no matter what I do, I get the error of</p>

<blockquote>
  <p>Doctrine\DBAL\Exception\ConnectionException: An exception occurred in
  driver: SQLSTATE[HY000] [1045] Access denied for user
  'db_user'@'localhost' (using password: YES)</p>
</blockquote>

<p>Of course the database where my dev env is connecting has different credentials and I would like to ensure that my unit test is using the same credentials. How to achieve that?</p>
",https://stackoverflow.com/questions/57963365/how-to-ensure-that-unit-test-doctrine-is-attempting-to-load-to-the-same-database,"['mysql', 'unit-testing', 'symfony', 'doctrine']",671,True,0,1
Is it safe to overwrite app config after 1st config assignment is made (and doesn&#39;t it negate the benefit of facotry pattern)?,"<p>Hello so we have couple of methods to setup app configurations in Flask.</p>

<ol>
<li><p><code>ENV</code> var directly in cmd before running flask</p></li>
<li><p><code>app.config['xxx']</code></p></li>
<li><p><code>app.config.from_object</code> (module or class)</p></li>
<li><p><code>app.config.from_pyfile</code> (file)</p></li>
<li><p><code>app.config.from_envvar</code> (FILEPATH_ENVVAR)</p></li>
</ol>

<p>I have read that for example when unit testing, it is best to implement factory pattern as some configs don't work when overwritten.</p>

<p>So I am wondering if it is safe to use multiple methods from above? </p>

<p>For example if i follow below steps together then is it safe to assume config will be applied correctly?</p>

<p>Step 1: Use method 1 before running application (for example to set <code>ENV</code> var secret key <strong>or</strong> to setup an <code>ENV</code> var that can be checked in the code at step 2 to decide whether to apply dev/prod config settings class <strong>or</strong> to set <code>ENV</code> var PATH_TO_SOMECONFIGFILE)</p>

<p>Step 2: Immediately after initializing the app object, use method 3 (to set default production settings <strong>or</strong> check <code>ENV</code> var set in above step to invoke appropriate dev/prod class).</p>

<p>Step 3: Immediately after above step, use method 4 or 5 to update the config settings</p>

<p>So will the settings from step 3 overwrite all previous (previously set) settings correctly? And is this good practice? And doesn't it negate the benefit of using factory pattern since I have read that not using factory pattern (for example while unit testing) could result in certain config if updated will not apply correctly. Hence create factory pattern to get fresh object with the needed config applied.</p>
",https://stackoverflow.com/questions/57899200/is-it-safe-to-overwrite-app-config-after-1st-config-assignment-is-made-and-does,"['python', 'python-3.x', 'flask', 'python-unittest', 'python-config']",552,True,0,1
Spark: Unit Test - I have one function that unions 3 input datasets. Should I do Unit test on them?,"<p>I have written a code part of which is as below</p>

<pre><code>Object Cal{
def mergedatasets(df: Dataset[Row], df1: Dataset[Row],df2: Dataset[Row]):Dataset[Row]={
 df.union(df1).union(df2)
//other logic

}

}
object readDataframes{
def readFirstDF(spark:SparkSession):Dataset[Row]={
 spark.read.json(somefile)
}
def readSecondDF(spark:SparkSession):Dataset[Row]={
 spark.read.json(somefile)
}
def readThirdDF(spark:SparkSession):Dataset[Row]={
 spark.read.json(somefile)
}
}
</code></pre>

<p>In the above code I am reading 3 files and then merging them into one which I use further for processing.
Based on the above scenario my questions are as follows:</p>

<ol>
<li>Does it make sense to Unit test the function mergdatasets? If yes, What are the basic/minimal things to test for?How to check for corner cases, if any?</li>
<li>Does it make sense to Unit test readDataframes?If yes what to test for ?Would it be to check if inferred schema is as expected? and anything else?</li>
</ol>

<p>I would like to extend the above questions for the following functions too</p>

<pre><code>def timeIntervalAgg(df: Dataset[Row]): Dataset[Row] = {

    val timeInterval = df
      .groupBy(""id"",""page_number"")
      .agg(sum(""timeInterval"").alias(""timeInterval""))
    timeIntervalAgg

  }

  def timeInterval(df: Dataset[Row]): Dataset[Row] ={

    val windowSpec = Window.partitionBy(""id"").orderBy(""date_time"")
    val timeFmt = ""yyyy-MM-dd'T'HH:mm:ss""
    val endTime = lead(col(""date_time""),1).over(windowSpec)
    val startTime = col(""date_time"")
    val timeDiff = (unix_timestamp(endTime, timeFmt)
      - unix_timestamp(startTime, timeFmt))
    val timeInterval = df
      .withColumn(""timeInterval"", lit(when(col(""event"") === ""this_event"",lit(null)
        .cast(""long""))
        .otherwise(timeDiff)))
      .where(""""""event != ""this_event"" """""")
    timeInterval

  }

  def addOddpages(df: Dataset[Row]) :Dataset[Row] = {

    val odd = df
      .where(""""""view_mode = ""twin"" """""")
      .withColumn(""page_odd"", col(""page"") + 1)
      .drop(""page"")
      .select(col(""id""), col(""date_time"")
        .cast(""timestamp""),col(""page_odd"")
        .alias(""page""), col(""page_view_mode""),
        col(""event""),col(""timeInterval""))
    val timeIntervalWithoddPage = df.union(odd)
    timeIntervalWithoddPage

  }
</code></pre>

<ul>
<li><p>Please suggest if it is needed to refactor the code in a better way
to enable better testing.</p></li>
<li><p>My goal is to understand what to test for? what to look out while
writing test for code like above? All this questions are for Spark
code Unit testing not other language code testing.</p></li>
<li>How to unit test without redundantly testing spark which is already
tested?</li>
<li>Is it needed to test every function like this(since the logic/code is not very complicated) or is best to test the
function that combines the above functions in proper order.By doing
so can it be called unit testing?</li>
<li>Please feel free to share some sample Unit tests that you may write
for above code.</li>
</ul>
",https://stackoverflow.com/questions/58066394/spark-unit-test-i-have-one-function-that-unions-3-input-datasets-should-i-do,"['unit-testing', 'apache-spark', 'apache-spark-sql']",285,False,0,1
Boost test case mixing dataset and template,"<p>I'm using boost.test for unit testing (currently using boost 1.71.0). I have a template class I would like to test with a dataset.</p>

<p>I could only find ways to test on different template parameters (using <code>BOOST_AUTO_TEST_CASE_TEMPLATE</code>) or on a dataset (using <code>BOOST_DATA_TEST_CASE</code>). But i couldn't find a way to mix both template and dataset.</p>

<p>Here is a MWE of what I achieved to do, and commented what I'm trying to do.</p>

<p><code>test.cpp</code>:</p>

<pre class=""lang-cpp prettyprint-override""><code>#define BOOST_TEST_MODULE data_template
#include &lt;boost/mpl/list.hpp&gt;
#include &lt;boost/test/data/test_case.hpp&gt;
#include &lt;boost/test/unit_test.hpp&gt;
#include &lt;vector&gt;
#include &lt;list&gt;
#include &lt;numeric&gt; // std::accumulate

template &lt;typename C&gt;
struct Testee{
    C container;
    typename C::value_type f(){
        // just a dummy function to be tested
        return std::accumulate(container.begin(),container.end(),0);
    }
};

typedef boost::mpl::list&lt;std::vector&lt;double&gt;, std::list&lt;double&gt;, std::vector&lt;size_t&gt;&gt; container_types;

template &lt;class T&gt; void test_containers(size_t size)
{
    Testee&lt;T&gt; t;
    t.container = T(size,1);

    BOOST_CHECK_EQUAL(t.f(), size);
}

// test on all container types but only with size=100 (3 test cases)
BOOST_AUTO_TEST_CASE_TEMPLATE(test1, T, container_types)
{
    test_containers&lt;T&gt;(100);
}

// test with several container sizes but only for vector&lt;double&gt; (6 test cases)
BOOST_DATA_TEST_CASE(test2, boost::unit_test::data::make({0, 1, 2, 10, 100, 1000}), size)
{
    test_containers&lt;std::vector&lt;double&gt;&gt;(size);
}

// What I'm looking for looks like:
// // test for each combination of container type and size (6*3=18 test cases)
// BOOST_DATA_TEST_CASE_TEMPLATE(test3, T, container_types, boost::unit_test::data::make({0, 1, 2, 10, 100, 1000}), size)
// {
//     test_containers&lt;T&gt;(size);
// }
</code></pre>

<p><code>CMakeLists.txt</code>:</p>

<pre><code>CMAKE_MINIMUM_REQUIRED( VERSION 3.5 )
PROJECT(data_template_test
    LANGUAGES CXX)

set (CMAKE_CXX_FLAGS ""-std=c++17 -Wall ${CMAKE_CXX_FLAGS}"")

find_package(Boost 1.59 REQUIRED COMPONENTS unit_test_framework)
add_executable(${PROJECT_NAME} test.cpp)
target_link_libraries(${PROJECT_NAME} Boost::unit_test_framework)
target_compile_definitions(${PROJECT_NAME} PRIVATE BOOST_TEST_DYN_LINK)
</code></pre>

<p>The MWE produces 9 test cases that pass without errors, but I want the combination of all types with all sizes, so 3x6=18 test cases.
Is there any way to do that using boost-test? Maybe using some more verbose / less friendly API?</p>

<p>Thanks for helping!</p>
",https://stackoverflow.com/questions/57789066/boost-test-case-mixing-dataset-and-template,"['c++', 'boost', 'boost-test']",566,False,9,0
NSubstitute Mock static class and static method,"<p>I'm new at unit testing, and I'm trying to mock a static method in a static class. I already read that you can't do that, but I was looking a way to work around that.</p>
<p>I can't modify the code, and making the same function without being static is not an option because they check the code coverage of the test, and I need at least 90%.<br />
I already tried to mock the variables that it uses but it doesn't work.</p>
<pre><code>public static class MyClass
{
    public static response MyMethod(HttpSessionStateBase Session, 
        otherVariable, stringVariable)
    {
        //some code
    }
}

public ActionResult MyClassTested()
{
    var response = MyClass.MyMethod(Session);
    //more code
}
</code></pre>
<p>My problem is that this method is inside a controller that declares a var with the response, and according to that redirects the user.</p>
",https://stackoverflow.com/questions/56601788/nsubstitute-mock-static-class-and-static-method,"['c#', 'visual-studio-2017', 'mocking', 'nsubstitute']",9906,True,4,2
Unit testing outside of a package in R,"<p>Often times we're using R in contexts where we want to have reproducibility in the face of modifications and where we have complex code bases but outside of writing a package. It seems like testthat and the other testing packages are geared towards unit testing for package code, which makes sense since that's the most common case where you need a lot of testing where you're not in full control of all the data, but I was wondering if there was a good package or method for unit testing in R outside of the context of writing a package. </p>

<p>For example, a lot of times in a package context you're testing something of the form: </p>

<pre class=""lang-r prettyprint-override""><code>foo &lt;- function(bar){
    # do something to bar
    return(bar.outcome)
}
</code></pre>

<p>and so then you're testing for expected output from the function, that things are the right type, that there is proper error handling. The way you do this is that you create a directory in your package for tests and write them there and then devtools can use <code>load_all</code> and <code>testthat</code> to run them and produce results. </p>

<p>One thing I would like to be able to do is run these same sort of tests outside of the context of a package, such as in a script. This is important because a lot of R code that is written in academia doesn't generalize a whole lot to different contexts or data without considerable difficulty, so that having a package doesn't make much sense, but at the same time unit testing would make it easier to extend the code in future packages. That's the easy case.</p>

<p>The harder case is actually something you rarely do in packages, which is test things about the shape, kind, and state of the data. So, for example, I often read R code written in academia with comments like </p>

<pre class=""lang-r prettyprint-override""><code>data &lt;- data %&gt;% doSomething() #1023 rows 

parameter_df &lt;- // read file 
print(parameter_df) # 5 columns 
data &lt;- data %&gt;% doSomething(param = parameter_df)

lapply(df, class) #should be char, char, char, numeric, Date

</code></pre>

<p>I like the idea that ""every time you want to write a print statement, write a test instead"", but I actually don't have a good framework for how this should be done in R. Especially in this harder case where you're not testing a function, you're testing to make sure that the data flowing through your program is correct. </p>

<p>The context here is that R is used in a lot of contexts where the point of a script is replication in the scientific sense, but where there is possibly great gain from people being able to easily extend other's scripts which are released as part of replication materials for new projects, which is much harder to do, especially in complex code, whenever there are no tests and code can be very fragile and fail in nontrivial and <em>silent</em> ways. </p>
",https://stackoverflow.com/questions/58002252/unit-testing-outside-of-a-package-in-r,"['r', 'unit-testing']",775,True,8,1
.Net Core Nuget Package Version mismatch: Two packages have references to different versions of the same dll,"<p>Currently I have a ASPNet.Core web application with 2 nuget packages that reference different versions of the same dll.  The web project works fine, but when I add a reference in a <code>Unit Testing</code> project to the <code>Web</code> project, I get this compile error.  Something is clearly solving these dll differences because the web project compiles without issue.  It's only when I add a reference to the web project to add tests does the below compilation error occur, and only in the unit testing project.</p>

<blockquote>
  <p>Assembly 'KII.Web' with identity
  'KII.Web, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null' uses 'Microsoft.Extensions.Options,
  Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
  which has a higher version than referenced assembly
  'Microsoft.Extensions.Options' with identity
  'Microsoft.Extensions.Options, Version=2.1.1.0, Culture=neutral,
  PublicKeyToken=adb9793829ddae60'    KII.UnitTests<br>
  C:\Projects\kii\web\src\Tests\KII.UnitTests\Controllers\HomeControllerTest.cs</p>
</blockquote>

<p>Additionally, I also have this build error in the Unit Test project.</p>

<blockquote>
  <p>Assembly 'KII.Web' uses 'Microsoft.AspNetCore.Mvc.ViewFeatures,
  Version=2.1.1.0, which has a higher version than referenced assembly
  'Microsoft.AspNetCore.Mvc.ViewFeatures' with identity
  'Microsoft.AspNetCore.Mvc.ViewFeatures, Version=1.0.3.0</p>
</blockquote>

<p>Essentially the web project has this</p>

<ul>
<li><code>Microsoft.AspNetCore.App 2.2.0</code> has a reference to <code>Microsoft.Extensions.Options 2.2.0</code></li>
<li><code>KenticoCloud.Delivery 10.0.1</code> has a reference to <code>Microsoft.Extensions.Options 2.1.1</code></li>
</ul>

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

<ul>
<li>clean/rebuild</li>
<li>manually delete bin directories</li>
<li>add <a href=""https://blog.rytmis.net/2016/03/29/asp-net-core-and-assembly-binding-redirects/"" rel=""nofollow noreferrer"">binding redirects</a> in app.configs in both unit testing and web projects</li>
<li>Update KenticoCloud.Delivery to <code>11.0.0-beta1</code></li>
</ul>

<p>Since this is .net core, there are no <code>hintpaths</code> that I can tweak in the <code>web.config</code>.  I don't think checking the GAC for an old version/updating it is going to work because .net core doesn't use the GAC. Since the dll in question is a sub-dependency of nuget packages, I cannot update the nuget packages to resolve.</p>

<p><a href=""https://stackoverflow.com/questions/39628060/error-cs1705-assembly-uses-system-web-mvc-version-5-2-3-0-which-has-a-higher"">Similar SO question</a></p>
",https://stackoverflow.com/questions/57908508/net-core-nuget-package-version-mismatch-two-packages-have-references-to-differ,"['.net', 'asp.net-core', '.net-core']",2347,True,4,1
PHP Fatal error: Class &#39;WP_UnitTestCase&#39; not found when trying to run test-sample,"<p>I am trying to initialize php unit testing with my wordpress plugin using phpunit.  I am running xampp on windows.  My xampp installation is also on my E: drive if that makes any difference.  I am following along with this tutorial: </p>

<p><a href=""https://www.smashingmagazine.com/2017/12/automated-testing-wordpress-plugins-phpunit/"" rel=""nofollow noreferrer"">https://www.smashingmagazine.com/2017/12/automated-testing-wordpress-plugins-phpunit/</a></p>

<p>I have gotten to the part where I run</p>

<p><code>install-wp-tests.sh wordpress_test root '' localhost latest</code></p>

<p>I run that and it pops up and closes quickly, so I don't know if it is really working or not.  I then try to run</p>

<p><code>phpunit tests/test-sample.php</code></p>

<p>and I get: </p>

<pre><code>PHP Fatal error:  Class 'WP_UnitTestCase' not found in E:\xampp\htdocs\wp-content\plugins\SRBC\tests\test-sample.php on line 11

Fatal error: Class 'WP_UnitTestCase' not found in E:\xampp\htdocs\wp-content\plugins\SRBC\tests\test-sample.php on line 11

</code></pre>

<p>I assume that means the install-wp-test.sh isn't installing correctly and it is missing those classes.  Any ideas?</p>
",https://stackoverflow.com/questions/56763165/php-fatal-error-class-wp-unittestcase-not-found-when-trying-to-run-test-sampl,"['php', 'phpunit']",1628,True,3,1
Golang multi-method interface and struct naming,"<p>Golang docs provide a clear guidance on <a href=""https://golang.org/doc/effective_go.html#interface-names"" rel=""noreferrer"">how to name single-method interface</a> (by appending ""-er""). But what is the best practice to name a multi-method interface that has only a single struct implementing it? </p>

<p>In C# the interface would have ""I"" prefix, in Java, the class will have ""Impl"" suffix. Are there similar guidelines for Golang?</p>

<p>The point of having an interface here is to be able to mock it for unit-testing of components that depend on it.</p>

<p>Here is a specific example of UserManager interface. It is going to be consumed by a web api controller that will translate HTTP requests into method calls on this interface.  This web api controller will use most of the methods of UserManager. </p>

<pre><code>type UserManager interface { // Should it be UserManagerInterface ?
    GetUser(id int) User
    CreateUser(user User)
    DeleteUser(id int)
    ResetPassword(id int, newPassword string)
    VerifyEmail(id int)
}

type UserManagerImpl struct { // -Impl, or -Struct, or something else? 

}
</code></pre>
",https://stackoverflow.com/questions/57063010/golang-multi-method-interface-and-struct-naming,['go'],5004,True,12,3
How should you divide a service layer method into testable chunk?,"<pre><code>exports.sendFeedbackServiceProviderMethod = function(req, res, next) {

    var articleId = req.body.articleId
    var commentId = req.body.commentId
    var action = req.body.action
    var meta = req.body.meta

    var Target
    var targetId
    if (articleId) {
        Target = Article
        targetId = articleId
    }
    else if (commentId) {
        Target = Comment
        targetId = commentId
    }

    //1. find the target
    //Note: will refetch when need to send json, since feedback has been changed
    Target.findById(targetId).exec(function(err, target) {
        if (err)
            return next(err)
        if (!target)
            return next(helper.getGeneralError('target does not exist'))


        //2. find the feedback
        var criteria = {}
        criteria['statusMeta.createdBy'] = req.user
        if (action === 'like' || action === 'dislike' || action === 'unlike' || action === 'undislike')
            criteria['type'] = {$in: ['like', 'dislike']}
        else if (action === 'share' || action === 'unshare')
            criteria['type'] = 'share'
        if (articleId)
            criteria['target.article'] = articleId
        else if (commentId)
            criteria['target.comment'] = commentId

        Feedback.find(criteria).exec(function(err, feedbacks) {

            if (err)
                next(err)
            if (feedbacks.length === 0) {
                //3. Feedback does not exist, create it
                var newFeedback = new Feedback()

                if (action === 'like' || action === 'dislike' || action === 'share') {
                    newFeedback.type = action
                    newFeedback.status = 'normal'
                    newFeedback.statusMeta.createdBy = req.user
                    if (articleId)
                        newFeedback.target.article = targetId
                    else if (commentId)
                        newFeedback.target.comment = targetId
                    if (meta)
                        newFeedback.meta= meta
                }

                newFeedback.save(function(err) {
                    if (err)
                        return next(err)

                    //4. save to target feedbacks list
                    target.feedbacks.push(newFeedback)
                    target.save(function(err) {
                        if (err)
                            return next(err)

                        //5. save to user feedbacks list
                        req.user.feedbacks.push(newFeedback)
                        req.user.save(function(err) {
                            if (err)
                                return next(err)

                            //6. done
                            //Note: send the target!
                            //Note: refetch target and populate, since its feedbacks have been changed
                            var query = Target.findById(targetId)
                            populateUsersForQuery(query)
                            populateFeedbacksForQuery(query)
                            query.exec(function(err, target) {
                                if (err)
                                    return next(err)
                                return res.json(target)
                            })
                        })
                    })
                })
            }
            else {
                //3x. Found the feedback, update it
                var feedback = feedbacks[0] //must be length 1

                if (action === 'like' || action === 'dislike' || action === 'share') {
                    feedback.type = action
                    feedback.status = 'normal'
                    feedback.statusMeta.updatedBy = req.user
                    feedback.statusMeta.updatedDate = new Date
                }
                else if (action === 'unlike' || action === 'undislike' || action === 'unshare') {
                    feedback.status = 'deleted'
                    feedback.statusMeta.deletedBy = req.user
                    feedback.statusMeta.deletedDate = new Date
                }
                if (meta)
                    feedback.meta= meta

                feedback.save(function(err) {
                    if (err)
                        return next(err)

                    //4x. done
                    //Note: send the target!
                    //Note: refetch target and populate, since its feedbacks have been changed
                    var query = Target.findById(targetId)
                    populateUsersForQuery(query)
                    populateFeedbacksForQuery(query)
                    query.exec(function(err, target) {
                        if (err)
                            return next(err)
                        return res.json(target)
                    })
                })
            }
        })
    })
}
</code></pre>

<p>I have this piece of code and it's huge and I was wondering how to go about testing it. Should I divide it into smaller pieces and how should I do this, or should I leave it as it is and test the whole chunk. Also, I am not sure what's the standard way of testing a service layer method, do we just test the route as a whole like here:</p>

<pre><code>describe('POST /user', function() {
  it('user.name should be an case-insensitive match for ""john""', function(done) {
    request(app)
      .post('/user')
      .send('name=john') // x-www-form-urlencoded upload
      .set('Accept', 'application/json')
      .expect(function(res) {
        res.body.id = 'some fixed id';
        res.body.name = res.body.name.toLowerCase();
      })
      .expect(200, {
        id: 'some fixed id',
        name: 'john'
      }, done);
  });
});
</code></pre>

<p>Or should I check the state of every object modified? Could you tell me how to set up the unit testing for the method above and how I should divide it to make testing easier?</p>
",https://stackoverflow.com/questions/58896440/how-should-you-divide-a-service-layer-method-into-testable-chunk,"['node.js', 'unit-testing', 'tdd']",302,True,2,1
How to avoid ThrottleRequestsException in Laravel unit test?,"<p>I am working on an application that has date logic within i.e something will be returned from the database based on the date, and only the relevant data for that date should be returned. How would I go about unit testing this? There are 24 dates that return 24 different pieces of data, I thought maybe doing something like this, </p>

<pre class=""lang-php prettyprint-override""><code>public function testGetActiveData()
{
    $this-&gt;withoutExceptionHandling();

    //Create the data
    $dates = CarbonPeriod::create('2019-12-01', '2019-12-12');
    $start_date = new Carbon(""2019-12-01 00:00:00"");

    $dates-&gt;forEach(function($date){
        $data = factory(Data::class)-&gt;create([
            'date_playable' =&gt; $date-&gt;toDateTimeString()
        ]);
        factory(LinkedData::class, 15)-&gt;create([
            'data_id' =&gt; $data-&gt;id
        ]);
    });

    for($day = 1; $day &lt;= 24; $day++) {
        if($day = 1) {
            Cache::put('data_date', $start_date-&gt;toDateTimeString(), now()-&gt;addMinutes(30));
        } else {
            Cache::put('data_date', $start_date-&gt;toDateTimeString()-&gt;addDays($day), now()-&gt;addMinutes(30));
        }

        $response = $this-&gt;json('GET', '/api/data');

        $response-&gt;assertJson(['date_playable' =&gt; Cache::get('data_date')]);

    }
}
</code></pre>

<p>However this errors due to too many attempts, is there a better way to test this? An obvioulsy I am testing dates in the future so I am pushing a ""future date"" into cache and then using that is there a better of doing that also?</p>
",https://stackoverflow.com/questions/57969453/how-to-avoid-throttlerequestsexception-in-laravel-unit-test,"['php', 'laravel', 'unit-testing', 'phpunit']",3206,True,2,1
Unit tests to catch exception in controller method,"<p>I'm trying to learn unit testing in xUnit for ASP.NET Core projects. In order to achieve it, I have created simple ASP.NET Core project to perform tests on it. However I cannot get 100% cover of tests due to wrong testing an exception that's being caught inside controller method.</p>

<p>Here is my controller method I'm testing:</p>

<pre><code>        [HttpGet]
        public async Task&lt;IEnumerable&lt;User&gt;&gt; GetUsers()
        {
            try
            {
                var users = await _repository.User.GetAllUsersAsync();
                return users;
            }
            catch (Exception e)
            {
                _logger.LogError($""Error in GetUsers: {e}"");
                return null;
            }
        }
</code></pre>

<p>And here is my unit test method in xUnit:</p>

<pre><code>        [Fact]
        public async Task GetUsers_WhenCalled_ReturnsCorrectAmountOfUsers()
        {
            //Arrange
            var mockRepo = new Mock&lt;IRepositoryWrapper&gt;();
            mockRepo.Setup(repo =&gt; repo.User.GetAllUsersAsync())
                .ReturnsAsync(GetTestUsers());
            var controller = new UsersController(mockRepo.Object, _logger, _service);

            //Act
            var result = await controller.GetUsers();

            //Assert
            var model = Assert.IsAssignableFrom&lt;IEnumerable&lt;User&gt;&gt;(result);
            model.Count().Should().Be(3);
            Assert.Throws&lt;NullReferenceException&gt;(() =&gt; 
            _controller.GetUsers().Exception);
        }
</code></pre>

<p>When I run tests, everything gets green status, however inside the controller class I cannot see a 'green tick' next to the lines with catch block scope. I'd really like to know how to write proper code for testing an exceptions inside catch blocks!</p>
",https://stackoverflow.com/questions/54503317/unit-tests-to-catch-exception-in-controller-method,"['c#', 'unit-testing', 'asp.net-core', 'moq', 'xunit']",3712,True,2,1
Unit test component with mocked service - error,"<p>I started working on testing components and service in Angular. I watched a course on pluralsight and tried to follow ideas from: <a href=""https://codecraft.tv/courses/angular/unit-testing/mocks-and-spies/"" rel=""nofollow noreferrer"">https://codecraft.tv/courses/angular/unit-testing/mocks-and-spies/</a> 
however, I have a problem with the testing component method. Unfortunately, I cannot find a solution so decided to ask you for help.</p>

<p>My service:</p>

<pre><code>@Injectable()
export class MyService {
  private config: AppConfig;
  constructor(private apiService: ApiService, private configService: ConfigurationService) {
    this.config = configService.instant&lt;AppConfig&gt;();
  }

  public get(name: string, take: number = 10, skip: number = 0, params?:any): Observable&lt;any&gt; {
    return this.apiService.post(`${this.config.baseUrl}/${name}/paginated?take=${take}&amp;skip=${skip}`, params);
  }
}
</code></pre>

<p>My Component:</p>

<pre><code> @Component({
  selector: 'my',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {
  @Input(""customerId"") customerId: string;
  items: CustomerItem[] = [];

  public pagingInfo: PagingMetadata = {
    itemsPerPage: 5,
    currentPage: 1,
    totalItems: 0
  };
  constructor(private service: MyService) { }

  ngOnInit() {
    if (this.customerId) {
      this.updateItems();
    }
  }

  updateItems() {
    let skip = (this.pagingInfo.currentPage - 1) * this.pagingInfo.itemsPerPage;
    let take = this.pagingInfo.itemsPerPage;
    this.service.get(""customer"", take, skip, { customerId: this.customerId }).subscribe(result =&gt; {
      this.items = result.entities;
      this.pagingInfo.totalItems = result.total;
    }, (error) =&gt; {
      console.log(error.message);
    });
  }
}
</code></pre>

<p>My my.component.spec.ts test file:</p>

<pre><code>describe('MyComponent', () =&gt; {
  let component: MyComponent;
  let fixture: ComponentFixture&lt;MyComponent&gt;;
  let mockService;
  let ITEMS = [
    {
        ""title"": ""test"",
        ""id"": ""5e188d4f-5678-461b-8095-5dcffec0855a""
    },
    {
        ""title"": ""test2"",
        ""id"": ""5e188d4f-1234-461b-8095-5dcffec0855a""
    }
]

beforeEach(async(() =&gt; {
  mockService = jasmine.createSpyObj(['get']);

  TestBed.configureTestingModule({
    imports: [NgxPaginationModule, RouterTestingModule],
    declarations: [MyComponent],
    providers: [
      { provide: MyService, useValue: mockService }
    ]
  })
    .compileComponents();
}));

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

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

// works fine
it('should NOT call updateItems method on initialization', () =&gt; {
  component.ngOnInit();
  let spy = spyOn(component, 'updateItems').and.callThrough();

  expect(spy).not.toHaveBeenCalled();
});

// works fine
it('should call updateItems method on initialization', () =&gt; {
    component.customerId = ""1"";
    let spy = spyOn(component, 'updateItems').and.callFake(() =&gt; { return null });

    component.ngOnInit();

    expect(spy).toHaveBeenCalled();
  });

// gives error
it('should update items', () =&gt; {
  component.pagingInfo.currentPage = 1;
  component.pagingInfo.itemsPerPage = 10;
  component.customerId = ""1"";
  mockService.get.and.returnValue(of(ITEMS));

  component.updateItems();

  expect(component.items).toBe(ITEMS);
});
});
</code></pre>

<p>3 first tests work fine, however for the last - updating items I got error:</p>

<blockquote>
  <p>Expected undefined to be [ Object({""title"": ""test"",""id"": ""5e188d4f-5678-461b-8095-5dcffec0855a""},{""title"": ""test2"",""id"": ""5e188d4f-1234-461b-8095-5dcffec0855a""})]</p>
</blockquote>

<p>I would be very grateful for any tips ;)</p>
",https://stackoverflow.com/questions/54117197/unit-test-component-with-mocked-service-error,"['angular', 'unit-testing', 'jasmine', 'mocking', 'spy']",1839,True,2,1
How to do method instrumentation in Kotlin - but keep it method testable,"<p>I have a method that I need to instrument to call New Relic: setup a segment, run the business logic and end the segment. Is there a way to do it in Kotlin (as in Spring AOP)?</p>

<pre><code>fun saveCustomer() {
   val segment = NewRelic.getAgent().transaction.startSegment(""save customer"")
   // business logic here
   segment.end()
}
</code></pre>

<p>I experimented isolating <code>newRelic</code> dependency and can now reuse it across my whole app:</p>

<pre><code>fun saveCustomer() {
   newRelic.executeWithSegment { // this starts/ends the segment and calls the function block
      // business logic here
   }
}
</code></pre>

<p>However, this makes unit testing of <code>saveCustomer</code> harder, because after mocking <code>newRelic.executeWithSegment</code> (which I must; otherwise New Relic is contacted in the tests), the code block (business logic) is not executed anymore - so the test fails.</p>

<p>Is there a way to fulfill those requirements? (Perhaps with an annotation or using Kotlin delegation pattern or even some lightweight library; not sure.)</p>
",https://stackoverflow.com/questions/57915364/how-to-do-method-instrumentation-in-kotlin-but-keep-it-method-testable,"['kotlin', 'aop', 'newrelic']",147,True,2,1
How to access this.app and/or a injected plugin in a Vuex store test with Nuxt and Jest,"<p>In a Vuex store action, I'm using this.app.router and a Nuxt plugin that injects the property $alert. </p>

<p>When I'm trying to test the Vuex store with Jest the test keeps failing because both of the properties are undefined.</p>

<p>I'm unit testing the getters, mutations, and actions separately as a javascript function like described <a href=""https://vue-test-utils.vuejs.org/guides/#testing-a-vuex-store"" rel=""nofollow noreferrer"">here</a>.</p>

<p>So not using Vue Test Utils or Vuex.</p>

<p>What I've already tried without any effect:</p>

<ul>
<li>setup a new <code>Vuex.Store</code> and <code>localVu</code>e from <code>vue-test-utils</code>.</li>
<li>setting a global variable with properties app and <code>$alert</code> before the test.</li>
</ul>

<pre><code>// actions.js
export default {
  async signup({ dispatch, state }, payload) {
      try {
        await dispatch('createUserData', payload)
        await dispatch('setUser', payload)
        this.app.router.push(state.redirectAfterLogin)
      } catch (error) {
        this.$alert.error(`errors.${error.code}`)
      }
  }
}

// actions.spec.js
import actions from '@/store/auth/actions'

describe('Auth store', () =&gt; {
  let dispatch
  let state

  test('signup', async () =&gt; {
    dispatch = jest.fn()
    state = {
      user: null
    }
    await actions.signup(
      { dispatch, state },
      {
        email: 'test@test.nl',
        password: 'password',
        displayName: 'Test'
      }
    )
    expect(dispatch).toHaveBeenCalledWith('createUserData')
    expect(dispatch).toHaveBeenCalledWith('setUser')
  })
})
</code></pre>

<p>Someone has any idea where and how I can define this method as mock functions in my test file?</p>
",https://stackoverflow.com/questions/55949774/how-to-access-this-app-and-or-a-injected-plugin-in-a-vuex-store-test-with-nuxt-a,"['vue.js', 'jestjs', 'vuex', 'nuxt.js']",2190,True,2,2
stubbing a yield* function call with sinon,"<p>I'm new to <code>function*</code>/<code>yield</code>/<code>yield*</code> as well as to unit testing, and I'm not sure why my unit test code isn't working. It's using sinon stubbing with mocha testing framework. I've read up on <code>function*</code>/<code>yield</code>/<code>yield*</code> but it's still confusing to me.</p>

<p>Using the Co library, I have a <code>function*</code> with a <code>yield*</code> inside that calls another <code>function*</code>. I'm trying to mock the call to the <code>function*</code> called by <code>yield*</code> with a sinon stub, but the stub returns undefined. The stub returns the correct response if it's simply <code>yield</code> and not <code>yield*</code>.</p>

<p>import:</p>

<pre><code>import * as name from './file';
</code></pre>

<p>call to original generator function:</p>

<pre><code>export const func = (a, b, c) =&gt; co(secondFunc.bind(this, a, b, c));
</code></pre>

<p>function secondFunc:</p>

<pre><code>function* secondFunc(a, b, c) {
  try {
    const x = yield* name.get(a); // this is where x is undefined
    // logic
    return value;
  } catch (err) {
    // logic
  }
}
</code></pre>

<p>unit test:</p>

<pre><code>const callback = sinon.stub(name, 'get');
callback.returns(new Promise((resolved, reject) =&gt; resolved(response)));

co(func(""a"", ""b"", ""c"")).then((value) =&gt; {
    console.log(value);
    done();
}).catch(done);     
</code></pre>

<p>(Of note, the original code is not something I wrote. I'm just adding unit tests.)</p>
",https://stackoverflow.com/questions/59308604/stubbing-a-yield-function-call-with-sinon,"['javascript', 'unit-testing', 'mocha.js', 'sinon', 'yield']",1187,True,2,2
Unable to execute groovy test files in Springboot application,"<p>I have created a sample <code>SpringBoot</code> application for writing unit-tests using <code>Spock</code> framework. Below are the files.</p>

<p><strong>Calculator.Java</strong></p>

<pre><code>public class Calculator {
   @Autowired
   Addition addition;

   public int calculate(int a, int b, String choice) {
      return addition.add(a, b);
   }
}
</code></pre>

<p>I have created test-class using Junit as below, its working fine</p>

<p><strong>CalculatorTest.java</strong></p>

<pre><code>@SpringBootTest
public class CalculatorTest {

   @Mock
   Addition addition;

   @InjectMocks
   Calculator cal;

   @Test
   public void testCal() {
     when(addition.add(2, 3)).thenReturn(8);
     int value = cal.calculate(2, 3, ""add"");
     assertEquals(8, value);
   }
}
</code></pre>

<p>But I need to write unit-test using <code>Spock Framework</code>, So I created groovy files and added corresponding <code>dependencies</code> and <code>plugins</code> in the <code>pom.xml</code>. when I run <code>mvn clean install</code> to build the application. Under <code>TESTS</code> I can see only <code>CalculatorTest.java</code> execution but not able to see <code>CalculatorGroovyTest.groovy</code> file's execution.</p>

<p><strong>CalculatorGroovyTest.groovy</strong></p>

<pre><code>@SpringBootTest
class CalculatorGroovyTest extends Specification{

   @Mock
   Addition addition;

   @InjectMocks
   Calculator cal;

   def ""Callator test method""(){
       given:
           addition.add(5, 8) --&gt; 9;
       when:
           int val = cal.calculate(5, 8, ""add"");
       then:
           val == 9;
   }
}
</code></pre>

<p>Below are the dependencies and Plugins which I added in my pom.</p>

<p><strong>Dependencies</strong></p>

<pre><code>&lt;dependency&gt;
        &lt;groupId&gt;org.spockframework&lt;/groupId&gt;
        &lt;artifactId&gt;spock-core&lt;/artifactId&gt;
        &lt;version&gt;1.3-groovy-2.5&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.codehaus.groovy&lt;/groupId&gt;
        &lt;artifactId&gt;groovy-all&lt;/artifactId&gt;
        &lt;version&gt;2.4.1&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.spockframework&lt;/groupId&gt;
        &lt;artifactId&gt;spock-guice&lt;/artifactId&gt;
        &lt;version&gt;1.0-groovy-2.4&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
</code></pre>

<p><strong>PlugIns</strong></p>

<pre><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;useFile&gt;false&lt;/useFile&gt;
                &lt;includes&gt;
                    &lt;include&gt;**/*Spec.groovy&lt;/include&gt;
                    &lt;include&gt;**/*Test.groovy&lt;/include&gt;
                    &lt;include&gt;**/*Test.java&lt;/include&gt;
                &lt;/includes&gt;
            &lt;/configuration&gt;
        &lt;/plugin&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.codehaus.gmavenplus&lt;/groupId&gt;
            &lt;artifactId&gt;gmavenplus-plugin&lt;/artifactId&gt;
            &lt;version&gt;1.4&lt;/version&gt;
            &lt;executions&gt;
                &lt;execution&gt;
                    &lt;goals&gt;
                        &lt;goal&gt;compile&lt;/goal&gt;
                        &lt;goal&gt;testCompile&lt;/goal&gt;
                    &lt;/goals&gt;
                &lt;/execution&gt;
            &lt;/executions&gt;
            &lt;configuration&gt;
                &lt;testSources&gt;
                    &lt;testSource&gt;
                        &lt;directory&gt;${project.basedir}/src/test/java&lt;/directory&gt;
                        &lt;includes&gt;
                            &lt;include&gt;**/*.groovy&lt;/include&gt;
                        &lt;/includes&gt;
                    &lt;/testSource&gt;
                &lt;/testSources&gt;
            &lt;/configuration&gt;
        &lt;/plugin&gt;
</code></pre>

<p><strong>NOTE:</strong> I am not getting any errors and getting Build Success after maven build</p>

<p><strong>I am not Sure Why it is not considering <code>groovy</code>files for Unit-Testing</strong></p>
",https://stackoverflow.com/questions/59136656/unable-to-execute-groovy-test-files-in-springboot-application,"['spring-boot', 'maven', 'groovy', 'spock', 'spring-boot-test']",1403,True,2,1
macOS Catalina + Xcode 11 Error on reading file from project,"<p>After upgrading to macOS Catalina with latest Xcode 11, I am not able to read files directly from user path when doing unit testing, example: 
<code>PROJECT_DIR + ""/FolderX/myFile.json""</code>,
I keep getting error <code>Thread 1: EXC_BAD_ACCESS (code=1, address=0x8)</code></p>

<p>This is also happened when I am trying to open a couchbase lite database with custom path.
Error:
<code>error opening!: 14</code>
<code>Cannot open database, Error : Error Domain=SQLite Code=14 ""unable to open database file"" UserInfo={NSLocalizedDescription=unable to open database file}</code></p>

<p>I believe this is an issue due to the read write access between my simulator and the latest Catalina.</p>

<p>My current <strong>workaround</strong> is to <strong>add my files and database to target membership and read the files directly from <code>[NSBundle bundleForClass:[self class]].bundlePath</code></strong>.
Is there any better fix to this? Like tweaking any setting to allow it to read files from custom path like in older versions?</p>
",https://stackoverflow.com/questions/58372823/macos-catalina-xcode-11-error-on-reading-file-from-project,"['directory', 'project', 'exc-bad-access', 'xcode11', 'macos-catalina']",2668,True,2,3
Unit testing private variables in Swift,"<p>I have a hard time to grasp how to implement unit tests in a class where all my fields are private.</p>

<p>The class is calculating a user's position with BLE and CoreLocation - not that important. I have a protocol, which when a new location is found I'm calling it and all the classes which conform to that protocol will receive a room id and room name. So, what that means is that literally all the fields in my class are private, because yeah, there's no reason any outside class should access them right? But that also means I can literally test nothing in that class, even though there are quite a few functions which I would like to test. I mean, I could just make the variables internal instead of private, but it just seems wrong to do that just to unit test. I've heard about dependency injection, but it just seems like so much effort.</p>

<p>For example I have this function:</p>

<pre><code>
private var beacons: [AppBeacon] = []
private var serverBeacons:[Beacon] = []

private func addBeacons(serverBeacons: [Beacon]){
        for beacon in serverBeacons {
            let beacon = AppBeacon(id: beacon.id, uuid: beacon.uuid, building: beacon.building, name: beacon.name)
            beacons.append(beacon)
       }
   }
</code></pre>

<p>there's no way I can test whether the beacons array was actually filled up as I wanted to or not for example. The public features of my class are basically a function called startLocating and the result which is the room id and name and I know in black box testing which unit testing imitates (right?) I should not care about the intermediate steps, but honestly, with this much functionality should I just say, doesn't matter? And assume i did populate the beacons with some rssi values of my choice, the actual location algorithm is executed on a node.js server, so I honestly don't know what to test client side? </p>

<p>It's classic MVC and there's no way I can change it architecture until the deadline that I have, so I don't know what's the best way to go from here? Just don't test the functionalities? Make the fields internal instead of private? We do testing of the algorithm itself server side, so testing whether the the room id is the expected room id, is already tested.</p>

<p>I read on another post the following:</p>

<p><em>""Unit testing by definition is black box testing, which means you don't care about the internals of the unit you test. You are mainly interested to see what's the unit output based on the inputs you give it in the unit test.
Now, by outputs we can assert on several things:</em></p>

<ul>
<li>the result of a method</li>
<li>the state of the object after acting on it,</li>
<li>the interaction with the dependencies the object has</li>
</ul>

<p><em>In all cases, we are interested only about the public interface, since that's the one that communicates with the rest of the world.
Private stuff don't need to have unit tests simply because any private item is indirectly used by a public one. The trick is to write enough tests that exercise the public members so that the private ones are fully covered.</em></p>

<p><em>Also, one important thing to keep in mind is that unit testing should validate the unit specifications, and not it's implementation. Validating implementation details adds a tight coupling between the unit testing code and the tested code, which has a big disadvantage: if the tested implementation detail changes, then it's likely that the unit test will need to be changed also, and this decreases the benefit having unit test for that piece of code.""</em></p>

<p>And from that I essentially understand it as that I should just not unit test this?</p>
",https://stackoverflow.com/questions/56058681/unit-testing-private-variables-in-swift,"['ios', 'swift', 'unit-testing', 'private']",1397,True,3,2
Why is this byte to struct de-serialization unit test failing?,"<p>I have this simple struct:</p>

<pre class=""lang-cs prettyprint-override""><code>[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)]
public struct TestStruct
{
    public bool Valid;     // 1
    public UInt64 Value1;  // 8 
    public UInt64 Value2;  // 8
    public float Value3;   // 4
}
</code></pre>

<p>and this generic from byte array to struct method:</p>

<pre class=""lang-cs prettyprint-override""><code>public static T ByteArrayToStructure&lt;T&gt;(byte[] bytes) where T : struct
{
    var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    try 
    {
        return (T) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    }
    finally 
    {
        handle.Free();
    }
}
</code></pre>

<p>and this simple unit test:</p>

<pre class=""lang-cs prettyprint-override""><code>[Test]
public void BytesToMyStruct()
{
    const bool Valid = true;
    const UInt64 Value1 = 1;
    const UInt64 Value2 = 2;
    const UInt64 Value3 = 99;

    var validBytes = BitConverter.GetBytes(Valid);
    var value1Bytes = BitConverter.GetBytes(Value1);
    var value2Bytes = BitConverter.GetBytes(Value2);
    var value3Bytes = BitConverter.GetBytes(Value3);  

    // 1 + 8 + 8 + 4 = 21
    var testBytes = new byte[21];

    Array.Copy(validBytes, 0, testBytes, 0, 1);
    Array.Copy(value1Bytes, 0, testBytes, 1, 8);
    Array.Copy(value2Bytes, 0, testBytes, 9, 8);
    Array.Copy(value3Bytes, 0, testBytes, 17, 4);

    var myStruct = ByteUtils.ByteArrayToStructure&lt;TestStruct&gt;(testBytes);

    Assert.That(myStruct.Valid, Is.EqualTo(true));
    Assert.That(myStruct.Value1, Is.EqualTo(1));
    Assert.That(myStruct.Value2, Is.EqualTo(2));
    Assert.That(myStruct.Value3, Is.EqualTo(99));
}
</code></pre>

<p>In this unit test I simply wish to manually populate a byte array, deserialize to a struct, and ensure the properties of the struct equal those which were set in the byte array. I assume my approach of manually copying to the same byte array via <code>Array.Copy</code> repeatedly is failing due to the fact that when I execute my unit test, I receive a failure stating that <code>Value1</code> is not being set correctly:</p>

<pre><code>Expected: 1
But was:  0
</code></pre>

<p>I am not sure if I am setting my byte arrays correctly by manually setting them for unit testing purposes.</p>
",https://stackoverflow.com/questions/58808933/why-is-this-byte-to-struct-de-serialization-unit-test-failing,"['c#', 'arrays', 'unit-testing', 'struct']",72,True,2,1
Do i have to moq Database and input Setup for PostgreSQL testing?,"<p>I have try to test PostgreSQL [Does PostgreSQL work properly ?]. I have read a little bit about Moq when we have to do unit testing. So I have 3 questions. </p>

<p>1 When we do Arrange [AAA pattern] Do we have to moq configuration database and input before testing SQL execution?</p>

<p>2 Based on first question. If it required for moq then What is different if i just set up normally like this</p>

<pre><code>            DumpDatabase databaseSetting = new DumpDatabase();
            databaseSetting.Host = ""***.***.*.*.*"";
            databaseSetting.Port = ""****"";
            databaseSetting.Database = ""*****"";
            databaseSetting.UserName = ""****"";
            databaseSetting.Password = **********"";
</code></pre>

<p>instead of</p>

<pre><code>   var mockdb = new Mock&lt;DumpDatabase&gt;();
            mockdb.Setup(x =&gt; x.dumpDatabase).Returns(
                new DumpDatabase()
                {
                    Host = ""***.***.*.*.*"",
                    Port = ""****"",
                    Database = ""*******"",
                    UserName = ""*****"",
                    Password = ""***********""
                }
                );

</code></pre>

<p>3 If Query has been passed, i have to roll back original in every single test  right ?</p>

<p>For example </p>

<pre><code>
  string query = ""INSERT INTO pictures (id, created, width, height, device_id, user_id, modified, checksum, file_path, file_extension, file_size, mime_type, thumbnail, title, classification, description)"" +
                                                                 "" VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12::mime, @p13, @p14, @p15::classification, @p16); "";

</code></pre>

<p>then i need to roll back original After Assert [AAA pattern]  by doing this</p>

<pre><code>string sqlDelete = ""DELETE FROM public.pictures WHERE id = @p1;"";

</code></pre>
",https://stackoverflow.com/questions/55791501/do-i-have-to-moq-database-and-input-setup-for-postgresql-testing,"['c#', 'postgresql', 'nunit', 'moq']",323,False,1,0
Python Dataclasses: FrozenInstanceError a subclass of AttributeError?,"<p>I'm doing some self-learning on the new python dataclasses.</p>

<p>One of the parameters that can be passed to the dataclass decorator is frozen=True, to make the object immutable.</p>

<p>The documentation (and experience) indicates that a:</p>

<pre><code>dataclasses.FrozenInstanceError
</code></pre>

<p>exception will be raised.</p>

<p>When unit testing though (with pytest) the following test passes:</p>

<pre><code>def test_change_page_url_values_raises_error(self, PAGE_URL):
    page_url = PageURL(PAGE_URL)
    with pytest.raises(AttributeError) as error:
        page_url.value = PAGE_URL
</code></pre>

<p>where PageURL is a dataclass with the frozen=True parameter.</p>

<p>Any ideas why why pytest indicates that this action (assigning a value to page_url.value) raises an Attribute Error? Does FrozenInstanceError inherit from AttributeError?</p>

<p>Note: If I change the unit test to test for a different exception (ie. TypeError), the test fails as expected.</p>
",https://stackoverflow.com/questions/56362040/python-dataclasses-frozeninstanceerror-a-subclass-of-attributeerror,"['python', 'pytest', 'python-dataclasses']",2875,True,1,1
How to access a specific reducer in react-testing-library,"<p>I've been trying to implement unit testing with react using the react-testing-library</p>

<p>I want to test my login component that use <strong>useSelector</strong> and <strong>useDispatch</strong> hooks from react-redux</p>

<p>The problem is that when I use this function to pass the store to in my login.test.js is not recognizing the reducer and show me this error:</p>

<pre><code> An error occurred while selecting the store state: Cannot read property 'isLoading' of undefined.

 const isLoadingAuth = useSelector(state =&gt; state.Auth.isLoading);

</code></pre>

<p>I use combineReducers in my store (the app has a lot of reducers) in order to access in that specific reducer ""Auth"" but I don't know how to use them in my login.test.js </p>

<p>How can I access to my Auth reducer in my login.test.js file?</p>

<p>This is my login.jsx </p>

<pre><code>const LoginForm = () =&gt; {
  const [values, setValues] = useState({ email: """", password: """" });
  const dispatch = useDispatch();

  function handleChange(e) {
    const { name, value } = e.target;
    setValues({ ...values, [name]: value });
  }

  function submitData(e) {
    e.preventDefault();
    dispatch(actions.AuthUser(values));
  }

  const isLoadingAuth = useSelector(state =&gt; state.Auth.isLoading);
  const error = useSelector(state =&gt; state.Auth.err);
  const isAuthSucess = useSelector(state =&gt; state.Auth.isAuthSuccess);

  if (isAuthSuccess) {
    &lt;Redirect to=""/dashboard"" /&gt;;
  }

  return (
    &lt;&gt;
      &lt;div&gt;
        &lt;form onSubmit={submitData}&gt;
          &lt;Input
            label=""Email""
            name=""email""
            value={values.email}
            change={handleChange}
          /&gt;
          &lt;Input
            label=""Password""
            name=""password""
            type=""password""
            value={values.password}
            change={handleChange}
          /&gt;
          &lt;div&gt;
            &lt;button&gt;Entrar&lt;/button&gt;
          &lt;/div&gt;
        &lt;/form&gt;
      &lt;/div&gt;
    &lt;/&gt;
  );
};
</code></pre>

<p>My AuthReducer.js</p>

<pre><code>import * as actionTypes from ""../actions/Auth/types"";
import { updateObject } from ""../store/utility"";

export const initalState = {
  authData: null,
  isLoading: false,
  isAuthSuccess: null,
  err: null
};

const authStart = state =&gt; {
  return updateObject(state, {
    isLoading: true,
    err: null
  });
};

const authFail = (state, action) =&gt; {
  return updateObject(state, {
    isLoading: false,
    err: action.err
  });
};

const auth = (state, action) =&gt; {
  return updateObject(state, {
    isLoading: false,
    authData: action.authData,
    isAuthSuccess: true
  });
};

export function reducer(state = initalState, action) {
  switch (action.type) {
    case actionTypes.START_AUTH_REQ: {
      return authStart(state, action);
    }
    case actionTypes.FAIL_AUTH_REQ: {
      return authFail(state, action);
    }
    case actionTypes.AUTH: {
      return auth(state, action);
    }
    default:
      return state;
  }
}

export default reducer;

</code></pre>

<p>And my Login.test.js</p>

<pre><code>import React from ""react"";
import { createStore, combineReducers } from ""redux"";
import { Provider } from ""react-redux"";
import { render, cleanup, fireEvent } from ""@testing-library/react"";
import rootReducer from ""../../../../reducers"";
import ""@testing-library/jest-dom/extend-expect"";
import LoginForm from ""./Form"";


function renderWithRedux(
  ui,
  {
    initialState,
    store = createStore(combineReducers(rootReducer, initialState))
  } = {}
) {
  return {
    ...render(&lt;Provider store={store}&gt;{ui}&lt;/Provider&gt;),
    // adding `store` to the returned utilities to allow us
    // to reference it in our tests (just try to avoid using
    // this to test implementation details).
    store
  };
}

test(""can render with redux with custom initial state"", () =&gt; {
  const { getByTestId, getByText } = renderWithRedux(&lt;LoginForm /&gt;, {
    initialState: { isLoading: false }
  });
});

</code></pre>
",https://stackoverflow.com/questions/57894300/how-to-access-a-specific-reducer-in-react-testing-library,"['reactjs', 'unit-testing', 'redux', 'react-testing-library']",3579,False,1,2
React app Jest unit test failing with Microsoft application insights react plugin,"<p>I'm trying to use the Microsoft's Application Insights JavaScript SDK React Plugin in my React application, and although it's working successfully, I'm having trouble getting my Jest and Enzyme unit test to pass with it.</p>

<p>I've set up my unit test like the following:</p>

<pre><code>import React from 'react';
import {act} from 'react-dom/test-utils';
import ReactDOM from 'react-dom';
import App from '../App.view';

jest.mock('@microsoft/applicationinsights-react-js', () =&gt; ({
  ReactPlugin: Object,
}));

jest.mock('@microsoft/applicationinsights-web', () =&gt; ({
  ApplicationInsights: Object,
  loadAppInsights: () =&gt; ({}),
}));

describe('App View', () =&gt; {
  it('renders without crashing', () =&gt; {
    const div = document.createElement('div');
    act(() =&gt; {
      ReactDOM.render(&lt;App /&gt;, div);
    });
    ReactDOM.unmountComponentAtNode(div);
  });
});
</code></pre>

<p>With my application insights service as:</p>

<pre><code>import {ApplicationInsights} from '@microsoft/applicationinsights-web';
import {ReactPlugin, withAITracking} from '@microsoft/applicationinsights-react-js';
import {createBrowserHistory} from 'history';

// Set up AppInsights connection
const browserHistory = createBrowserHistory({basename: ''});
const reactPlugin = new ReactPlugin();
const ai = new ApplicationInsights({
  config: {
    instrumentationKey:
      process.env.REACT_APP_APPINSIGHTS_KEY || 'xxxxxxxxxxx-xxxxxxxxxx-xxxxxxx-xxxxx',
    extensions: [reactPlugin],
    extensionConfig: {
      [reactPlugin.identifier]: {history: browserHistory},
    },
  },
});
ai.loadAppInsights();

export default Component =&gt; withAITracking(reactPlugin, Component);
export const appInsights = ai.appInsights;
</code></pre>

<p>When I run my tests, I keep getting the error, <code>TypeError: ai.loadAppInsights is not a function</code></p>

<p>Since I'm using jest mocking for the application insights modules, I've tried to mock this method as well in several ways, but with no luck. Any ideas on what I'm missing here? I'm also unable to find any good documentation on how to properly integrate application insights into a React application, which includes proper unit testing.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/58902848/react-app-jest-unit-test-failing-with-microsoft-application-insights-react-plugi,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'azure-application-insights']",1646,False,6,0
Vueify and Babel 7,"<p>I am using Gulp, Browserify, Vueify and Babel to build my vue.js project.
I cannot move to another building system, so Gulp it is.
I recently updated from Babel 6 to Babel 7, due to a new addition in my project : Jest and unit testing (Babel 7 is a requirement)</p>

<p>Unfortunately, this had as a side effect Vueify to stop working with Babel 7, because it seems they are not compatible, or something. <a href=""https://www.npmjs.com/package/vueify"" rel=""nofollow noreferrer"">Npm Vueify package</a> has not been updated for 2 years and I found a <a href=""https://github.com/vuejs/vueify/issues/237"" rel=""nofollow noreferrer"">git issue</a> that no-one has commented officially.</p>

<p>Has anyone faced and resolved the same issue? Any alternatives to Vueify?
Thanks</p>
",https://stackoverflow.com/questions/54985405/vueify-and-babel-7,"['vue.js', 'gulp', 'babeljs', 'vueify']",208,False,1,1
Angular Unit Testing: Is this code worth unit testing?,"<p>I have just began unit testing in angular. I am having a hard time figuring out what should be covered in unit tests in the application. Should I be testing the below code? </p>

<p>If I do I will be essentially be passing a valid value of <code>mode</code> and checking if correct values for various properties of <code>defaultProperties</code> were emitted by <code>this.propertiesSource</code>. Isn't it like writing the same code all over again and more? And this is just one example, application is full of such instances. </p>

<p>If I don't test such things then probably my code coverage will be negligible. </p>

<p>Here is an example of code from component:</p>

<pre><code> mode: string;
  defaultProperties = {
    editable: this.editable,
    showToolbar: this.showToolbar,
    viewMode: this.viewMode,
    editMode: this.editMode,
    showPopup: this.showPopup,
    formSavedClicked: this.formSavedClicked,
    cancelClicked: this.cancelClicked,
    refresh: this.refresh,
  };
  private propertiesSource = new BehaviorSubject(this.defaultProperties);
</code></pre>

<p><strong>Method to be tested:</strong></p>

<pre><code> setGridMode(mode) {
    this.mode = mode;
    if (mode === ""edit"") {
      this.propertiesSource.next({
        editable: true,
        showToolbar: true,
        viewMode: false,
        editMode: true,
        showPopup: false,
        formSavedClicked: this.formSavedClicked,
        cancelClicked: this.cancelClicked,
        refresh: false,

      });
    } else if (mode == ""save"") {
      this.propertiesSource.next({
        editable: false,
        showToolbar: false,
        viewMode: true,
        editMode: false,
        showPopup: false,
        formSavedClicked: this.formSavedClicked,
        cancelClicked: this.cancelClicked,
        refresh: true,
      })
      // more code..multiple if else block like above
    }  
   }
</code></pre>
",https://stackoverflow.com/questions/56681338/angular-unit-testing-is-this-code-worth-unit-testing,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",516,False,1,2
Is there a way to properly mock Reselect selectors for unit testing?,"<p>I'm having a pretty complex selectors structure in my project (some selectors may have up to 5 levels of nesting) so some of them are very hard to test with passing input state and I would like to mock input selectors instead. However I found that this is not really possible.</p>

<p>Here is the most simple example:</p>

<pre><code>// selectors1.js
export const baseSelector = createSelector(...);
</code></pre>

<p>-</p>

<pre><code>// selectors2.js
export const targetSelector = createSelector([selectors1.baseSelector], () =&gt; {...});
</code></pre>

<p>What I would like to have in my test suite:</p>

<pre><code>beforeEach(() =&gt; {
  jest.spyOn(selectors1, 'baseSelector').mockReturnValue('some value');
});

test('My test', () =&gt; {
  expect(selectors2.targetSelector()).toEqual('some value');
});
</code></pre>

<p>But, this approach won't work as <code>targetSelector</code> is getting reference to <code>selectors1.baseSelector</code> during initialization of <code>selectors2.js</code> and mock is assigned to <code>selectors1.baseSelector</code> after it.</p>

<p>There are 2 working solutions I see now:</p>

<ol>
<li>Mock entire <code>selectors1.js</code> module with <code>jest.mock</code>, however, it won't work if I'll need to change <code>selectors1.baseSelector</code> output for some specific cases</li>
<li>Wrap every dependency selectors like this:</li>
</ol>

<hr>

<pre><code>export const targetSelector = createSelector([(state) =&gt; selectors1.baseSelector(state)], () =&gt; {...});
</code></pre>

<p>But I don't like this approach a lot for obvious reasons.</p>

<p>So, the question is next: is there any chance to mock Reselect selectors properly for unit testing?</p>
",https://stackoverflow.com/questions/55696552/is-there-a-way-to-properly-mock-reselect-selectors-for-unit-testing,"['javascript', 'unit-testing', 'jestjs', 'reselect']",20154,True,25,4
Mock DbQuery to use FromSql from unit tests,"<p>I am using EF Core in a projet to get stored procedure calling. In my context i have the following :</p>

<pre><code>public class MyContext : DbContext
{
    public DbQuery&lt;User&gt; UserQuery { get; set; }

    public MyContext(DbContextOptions&lt;MyContext&gt; options) : base(options) { }
}
</code></pre>

<p>And i call the stored procedure like this :</p>

<pre><code>public virtual async Task&lt;User&gt; GetUserAsync(string name)
{
    return await MyContext.Query&lt;User&gt;()
        .FromSql($""EXEC [dbo].[GetUser], @Login = {name}"")
        .FirstOrDefaultAsync();
}
</code></pre>

<p>Code is working fine. I need to test this method in unit tests, i'm using InMemoryDatabase to mock my context MyContext like this :</p>

<pre><code>[Fact]
public async Task GetUserAsync_should_return_first_user_with_login_and_password_if_exists()
{
    // Arrange
    var users = new List&lt;User&gt;
    {
        new User()
        {
            Login = ""test@outlook.fr"",
            Password = ""pass1"",
        },
    };

    var options = new DbContextOptionsBuilder&lt;MyContext&gt;()
        .UseInMemoryDatabase(databaseName: ""BddName"")
        .Options;
    var context = new MyContext(options);
    var loginProvider = A.Fake&lt;LoginProvider&gt;(opts =&gt; opts.WithArgumentsForConstructor(() =&gt; new LoginProvider(context)));


    // Act

    // Assert
    context.Dispose();
}
</code></pre>

<p>And i have no idea how can i set my list into the result of the stored procedure called from DbQuery. I tried to follow this article : <a href=""https://nodogmablog.bryanhogan.net/2017/11/unit-testing-entity-framework-core-stored-procedures/"" rel=""nofollow noreferrer"">https://nodogmablog.bryanhogan.net/2017/11/unit-testing-entity-framework-core-stored-procedures/</a> but it works for DbSet only and not DbQuery.
I need some advices for this case.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/56931254/mock-dbquery-to-use-fromsql-from-unit-tests,"['unit-testing', 'entity-framework-core']",1751,False,1,1
Can&#39;t unit test a working file upload with node/express,"<p>I am trying to unit test a node/express upload file.This is my first piece of work tying node.I could get the job done in the frontend but hen I had to test it,it went downhill... The file gets uploaded on both frontend and when unit testing but I get an error of <code>res.json is not a function</code>mostly because I change the CVS to a JSON file in writeFile.</p>

<p>I tried to change the unit test a fair amount of time but I think I am stuck.I've changed the file parameter the attach parameter etc...</p>

<p>test.js</p>

<pre><code>var request = require(""supertest"");
const app = require('../routes/file');

describe('/upload file', () =&gt; {
    it('Should upload a file', (done) =&gt; {
        request(app).post('/upload',function(err,res){
            console.log('asdasdasd');
            done();
        })
         .set('Content-Type', 'multipart/form-data')
         .set('Accept', 'application/json')
         .attach('file', ""testdata.csv"")
         .end(function(){

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

<p>file.js</p>

<pre><code>router.post('/upload',function(req, res) {
  upload(req, res, function (err) {
    let filePath = req.file.path;
    let fileExtension = path.extname(filePath);

      if (err instanceof multer.MulterError || fileExtension !== '.csv') {
          return res.status(500).json(err);
      } else if (err || fileExtension !== '.csv') {
          return res.status(500).json(err);
      }

    CSVToJSON({
        headers: ['id', 'name', 'age', 'address', 'team'],
        noheader: true,
      }).fromFile(filePath).then(source =&gt; {
        helpers.writeFile('data',filePath,source,res);
        });
    });
});
</code></pre>

<p>helpers.js</p>

<pre><code>writeFile(fileName,filePath,source,res){
    if (fs.existsSync(filePath)) {
    fs.writeFile(`../public/files/${fileName}.json`,JSON.stringify(source),'utf-8',function (err) {
         if (err) {
           return res.json({""error"" : true, ""message"" : err,'status':500});
         } else {
        return res.json({""error"" : false, ""message"" : ""File Uploaded Successfuly"",'status':200});
         }
    });
   }
}
</code></pre>

<p>I expected a status of 200 and res.json to be defined.</p>
",https://stackoverflow.com/questions/57865378/cant-unit-test-a-working-file-upload-with-node-express,"['node.js', 'unit-testing', 'mocha.js', 'chai', 'supertest']",331,False,1,0
Get the &quot;process cannot access the file because it is being used by another process.&quot; error when unit testing uploade file laravel,"<p>Laravel Version: 5.5</p>

<p>PHP Version: 7.1</p>

<p>Database Driver: mysql</p>

<p>Im currently having a problem with unit testing, basically the problem is in the move() function inside my controller, when that function is running the program say the file is being used my another program. and throw this exception </p>

<blockquote>
  <p>Could not move the file ""C:\Users\JUAN ANTONIO\AppData\Local\Temp\phpED45.tmp"" to ""uploads/partners\15517582682740.jpg"" (rename(C:\Users\JUAN ANTONIO\AppData\Local\Temp\phpED45.tmp,uploads/partners\15517582682740.jpg): The process cannot access the file because it is being used by another process. (code: 32))""</p>
</blockquote>

<p>here are the snippet of my code:</p>

<p><strong>PartnerTest.php->testStorePartner()</strong></p>

<pre><code> /** @test */
public function testStorePartner(){
    Storage::fake('local');
    //1. Create Data
    $data = [
        'name' =&gt; 'test',
        'file' =&gt; UploadedFile::fake()-&gt;image('avatar.jpg')
    ];
    //2. Store Data
    $response = $this-&gt;actingAs($this-&gt;user)-&gt;json('POST', route('PartnersStore'), $data);
    //3. Data Stored In Database
    $this-&gt;assertDatabaseHas('partners', ['name' =&gt; 'test',]);
    //4. Test response status 302 -&gt; redirect
    $response-&gt;assertStatus(302);
}
</code></pre>

<p><strong>PartnerController->store(Request $request)</strong></p>

<pre><code>public function store(Request $request)
{
    $this-&gt;validate($request, [
        'file' =&gt; 'mimes:png,jpeg,jpg,gif|max:3000'
    ]);

    // Start of Upload Files
    $formFileName = ""file"";
    $fileName = """";
    if ($request-&gt;$formFileName != """") {
        $fileName = time() . rand(1111,
                9999) . '.' . $request-&gt;file($formFileName)-&gt;getClientOriginalExtension();
        $path = $this-&gt;getUploadPath();
        $request-&gt;file($formFileName)-&gt;move($path, $fileName);
    }
    // End of Upload Files

    $Partner = new Partner;
    $Partner-&gt;name = $request-&gt;name;
    $Partner-&gt;file = $fileName;
    $Partner-&gt;status = 1;
    $Partner-&gt;created_by = Auth::user()-&gt;id;
    $Partner-&gt;save();

    return redirect('/admin/partners')-&gt;with('doneMessage', trans('backLang.addDone'));
}
</code></pre>

<p><strong>filesystem.php</strong></p>

<pre><code>'disks' =&gt; [

    'local' =&gt; [
        'driver' =&gt; 'local',
        'root' =&gt; storage_path('app'),
    ],

    'public' =&gt; [
        'driver' =&gt; 'local',
        'root' =&gt; storage_path('app/public'),
        'url' =&gt; env('APP_URL').'/storage',
        'visibility' =&gt; 'public',
    ],

    's3' =&gt; [
        'driver' =&gt; 's3',
        'key' =&gt; env('AWS_KEY'),
        'secret' =&gt; env('AWS_SECRET'),
        'region' =&gt; env('AWS_REGION'),
        'bucket' =&gt; env('AWS_BUCKET'),
    ],

],
</code></pre>
",https://stackoverflow.com/questions/54995282/get-the-process-cannot-access-the-file-because-it-is-being-used-by-another-proc,"['php', 'laravel', 'unit-testing', 'upload', 'storage']",685,False,1,0
How to await for the stream event to get processed in the unit-test?,"<p>The unit-test implies that after some item was passed to a <code>Sink</code> object through the <code>add</code> method, than some operation will be performed in response to it.</p>

<pre><code>class Subject {
  final StreamController&lt;Item&gt; _itemStreamController = StreamController();
  Sink&lt;Item&gt; get itemsSink =&gt; _itemStreamController.sink;
  Stream&lt;Item&gt; get _itemsStream =&gt; _itemStreamController.sink;
  final SomeService _service;

  Subject(this._service) {
    _itemsStream.listen((item) =&gt; _service.processItem(item));
  }
}
</code></pre>

<p>And the unit test itself:</p>

<pre><code>test('description', () async {
  final Item givenItem = Item(""givenValue"");
  final SomeService givenService = MockSomeService();
  final Subject subject = Subject(givenService);
  subject.itemsSink.add(givenItem);
  verify(givenService.add(givenItem));
});
</code></pre>

<p>And as you can understand the event looping thread firstly processes <code>verify</code> instructions and only then dispatches the event to the listener. </p>

<p>If I just insert <code>await Future.value(null);</code> between sink interaction and method invocation verification than all works like a charm. Still, this solution is quite ugly.</p>

<p>Does the unit-testing framework itself offer something to schedule verification at the end of event loop? Or any measures to get this unit-test passed without resorting to something like <code>await Future.value(null);</code>?</p>
",https://stackoverflow.com/questions/56270946/how-to-await-for-the-stream-event-to-get-processed-in-the-unit-test,"['unit-testing', 'dart', 'stream']",48,False,1,0
How to patch requests.get from a different file in python,"<p>I have 2 python files: 1 for unit testing (tests.py) and 1 for the script I want to test (main.py):</p>

<pre><code># In main.py:

import requests

def get_response(url):
    response = requests.get(url);
    # Do stuff...
    return response
</code></pre>

<p>-</p>

<pre><code># In tests.py

from unittest import mock
from unittest.mock import patch
from my_project.main import get_response

def some_handler(url):
    return ""test_response""

class GetResponseTestCase(unittest.TestCase):

    def setUp(self):

        # setup mocks
        patch('requests.get', mock.Mock(side_effect=some_handler)

    def run_test(self):

        result = get_response(""test_response"")
</code></pre>

<p>I want to patch <code>requests.get</code> to return <code>test_response</code> but the patching is not working because it tries to send a request/make a connection to the url supplied. I think the patch name <code>requests.get</code> is not targeting the place it is being used in main.py (as it is referring to where it is defined instead) as some people have mentioned online. But in this scenario I am not sure how to fix this.</p>

<p>If <code>import requests</code> is being used in main.py then how can I patch it from another file? Thanks.</p>
",https://stackoverflow.com/questions/55394496/how-to-patch-requests-get-from-a-different-file-in-python,"['python', 'unit-testing', 'mocking', 'patch']",1524,True,1,2
Why is my unit test failing for a switch statement?,"<p>Hi I am trying to unit test the following and check that this switch/case statement works:</p>

<p><code>DiagnosticsComponentFactory</code> class</p>

<pre><code>private readonly IServiceProvider _serviceCollection;

public IComponent Create (string name)
{
    switch (name)
    {
        case BoardItemComponent.TypeName:
            return _serviceCollection.GetService&lt;BoardItemComponent&gt;();
        default:
            throw new NotSupportedException();
    }
}
</code></pre>

<p>My <code>BoardItemComponent</code> class:</p>

<pre><code>public class BoardItemComponent
{
    public const string TypeName = ""name"";

    public BoardItemComponent(IConfigurationRepository configurationRepository) : base(configurationRepository)
    {

    }
}
</code></pre>

<p><code>BoardItemComponent</code> is derived from <code>IComponent</code>, and it's added like follows in my <em>Startup.cs</em> file: </p>

<pre><code>services.AddScoped&lt;IComponent, BoardItemComponent&gt;();
</code></pre>

<p>my unit test:</p>

<pre><code>[Test]
public void GetComponent_GivenComponentFactory_ExpectBoardComponent()
{
    var serviceCollection = new ServiceCollection();
    ComponentFactoryRegistration.Register(serviceCollection);
    var factory = new DiagnosticsComponentFactory(serviceCollection.BuildServiceProvider());
    var component = factory.Create(""name"");
    Assert.IsNotNull(component);
}
</code></pre>

<p>When I debug my unit test, <code>component</code> is <em>null</em>, despite it following all the correct steps. It goes into the switch case statement correctly and recognizes that is the correct case, however it still returns <em>null</em>. </p>

<p>From what I have shared (and apologies, as I know that the names in these code snippets are vague without context), is there any obvious reason that my unit test fails? I'm new when it comes to unit testing in C#.</p>
",https://stackoverflow.com/questions/59073228/why-is-my-unit-test-failing-for-a-switch-statement,"['c#', '.net', 'unit-testing', 'dependency-injection', 'nunit']",330,True,1,1
how to mock constructor in sub third party attribute using jest,"<p>We have a simple express app. We use winston as third party to be able to handle logging properly.</p>

<pre><code>const express = require('express');
const app = express();
const { createLogger, transports } = require('winston');

const port = process.env.PORT || 5000;
const logger = createLogger({ transports: [ new transports.Console()] });

const { catchAll } = require('./routes/catchall');

app.get('*', catchAll);

app.listen(port, () =&gt; logger.log({ level: 'info', message: `server listening on port ${port}!` }));
</code></pre>

<p>We would like, in our unit testing, check that createLogger has been called with proper arguments.</p>

<p>We first tried just to use <code>jest.mock('winston)</code> but jest complains that <code>TypeError: transports.Console is not a constructor</code>.</p>

<p>We then tried to mock manually the package using:</p>

<pre><code>let { createLogger, transports } = require('winston');

const consoleClass = class Console{};
jest.doMock('winston', () =&gt; {
  return {
    createLogger: jest.fn(),
    transports: {
      Console: consoleClass
    }
  }
});

describe('logger', () =&gt; {
  it('should create proper logger', () =&gt; {
    expect(createLogger).lastCalledWith({ transports: [ new transports.Console()] })
  });
});
</code></pre>

<p>The error about Console is gone. But then our test fails with:</p>

<pre><code>logger › should create proper logger

expect(jest.fn())[.not].lastCalledWith()

jest.fn() value must be a mock function or spy.
Received:
  function: [Function anonymous]

  39 | describe('logger', () =&gt; {
  40 |   it('should create proper logger', () =&gt; {
&gt; 41 |     expect(createLogger).lastCalledWith({ transports: [ new transports.Console()] })
     |                          ^
  42 |   });
  43 | });
  44 |

  at Object.lastCalledWith (tests/app.spec.js:41:26)
</code></pre>

<p>We tried to add after <code>doMock</code></p>

<pre><code>createLogger.mockImplementation(() =&gt; {});
</code></pre>

<p>But it complained that <code>TypeError: createLogger.mockImplementation is not a function</code></p>

<p>How can we both replace transports attribute and createLogger?</p>

<p>We need to be able to mock implementation of <code>createLogger</code> to then be able in another test to assert that <code>app.listen</code> has been called with logger.log and proper parameters.</p>
",https://stackoverflow.com/questions/54309410/how-to-mock-constructor-in-sub-third-party-attribute-using-jest,"['javascript', 'node.js', 'jestjs', 'winston']",1094,True,1,1
How to enable debug in Semantic-UI-React?,"<p>I'm using Semantic-UI in my react project.
It works well. but sometimes it shows error in during unit testing with Jest.</p>

<p>This is the error message</p>

<pre><code>console.error node_modules/semantic-ui-react/dist/commonjs/lib/debug.js:25
      Semantic-UI-React could not enable debug.
    console.error node_modules/semantic-ui-react/dist/commonjs/lib/debug.js:26
      TypeError: Cannot read property 'debug' of undefined
          at Object.&lt;anonymous&gt; (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/semantic-ui-react/dist/commonjs/lib/debug.js:22:33)
          at Runtime._execModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:513:13)
          at Runtime.requireModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:329:14)
          at Runtime.requireModuleOrMock (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:405:19)
          at Object.&lt;anonymous&gt; (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/semantic-ui-react/dist/commonjs/lib/index.js:77:14)
          at Runtime._execModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:513:13)
          at Runtime.requireModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:329:14)
          at Runtime.requireModuleOrMock (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:405:19)
          at Object.&lt;anonymous&gt; (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/semantic-ui-react/dist/commonjs/addons/Responsive/Responsive.js:43:12)
          at Runtime._execModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:513:13)
          at Runtime.requireModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:329:14)
          at Runtime.requireModuleOrMock (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:405:19)
          at Object.&lt;anonymous&gt; (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/semantic-ui-react/dist/commonjs/addons/Responsive/index.js:8:19)
          at Runtime._execModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:513:13)
          at Runtime.requireModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:329:14)
          at Runtime.requireModuleOrMock (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:405:19)
          at Object.&lt;anonymous&gt; (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/semantic-ui-react/dist/commonjs/index.js:7:19)
          at Runtime._execModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:513:13)
          at Runtime.requireModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:329:14)
          at Runtime.requireModuleOrMock (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:405:19)
          at Object.&lt;anonymous&gt; (/home/ubuntu/work/node/suite/suite-cloud-app/client/src/FamilyViewWithController/index.js:4:24)
          at Runtime._execModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:513:13)
          at Runtime.requireModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:329:14)
          at Runtime.requireModuleOrMock (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:405:19)
          at Object.&lt;anonymous&gt; (/home/ubuntu/work/node/suite/suite-cloud-app/client/src/FamilyViewWithController/index.test.js:1:232)
          at Runtime._execModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:513:13)
          at Runtime.requireModule (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/node_modules/jest-runtime/build/index.js:329:14)
          at jasmine2 (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-jasmine2/build/index.js:97:11)
          at runTest (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/build/runTest.js:85:10)
          at module.exports (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/jest-cli/build/TestWorker.js:87:5)
          at handle (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/worker-farm/lib/child/index.js:44:8)
          at process.&lt;anonymous&gt; (/home/ubuntu/work/node/suite/suite-cloud-app/client/node_modules/worker-farm/lib/child/index.js:51:3)
          at emitTwo (events.js:126:13)
          at process.emit (events.js:214:7)
          at emit (internal/child_process.js:772:12)
          at _combinedTickCallback (internal/process/next_tick.js:141:11)
          at process._tickCallback (internal/process/next_tick.js:180:9)

</code></pre>

<p>It's very wierd.
- sometimes it appears, sometimes it doesn't
- sometimes it appears in a component, sometimes it doesn't appear in that component.
- it doesn't appear with small amount of components. but it appears with a lot of components.
- but the tests always are passed even if this issue appears.</p>

<p>The test command that I'm using is</p>

<pre><code>CI=true NODE_ENV=test react-scripts test --env=jsdom --no-cache
</code></pre>

<p>any thoughts about that? I do want your team to solve this issue or let me know how to fix it.</p>

<p>Regards.</p>
",https://stackoverflow.com/questions/55078556/how-to-enable-debug-in-semantic-ui-react,['semantic-ui-react'],179,False,1,1
Adding Atl support to console project in vs2017,"<p>I am new to VC++, MFC and ATL.
I am trying to add ATL support to a console project which I have created for unit testing using CppUnit.
There are few com interfaces I need to test, for which I need to add an ATL simple obj in my console test project.
Few things that I have tried are to create an idl file and manually created a .rgs file but I am unable to register the same to my registry, due to which the class id is returning null...
Please help me understand how to add an ATL support to my console project</p>

<p>Thanks in advance...</p>
",https://stackoverflow.com/questions/54566545/adding-atl-support-to-console-project-in-vs2017,['visual-c++'],91,False,1,0
Coroutine Unit Testing Fails for the Class,"<p>I am facing a weird issue while unit testing Coroutines. There are two tests on the class, when run individually, they both pass and when <em>I run the complete test class, one fails with assertion error</em>.
I am using <code>MainCoroutineRule</code> to use the <code>TestCoroutineScope</code> and relying on the latest Coroutine Testing Library
Here is the test :</p>

<pre><code>    @Test
    fun testHomeIsLoadedWithShowsAndFavorites() {
        runBlocking {
            // Stubbing network and repository calls
            whenever(tvMazeApi.getCurrentSchedule(""US"", currentDate))
                .thenReturn(getFakeEpisodeList())
            whenever(favoriteShowsRepository.allFavoriteShowIds())
                .thenReturn(arrayListOf(1, 2))
        }

        mainCoroutineRule.runBlockingTest {
            // call home viewmodel
            homeViewModel.onScreenCreated()
            // Check if loader is shown
            assertThat(LiveDataTestUtil.getValue(homeViewModel.getHomeViewState())).isEqualTo(Loading)
            // Observe on home view state live data
            val homeViewState = LiveDataTestUtil.getValue(homeViewModel.getHomeViewState())
            // Check for success data
            assertThat(homeViewState is Success).isTrue()
            val homeViewData = (homeViewState as Success).homeViewData
            assertThat(homeViewData.episodes).isNotEmpty()
            // compare the response with fake list
            assertThat(homeViewData.episodes).hasSize(getFakeEpisodeList().size)
            // compare the data and also order
            assertThat(homeViewData.episodes).containsExactlyElementsIn(getFakeEpisodeViewDataList(true)).inOrder()
        }
    }
</code></pre>

<p>The other test is almost similar which tests for Shows without favorites. I am trying to test <code>HomeViewModel</code> method as:</p>

<pre><code>        homeViewStateLiveData.value = Loading
        val coroutineExceptionHandler = CoroutineExceptionHandler { _, exception -&gt;
            onError(exception)
        }

        viewModelScope.launch(coroutineExceptionHandler) {
            // Get shows from network and favorites from room db on background thread
            val favoriteShowsWithFavorites = withContext(Dispatchers.IO) {
                val favoriteShowIds = favoriteShowsRepository.allFavoriteShowIds()
                val episodes = tvMazeApi.getCurrentSchedule(COUNTRY_US, currentDate)
                getShowsWithFavorites(episodes, favoriteShowIds)
            }
            // Return the combined result on main thread
            withContext(Dispatchers.Main) {
                onSuccess(favoriteShowsWithFavorites)
            }
        }
    }
</code></pre>

<p>I cannot find the actual cause of why the tests if run separately are passing and when the complete class is tested, one of them is failing. Pls help if I am missing something</p>
",https://stackoverflow.com/questions/57239510/coroutine-unit-testing-fails-for-the-class,"['android', 'unit-testing', 'kotlin-coroutines']",677,True,1,1
How to inject Input() in unit testing?,"<p>So i try to do some unit testing on a component. But I have some problems with Input() parameter. And then especially a component in the component</p>

<p>SO I have this component:</p>

<pre><code>
export class EcheqDisplayComponent implements OnInit {
  echeq: EcheqSubmissionApi;


  constructor(
    private route: ActivatedRoute
  ) {
    this.echeq = this.route.snapshot.data['submission'];
  }

  ngOnInit() {
  }

  getAnswers(page: EcheqPageApi): any[] {
    return page.elements.map(element =&gt; this.echeq.answers[element.name]);
  }
}

</code></pre>

<p>and the template:</p>

<pre><code>
&lt;div class=""echeq-display"" *ngIf=""echeq""&gt;
  &lt;header class=""echeq-display-header header""&gt;
    &lt;div class=""echeq-display-info""&gt;
      &lt;h1 class=""heading echeq-display-heading""&gt;
        {{ echeq.definition.title }}
      &lt;/h1&gt;
      &lt;div class=""sub-heading echeq-display-subheading""&gt;
        &lt;span class=""echeq-display-creator""&gt;
          Toegekend door:
          {{ echeq.assignedByProfName ? echeq.assignedByProfName : 'Het Systeem' }}
        &lt;/span&gt;
        &lt;span class=""echeq-display-date""&gt;{{
          echeq.definition.createdOnUtc | date: 'dd MMM'
        }}&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;app-meta-box
      [metadata]=""{
        numPages: echeq.definition.numPages,
        vPoints: echeq.definition.awardedVPoints
      }""
    &gt;&lt;/app-meta-box&gt;
  &lt;/header&gt;
  &lt;main class=""echeq-display-questions body""&gt;
    &lt;app-echeq-question
      *ngFor=""let page of echeq.definition.pages; let i = index""
      [page]=""page""
      [readonly]=""true""
      [number]=""i + 1""
      [answers]=""getAnswers(page)""
    &gt;&lt;/app-echeq-question&gt;
  &lt;/main&gt;
&lt;/div&gt;


</code></pre>

<p>and the unit test:</p>

<pre><code>
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { EcheqDisplayComponent } from './echeq-display.component';
import { ParticipantEcheqModule } from '../../participant-echeq.module';
import { RouterModule, ActivatedRoute } from '@angular/router';
import { MockActivatedRoute } from 'src/app/shared/mocks/MockActivatedRoute';
import { MetaData } from '../meta-box/meta-box.component';

describe('EcheqDisplayComponent', () =&gt; {
  let component: EcheqDisplayComponent;
  let fixture: ComponentFixture&lt;EcheqDisplayComponent&gt;;
  const metaData: MetaData = new MetaData();
  // const metaDataInfo = fixture.debugElement.componentInstance;


  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ ],
      providers: [
        { provide: ActivatedRoute, useClass: MockActivatedRoute }
      ],
      imports:[
        ParticipantEcheqModule

      ]
    })
    .compileComponents();
  }));

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

  fit('should create component', () =&gt; {
    metaData.numPages = 20;
    expect(component).toBeTruthy();
  });
});



</code></pre>

<p>But it stay saying: </p>

<p>TypeError: Cannot read property 'numPages' of undefined.</p>

<p>So what I have to change that it is working?</p>

<p>Thank you</p>

<p>So the MetaData is from the app-meta-box component.it looks like this:</p>

<pre><code>
export class MetaData {
  numPages: number;
  vPoints: number;
}

@Component({
  selector: 'app-meta-box',
  templateUrl: './meta-box.component.html',
  styleUrls: ['./meta-box.component.scss']
})
export class MetaBoxComponent implements OnInit {
  @Input() metadata: MetaData;

  constructor() {}

  ngOnInit() {}

}


</code></pre>

<p>This is the mock class:</p>

<pre><code>export class MockActivatedRoute {
  public snapshot = {
      data: {
         submission: {
           answers: {}
         }
      }
  };
}
</code></pre>

<p>I have it now like this:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { EcheqDisplayComponent } from './echeq-display.component';
import { ParticipantEcheqModule } from '../../participant-echeq.module';
import { RouterModule, ActivatedRoute } from '@angular/router';
import { MockActivatedRoute } from 'src/app/shared/mocks/MockActivatedRoute';
import { MetaData } from '../meta-box/meta-box.component';

describe('EcheqDisplayComponent', () =&gt; {
  let component: EcheqDisplayComponent;
  let fixture: ComponentFixture&lt;EcheqDisplayComponent&gt;;
  const metaData: MetaData = new MetaData();
  // const metaDataInfo = fixture.debugElement.componentInstance;


  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ ],
      providers: [
        { provide: ActivatedRoute, useValue: new MockActivatedRoute().withData({submission:{ answers:{} } }) }
      ],
      imports:[
        ParticipantEcheqModule
      ]
    })
    .compileComponents();
  }));

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

  fit('should create component', () =&gt; {
    component.echeq = {
      definition: {
        title: 'test title',
        awardedVPoints: 0,
        numPages: 9
      }
   }
    expect(component).toBeTruthy();
  });
});

But then I get this error:


</code></pre>

<pre><code>Property 'answers' is missing in type '{ definition: { title: string; awardedVPoints: number; numPages: number; }; }' but required in type 'EcheqSubmissionApi'.ts(2741)
echeqSubmissionApi.ts(59, 5): 'answers' is declared here.
</code></pre>

<p>I have it now like this:</p>

<pre><code>fit('should create component', () =&gt; {
    component.echeq = {
      definition: {
        title: 'test title',
        awardedVPoints: 0,
        numPages:9
      }
    } as EcheqSubmissionApi;
    expect(component).toBeTruthy();
  });
</code></pre>

<pre><code>export interface EcheqSubmissionApi { 
    /**
     * Primary key of this submission (server set).
     */
    id?: string;
    definition?: EcheqDefinitionApi;
    /**
     * Id of the prof who assigned this eCheq (server set).
     */
    assignedByProfId?: string;
    /**
     * Name of the prof who assigned this eCheq (server set). Only set on get operations. May be null if assigned by the system.
     */
    assignedByProfName?: string;
    /**
     * Id of the organisation who assigned this eCheq (server set).
     */
    assignedByOrgId?: number;
    /**
     * Participant ID of the patient this eCheq is assigned to (server set).
     */
    assignedToId?: string;
    /**
     * When this submission was assigned (UTC, server set).
     */
    assignedOnUtc?: Date;
    /**
     * If set until when the eCheq can be submitted.
     */
    validUntilUtc?: Date;
    /**
     * Whether the eCheq has been started and whether it has been submitted (server set).
     */
    status?: EcheqSubmissionApi.StatusEnum;
    /**
     * When this submission was completed (UTC, server set).
     */
    submittedOnUtc?: Date;
    /**
     * Answers of form.  In the form of a json object with name and value of the questions  {      \""nameOfQuestion\"" : \""valueOfQuestion\""  }
     */
    answers: object;
    /**
     * initialValues of form.  In the form of a json object with name and value of variables  {      \""nameOfQuestion\"" : \""valueOfQuestion\""  }
     */
    initialValues?: object;
    /**
     * The page the participant is currently on
     */
    currentPage?: number;
    /**
     * The progress of the echeq in percentage
     */
    progress?: number;
}
export namespace EcheqSubmissionApi {
    export type StatusEnum = 'New' | 'Active' | 'Submitted';
    export const StatusEnum = {
        New: 'New' as StatusEnum,
        Active: 'Active' as StatusEnum,
        Submitted: 'Submitted' as StatusEnum
    };
}

</code></pre>

<p>But if I run the unit test, I still get this error:</p>

<pre><code>TypeError: Cannot read property 'numPages' of undefined
</code></pre>
",https://stackoverflow.com/questions/58792678/how-to-inject-input-in-unit-testing,"['javascript', 'angular', 'karma-jasmine']",241,False,0,3
Error when testing Firestore online with Jest: &quot;Auth error:TypeError: fetch is not a function&quot;,"<p>I am trying to test Cloud Firestore with Jest, but have the following error.</p>
<pre class=""lang-js prettyprint-override""><code>const admin = require('firebase-admin');
const serviceAccount = require(&quot;../../../config/YOUR-PROJECT-NAME-firebase-adminsdk-XXXX-XXXXXX.json&quot;);

// const myfirestore: any = new MyFireStore()

describe('MyFirestore', () =&gt;{
  it('getDocument', async () =&gt; {
    
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: &quot;https://unittest-dfb64.firebaseio.com&quot;
    });

    let result = false
    const db = admin.firestore();
    const collectionRef = db.collection('test')
    const docRef = collectionRef.doc('testDoc')
    const getDoc = await docRef.get()
    if (getDoc &amp;&amp; getDoc.exists) {
      result = getDoc.data()
    }

    expect(result).toEqual('testdata')
  }, 100000)
</code></pre>
<p>&quot;Auth error:TypeError: fetch is not a function&quot;.</p>
<p><a href=""https://i.stack.imgur.com/XvdWr.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/XvdWr.png"" alt="""" /></a><br />
<sub>(source: <a href=""https://www.goodpic.com/app/uploads/2019/05/Screenshot-2019-05-25-at-00.01.01.png"" rel=""nofollow noreferrer"">goodpic.com</a>)</sub></p>
<p>I googled a lot but could not find any hint about this error.
What is the proper way to access to the Firestore data inside Jest test?
Thank you so much for your help in advance.</p>
<p>The full code is uploaded here.</p>
<p><a href=""https://github.com/goodpic/firebase-graphql-boilerplate"" rel=""nofollow noreferrer"">https://github.com/goodpic/firebase-graphql-boilerplate</a></p>
<p>I checked and tried these docs but could not figure out what is the root of this error.</p>
<p><a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing</a>
<a href=""https://github.com/firebase/functions-samples/blob/master/quickstarts/uppercase/functions/test/test.online.js"" rel=""nofollow noreferrer"">https://github.com/firebase/functions-samples/blob/master/quickstarts/uppercase/functions/test/test.online.js</a>
<a href=""https://gist.github.com/starhoshi/21d1fb870d485a95c86fe93cfe1ac240"" rel=""nofollow noreferrer"">https://gist.github.com/starhoshi/21d1fb870d485a95c86fe93cfe1ac240</a></p>
",https://stackoverflow.com/questions/56300385/error-when-testing-firestore-online-with-jest-auth-errortypeerror-fetch-is-n,"['javascript', 'firebase', 'google-cloud-firestore', 'jestjs', 'google-cloud-functions']",713,True,0,2
How do I add svg files via MatIconRegistry in unit tests?,"<p>I'm currently implementing 'unit testing' in my angular application. However, if I run them, I receive multiple warnings/errors similar to this one: <code>'Error retrieving icon: Unable to find icon with the name "":myIcon""'</code>. I suspect it might be caused by not adding the svgs to my MatIconRegistry. I usually do this in my AppComponent, like so:</p>

<pre><code>constuctor(private iconRegistry: MatIconRegistry,
           private sanitizer: DomSanitizer,
           ...) {
        iconRegistry.addSvgIcon('myIcon', sanitizer.bypassSecurityTrustResourceUrl('./assets/icons/myIcon.svg'));
}
</code></pre>

<p>If I run a unit test of another component though, this will not execute and thus not add my svg to the registry. I already tried adding it in my .spec file of the corresponding component, like so:</p>

<pre><code>fdescribe('MyComponent', () =&gt; {
  let component: MyComponent;
  let fixture: ComponentFixture&lt;MyComponent&gt;;
  let iconRegistry;
  let sanitizer;

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

  beforeEach(() =&gt; {
    iconRegistry = TestBed.get(MatIconRegistry);
    sanitizer = TestBed.get(DomSanitizer);
    iconRegistry.addSvgIcon('myIcon', sanitizer.bypassSecurityTrustResourceUrl('./../../assets/icons/myIcon.svg'));
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create component', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>If I run this, it doesn't work. It just returns a different error message: </p>

<pre><code>Error retrieving icon: &lt;svg&gt; tag not found
</code></pre>

<p>My initial thought was that I have made a mistake in the path, but after trying various other paths I'm sure thats not the case.</p>

<p>Does anyone know how do solve this problem? Or maybe there is a better way doing this, since I would have to add my svg icon in every component I'm testing, which would be kinda redundant.</p>
",https://stackoverflow.com/questions/55472255/how-do-i-add-svg-files-via-maticonregistry-in-unit-tests,"['angular', 'testing', 'svg', 'jasmine']",10114,True,29,7
Eclipse CDT indexer different results for C file than C++ file,"<p>I'm using Eclipse 2018-12 with latest CDT.  Getting odd indexing problems with the Editor.  Given the below. If the source file has a "".c"" extension the indexer complains that type ""bool"" and ""false"" cannot be resolved.  If the file has a ""*.cpp"" extension the type is resolved.  </p>

<p>In both cases, the project will build and can be debugged.</p>

<p>Not sure if it matters, but I'm using CMake 3.13 to generate Eclipse Project files, although I have tried to manually adjust project settings to no avail.</p>

<pre><code>#include &lt;stdbool.h&gt;
void main(void)
{
    bool success = false;
}
</code></pre>

<p>I have a C Project, but my unit testing is using GTest and are the only .cpp files in the project. All .c files exhibit this behavior.</p>
",https://stackoverflow.com/questions/54834858/eclipse-cdt-indexer-different-results-for-c-file-than-c-file,"['c++', 'c', 'indexing', 'eclipse-cdt']",263,False,5,2
Unit testing spring webservice client Classes Inheriting WebServiceGatewaySupport,"<p>I am trying to unit test a webservice client in Spring boot. My client extends <code>WebServiceGatewaySupport</code> class and I am using <strong>Mockito</strong> framework.</p>

<p>The issue is I am unable to mock the super class method <code>getWebServiceMethod</code> </p>

<p>A quick search only explains about Integration test using spring which is not what I need<a href=""https://memorynotfound.com/spring-ws-client-side-integration-testing/"" rel=""nofollow noreferrer""> [link]</a></p>

<p>in S/O it has been suggested to Mock the entire base class, but its not  possible either since the unit tests are in same package and also I dont want to manually mock a spring class. </p>

<p>I understand <code>composition over inheritance</code> but is this a valid use case for violating this and How do we achieve this unit testing in these cases? </p>
",https://stackoverflow.com/questions/54153776/unit-testing-spring-webservice-client-classes-inheriting-webservicegatewaysuppor,"['java', 'spring', 'unit-testing', 'spring-boot', 'mockito']",436,False,0,1
Spring Boot 2 MockMVC unit testing with RequestPart and MultipartFile,"<p>I have the below email controller for sending email with RequestPart DTO object (userDTO) and Multipart file (3 files upload max). where userDTO is a JSON object</p>

<p>I tried using postman and it works perfectly for sending email with attachments, however i need to develop unit testing using MockMVC and I am not able to find any suitable examples on these combinations of Multipart and Request Part. When i tried using the below test class, i'm not able to hit  my controller which will trigger email.</p>

<p><strong>My Controller</strong></p>

<pre><code>   @PostMapping(path = ""/api/email/sendEmail)
    public ResponseEntity&lt;UserDto&gt; sendEmail(@RequestPart(value = ""file"", required = false) MultipartFile[] uploadfile,
            @RequestPart UserDto userDTO, WebRequest webRequest) {

            webRequest.setAttribute(""userDTO"", userDTO, RequestAttributes.SCOPE_REQUEST);
            UserDto obj = emailService.sendEmail(userDTO, uploadfile);
            return new ResponseEntity&lt;&gt;(obj, HttpStatus.OK);

    }
</code></pre>

<p><strong>My JSON (userDTO) which comes in request part</strong></p>

<pre><code>{
""sender"":""sender@gmail.com"",
""recipients"":""receiver@gmail.com"",
""subject"":""Hi Testing Mail API"",
""content"":""This is my email""
}

</code></pre>

<p><strong>My Test Class</strong></p>

<pre><code>@ContextConfiguration
@WebAppConfiguration
public class ServicesApplicationTests {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;


      @Test
        public void testEmail() throws Exception {
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();            
             mockMvc.perform(post(""/api/email/sendEmail"")
            .contentType(MediaType.APPLICATION_JSON)
               .content(""{ \""sender\"":\""sender@gmail.com\"",\""recipients\"":\""receiver@gmail.com\"",\""subject\"":\""Hi Testing Mail API\"",\""content\"":\""This is my email\""}"")
               .accept(MediaType.APPLICATION_JSON));


        }
</code></pre>

<p>Any leads would be much appreciated. Thanks</p>
",https://stackoverflow.com/questions/56301621/spring-boot-2-mockmvc-unit-testing-with-requestpart-and-multipartfile,"['unit-testing', 'spring-boot', 'multipart', 'spring-boot-test', 'mockmvc']",712,False,0,0
"Trying to import object in Webpack for testing, I&#39;m lost","<p>I'm working on a project for class and I'm lost regarding webpack and chai/mocha testing. </p>

<ul>
<li><p>I have a an object containing arrays called <code>gameData</code> that lives in a file called <code>data.js</code>.</p></li>
<li><p>I am exporting the <code>gameData</code> variable with <code>export default gameData</code>.</p></li>
<li><p>I am importing it into my <code>Game.js</code> file which has a class called Game. </p></li>
</ul>

<p>What approach can I use to give my Game class access to the gameData object from my <code>data.js</code> file and how can I test that my class has access to the gameData?</p>

<p>Apologies if this is a silly question, but dealing with webpack and unit testing is very new to me at this time.</p>

<pre class=""lang-js prettyprint-override""><code>import './data.js';

class Game {
  constructor(){
    this.currentTurn = 'p1';
    this.game = gameData;
  }
  startGame(){
    //import the data structures
    //copy the data structures
    //select 1 survey at random and remove it from the source array
    //append the question to the DOM
    //create a array with the three associated answers and remove them from source array
  }
  restartGame(){
    //clear all fields
    //revert back to starting arrays
  }
  whoseTurn(){
    if (this.currentTurn === 'p2'){
      //inputs and fields should reflect that it's players X's turn
      //player Y disabled
    } else {
      //inputs and fields should reflect that it's players Y's turn
      //player X disabled
    }
  }
}




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

<pre class=""lang-js prettyprint-override""><code>import chai from 'chai';
import Game from '../src/Game.js';
import '../src/data.js';
const expect = chai.expect;

describe('Game', function() {
    it('Should have access to the data structures', function() {
        let game = new Game();
    })
}

</code></pre>

<p>error for the test:</p>

<pre><code>1) Game
       Should have access to the data structures:
      ReferenceError: gameData is not defined
      at new Game (dist/webpack:/src/Game.js:6:1)
      at Context.&lt;anonymous&gt; (dist/webpack:/test/Game-test.js:8:1)
</code></pre>
",https://stackoverflow.com/questions/55315019/trying-to-import-object-in-webpack-for-testing-im-lost,"['javascript', 'webpack', 'mocha.js', 'chai']",24,False,0,1
TypeError: assertEqual() missing 1 required positional argument: &#39;second&#39;,"<p>I am working on a project in Runestone using test.testEqual().  I work with a Anaconda/Spyder console and translate code back into Runestone.  Python doesn't seem to support test.testEqual so I have attempted to use TestCase.assertEqual(first,second, msg) method under the unittest framework.  My code throws the error message:
TypeError: assertEqual() missing 1 required positional argument: 'second'</p>

<p>but as I show in the code below I include both arguments in the call. I am new to unit testing so not sure where to go in order to solve this issue?</p>

<p>switched from test.testEqual() to TestCase.assertEqual(first,second,msg)</p>

<pre><code>from unittest import TestCase
def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    dsquared = dx**2 + dy**2
    result = dsquared**0.5
    return result

TestCase.assertEqual(distance(1,2, 1,2),0,msg='Equal')
TestCase.assertEqual(distance(1,2, 4,6), 5, msg='Equal')
TestCase.assertEqual(distance(0,0, 1,1), 2**0.5, msg='Equal')
</code></pre>

<p>We would expect the three test cases to Pass based on their execution in Runestone consoles.</p>
",https://stackoverflow.com/questions/56362354/typeerror-assertequal-missing-1-required-positional-argument-second,"['python-unittest', 'testcase']",8683,True,5,2
How to test JMS request without creating SOAP or REST project in SOAPUI,"<p>I am trying to automate some testing for TIBCO BW project (version 5.7 cannot migrate to newer) I found that SOAPUI can be used for testing JMS. However, it requires that I create a REST or SOAP project and supply it with wsdl. I don't want to test SOAP  over JMS but plain JMS communications. Is there any way to do it in SOAPUI? If not, can you recommend any other tool that can be used for unit testing automation of TIBCO Business Works project? I cannot afford BWUnit. I did a lot of research and can't find any other tutorials or solutions. All solutions are about testing SOAP over JMS</p>
",https://stackoverflow.com/questions/57278965/how-to-test-jms-request-without-creating-soap-or-rest-project-in-soapui,"['soap', 'soapui', 'tibco-ems', 'tibco-business-works']",2157,True,0,2
Django: Checks with web-view,"<p>I read the docs for checks: <a href=""https://docs.djangoproject.com/en/2.2/topics/checks/"" rel=""nofollow noreferrer"">https://docs.djangoproject.com/en/2.2/topics/checks/</a></p>

<p>I am missing something: I would like to have a web view where an admin can see what's wrong.</p>

<p>Calling this view should execute the check and the result (ok or failure messages) should be visible.</p>

<p>I could hack something like this myself.</p>

<p>But I would like to go a common way, if there is already such a way.</p>

<p>As opposed to unit-testing this is about checking a <strong>production</strong> server.</p>

<p>How to do this the django-way?</p>

<p>Examples for checks I have on my mind: Checking if third party services are available (smtp server, archive systems, ERP systems, ...)</p>
",https://stackoverflow.com/questions/56558703/django-checks-with-web-view,"['python', 'django', 'health-monitoring']",1747,True,0,2
Elasticsearch + Spring boot: Query creation from method names for property with @InnerField/@MultiField,"<p>I'm trying to build an Elasticsearch query using method name and just curios on what would be the method name if one of the property has multiple fields like following</p>

<pre><code>    @MultiField(
            mainField = @Field(type = Text, fielddata = true),
            otherFields = {
                    @InnerField(suffix = ""keyword"", type = Keyword)
            }
    )
    private String resourceType;
</code></pre>

<p>I needed ""keyword"" type (non-analyzed) so I can search it with entire string.</p>

<p>I have tried it as </p>

<pre><code>List&lt;Event&gt; findByResourceType_KeywordIsIn(Collection&lt;String&gt; list);
</code></pre>

<p>and getting following error</p>

<pre><code>No property keyword found for type String! Traversed path: Event.resourceType.
</code></pre>

<p>Is there anyway I can tell spring-data-elasticsearch that it is for the same property but an InnerField ?</p>

<p>P.S: I can certainly go with either @Query or just build that entire query using NativeSearchQueryBuilder but curios if I can achieve it with just a method name(Less code -> Less unit testing :) )</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/57597498/elasticsearch-spring-boot-query-creation-from-method-names-for-property-with,"['spring-boot', 'elasticsearch', 'spring-data-elasticsearch']",470,True,0,1
How to choose which library to use in a class (maven)?,"<p>I'm started working on an already existing project. In this project there is some JSON-parsing happening with the following exception being thrown by several methods: </p>

<pre><code>JSONException.class
</code></pre>

<p>While I was unit-testing these parsers I couldn't import the right org.json.JSONException library.</p>

<p>The maven library used in the codebase was (package org.json.JSONException):</p>

<pre><code>org.json:json:20160810
</code></pre>

<p>And the one that was importing in my tests was (package org.json.JSONException):</p>

<pre><code>com.vaadin.external.google:android-json:0.0.20131108.vaadin1
</code></pre>

<p>I think the problem lies in both libraries share the same package names. When the test is execute the JSONException is thrown but the test still fails because its probably the other library. Anybody knows why this problem is happening and how to solve it?
Thanks in advance!</p>
",https://stackoverflow.com/questions/56855037/how-to-choose-which-library-to-use-in-a-class-maven,"['java', 'json', 'spring', 'maven']",62,False,0,2
How to unit test stateless material-ui components? functions are not accessible from the outside,"<p>In some of the material-ui examples they have internal functions inside the functional component. Those are unaccessible for unit testing, am I losing something?</p>

<p>What I've could done is just either convert it into a <code>class</code> component or extract those functions outside and bind the params inside...</p>

<p>IE: <a href=""https://material-ui.com/components/steppers/"" rel=""nofollow noreferrer"">https://material-ui.com/components/steppers/</a></p>

<pre class=""lang-js prettyprint-override""><code>import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step';
import StepLabel from '@material-ui/core/StepLabel';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';

const useStyles = makeStyles(theme =&gt; ({
  ...
}));

function getSteps() {
  return ['Select campaign settings', 'Create an ad group', 'Create an ad'];
}

function getStepContent(step) {
  switch (step) {
    case 0:
      return 'Select campaign settings...';
    case 1:
      return 'What is an ad group anyways?';
    case 2:
      return 'This is the bit I really care about!';
    default:
      return 'Unknown step';
  }
}

export default function HorizontalLinearStepper() {
  const classes = useStyles();
  const [activeStep, setActiveStep] = React.useState(0);
  const [skipped, setSkipped] = React.useState(new Set());
  const steps = getSteps();

  function isStepOptional(step) {
    return step === 1;
  }

  function isStepSkipped(step) {
    return skipped.has(step);
  }

  function handleNext() {
    let newSkipped = skipped;
    if (isStepSkipped(activeStep)) {
      newSkipped = new Set(newSkipped.values());
      newSkipped.delete(activeStep);
    }

    setActiveStep(prevActiveStep =&gt; prevActiveStep + 1);
    setSkipped(newSkipped);
  }

  ...

  return (
    &lt;div className={classes.root}&gt;
      &lt;Stepper activeStep={activeStep}&gt;
        {steps.map((label, index) =&gt; {
          const stepProps = {};
          const labelProps = {};
          if (isStepOptional(index)) {
            labelProps.optional = &lt;Typography variant=""caption""&gt;Optional&lt;/Typography&gt;;
          }
          if (isStepSkipped(index)) {
            stepProps.completed = false;
          }
          return (
            &lt;Step key={label} {...stepProps}&gt;
              &lt;StepLabel {...labelProps}&gt;{label}&lt;/StepLabel&gt;
            &lt;/Step&gt;
          );
        })}
      &lt;/Stepper&gt;
      &lt;div&gt;
        {activeStep === steps.length ? (
          &lt;div&gt;
            &lt;Typography className={classes.instructions}&gt;
              All steps completed - you&amp;apos;re finished
            &lt;/Typography&gt;
            &lt;Button onClick={handleReset} className={classes.button}&gt;
              Reset
            &lt;/Button&gt;
          &lt;/div&gt;
        ) : (
          &lt;div&gt;
            &lt;Typography className={classes.instructions}&gt;{getStepContent(activeStep)}&lt;/Typography&gt;
            &lt;div&gt;
              &lt;Button disabled={activeStep === 0} onClick={handleBack} className={classes.button}&gt;
                Back
              &lt;/Button&gt;
              {isStepOptional(activeStep) &amp;&amp; (
                &lt;Button
                  variant=""contained""
                  color=""primary""
                  onClick={handleSkip}
                  className={classes.button}
                &gt;
                  Skip
                &lt;/Button&gt;
              )}

              &lt;Button
                variant=""contained""
                color=""primary""
                onClick={handleNext}
                className={classes.button}
              &gt;
                {activeStep === steps.length - 1 ? 'Finish' : 'Next'}
              &lt;/Button&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        )}
      &lt;/div&gt;
    &lt;/div&gt;
  );
}

</code></pre>

<p>in this example functions like <code>isStepOptional</code>, <code>isStepSkipped</code>, 
<code>handleNext</code> are not accessible from the outside of the component</p>

<p>from a test file would be necessary to access those functions in order to unit-test them.</p>

<p>And another good question would be if those functions are not re-defining on every prop change of that component...</p>

<p>Isn't it a little bit anti-pattern?</p>
",https://stackoverflow.com/questions/57585766/how-to-unit-test-stateless-material-ui-components-functions-are-not-accessible,"['reactjs', 'unit-testing', 'material-ui', 'react-hooks']",216,False,0,0
ember unit testing models,"<p>I am trying to write unit tests for my ember application. Currently the test that model exist works but I want to test computed properties within model which are based on some other properties generated by mirage or returned from API calls. My concern is how shall I initialize or populate data for the model under unit testing?</p>

<p>Sample unit test code for my model: ""user"" is:</p>

<pre><code>import { moduleForModel, test } from 'ember-qunit';

moduleForModel('user', 'Unit | Model | User', {
    needs: ['model:account']
});
</code></pre>

<p>Now I want to write a test where I can use:</p>

<pre><code>let model = this.subject();
</code></pre>

<p>And then I shall be able to access the properties injected by mirage. But how can I do that here? I did not find anything on documentation. Please help</p>
",https://stackoverflow.com/questions/54409443/ember-unit-testing-models,"['unit-testing', 'ember.js']",198,True,0,1
"Subprocess.run does not work in Docker, particularly for pdftotext (IO Error, file not found)","<p>This works locally but not in a Docker container. I'm trying to run <a href=""https://linux.die.net/man/1/pdftotext"" rel=""nofollow noreferrer"">pdftotext</a> in a docker container then unit-testing it on a pdf file. I'm not sure if I'm misunderstanding the arguments required for <code>subprocess.run</code>. Is it not finding the directory of the pdf file or is the subprocess call just not working, or could it be an issue with docker?</p>

<p>I run <code>docker-compose up myproject python3 -m unittest</code></p>

<p>My file structure:</p>

<pre><code>├── myproject
├── ├── extract.py
│   ├── tests
│   │   ├── testExtract.py
│   │   ├── testfiles
|   |   |   ├── sample.pdf
</code></pre>

<p>pdftotext method:</p>

<pre><code>def extract(filepath)
    text = subprocess.run(['pdftotext', filepath],
                                stdout=PIPE,
                                stderr=STDOUT)
    text = str(fullText.stdout)
    return text
</code></pre>

<p>test method inside <code>testExtract.py</code>:</p>

<pre><code>testGetText(self):
    expected = ""b'Grab all text from this sentence.'""
    result = extract('./testfiles/sample.pdf')
    self.assertEqual(result, expected)
</code></pre>

<p>sample.pdf only contains the above sentence.</p>

<p>When I set <code>stderr</code> to <code>STDOUT</code> I get an IO error displayed below. If I set to<code>stderr=subprocess.PIPE</code> I just get an empty binary string. <code>""""</code></p>

<p>traceback:</p>

<pre><code>FAIL: testGetText 
----------------------------------------------------------------------
Traceback (most recent call last):

AssertionError: 'b""I/O Error: Couldn\'t open file \'./tes[51 chars]ry.""' != ""b'Grab all text from this sentence.'""
- b""I/O Error: Couldn't open file './testFiles/1SentenceFile.pdf': No such file or directory.""
+ b'Grab all text from this sentence.'
</code></pre>

<p>Edit:
docker-compose.yml</p>

<pre><code>version: ""3""

services:
    myproject:
        build:
            context: .
            dockerfile: ./myproject/Dockerfile
        depends_on:
            - database
        volumes:
            #- ./otherproject/logs:/code/logs
              # Dev specific
            - ./myproject:/code
        stdin_open: true
        tty: true
    database:
        # Possibly could do configurations here and skip database DOCKERFILE
        build:
            context: .
            dockerfile: ./database/Dockerfile
        environment:
            POSTGRES_USER_FILE: /secrets/dbUser.txt
            POSTGRES_PASSWORD_FILE: /secrets/dbPassword.txt
        ports:
            - ""8765:5432""
        volumes:
            - otherdata:/var/lib/postgresql/data


</code></pre>

<p>myproject/dockerfile:</p>

<pre><code>FROM python:3.7.3-stretch

RUN apt-get update &amp;&amp; apt-get install -y \
    poppler-utils

ARG moduleDir=myproject

WORKDIR /code

COPY secrets/ /secrets

# COPY $moduleDir/myproject/ ./

# Is executed before bind mount is implemented so need to COPY.
COPY $moduleDir/requirements/common.txt requirements/common.txt
COPY $moduleDir/requirements/development.txt requirements/development.txt
COPY .pylintrc ./

RUN pip install -r requirements/development.txt

</code></pre>
",https://stackoverflow.com/questions/58045373/subprocess-run-does-not-work-in-docker-particularly-for-pdftotext-io-error-fi,"['python', 'docker', 'subprocess', 'python-unittest', 'pdftotext']",504,False,0,0
Why would IntelliJ code coverage not show all coverage?,"<p>I have unit tests that I am certain covers a block of Java code. For example, if I run the debugger during unit testing, I can step right through that code. And the results I get can only be gotten from executing that code.</p>

<p>However, the IntelliJ native code coverage tool (even in Trace mode) gives  most of those statements in that block a pink color coding. The coloration does not even seem to make sense, since some green statements are preceded by pink statements that MUST have been executed first.</p>

<p>Does anyone have an explanation for this behavior, and hopefully how to fix it?</p>
",https://stackoverflow.com/questions/56070230/why-would-intellij-code-coverage-not-show-all-coverage,"['intellij-idea', 'code-coverage']",72,False,0,0
Unit testing a Friend Class from another Assembly,"<p>I have a solution which contains two assemblies, both in VB.Net. One assembly contains my code, which mainly includes <code>Friend</code> Classes; and the other assembly contains code dedicated toe unit testing the first assembly. I rely on MSTest.</p>

<p>How can I Unit Test my <code>Friend</code> Classes?</p>

<p>I have seen across several tutorials and documentation that C# has the <code>&lt;Assembly(): InternalsVisibleTo(""AssemblyName"")&gt;</code>, but I understand this is not available for VB.</p>

<p>Whilst searching on SO, I only found <a href=""https://stackoverflow.com/questions/3576242/how-to-use-reflection-to-unit-test-an-internal-friend-in-vb-class-within-an-as"">one match</a>, which suggests an interesting workaround. I am willing to follow this alternative if there is no better option. I am however very surprised there is no clean way to achieve something I though was quite elementary.</p>
",https://stackoverflow.com/questions/55975433/unit-testing-a-friend-class-from-another-assembly,"['vb.net', 'unit-testing']",251,True,0,1
Has anybody desired using chancejs like this: Chance.string(); rather than const chance = new Chance(); chance.string();,"<p>When unit testing in a JavaScript/TypeScript project I have found great value in using chancejs (<a href=""https://chancejs.com"" rel=""nofollow noreferrer"">https://chancejs.com</a>). But in each different spec file I have to instantiate a new instance of chance like so:</p>
<h2>Example with instances:</h2>
<pre><code>//Spec 1
const chance = new Chance();
const personMock = {
    firstName: chance.name(),
    age: chance.integer(),
};

//Spec 2
const chance = new Chance();
const addressMock = {
    address: chance.address(),
    isApartment: chance.bool(),
};
</code></pre>
<p>I have not discovered a need for a chance instance, except when a known seed is declared (<a href=""https://chancejs.com/usage/seed.html"" rel=""nofollow noreferrer"">https://chancejs.com/usage/seed.html</a>). In all cases where it is not desireable to use a seed, it seems like instantiating chance is only extra overhead.</p>
<p><strong>Question 1:</strong> Has anybody desired using chance in the same way we use Math.random()?</p>
<h2>Example without instances:</h2>
<pre><code>//Spec 1
const personMock = {
    firstName: Chance.name(),
    age: Chance.integer(),
};

//Spec 2
const addressMock = {
    address: Chance.address(),
    isApartment: Chance.bool(),
};
</code></pre>
<p><strong>Question 2:</strong> Can you foresee any drawbacks to doing so?</p>
",https://stackoverflow.com/questions/58328429/has-anybody-desired-using-chancejs-like-this-chance-string-rather-than-const,"['javascript', 'typescript', 'unit-testing', 'random']",379,True,0,1
Mocking Multiple Implementations of the interface used as IEnumerable in DI,"<p>Using ASP.NET core Dependency injection to inject multiple implementations of an Interface.
This is how my code looks:</p>

<p><code>public factory(IEnumerable&lt;ISomeInterface&gt; interfaceImplList){}</code></p>

<p><code>public class Impl1:ISomeInterface(){}</code></p>

<p><code>public class Impl2:ISomeInterface(){}</code></p>

<p><code>public class Impl3:ISomeInterface(){}</code></p>

<p><code>public class Impl4:ISomeInterface(){}</code></p>

<p>All the above implementations are injected into the factory and factory will return some implementation based on some configs (Not related to the question)</p>

<p>Now I want to mock this factory using moq. Is there a way to do that, or should I create all the mocked implementations of above classes and them put them in a IEnumerable and pass? </p>

<p>Also another question, is it even a good unit testing practice to create a factory to return mocked instance or should I directly unit test the individual implementations?</p>
",https://stackoverflow.com/questions/56821002/mocking-multiple-implementations-of-the-interface-used-as-ienumerable-in-di,"['c#', 'unit-testing', 'asp.net-core', 'dependency-injection', 'moq']",376,False,0,0
All ViewController Views are Nil in Unit Testing?,"<p>Sorry if this is a beginner question but I'm relatively new to Unit testing and didn't see this asked anywhere.   </p>

<p>When I start my unit tests in Swift, I setUp my tests by instantiating my viewController.</p>

<p>My code is set up using MVVM (Model - View - ViewModel).  So when I test some of my viewModel methods, they will update the Views (in the ViewController) in the UI.  The problem is, Xcode keeps crashing and says that the views in the ViewController are nil?  How do I prevent these views from being nil?  Am I doing something wrong?  How do I instantiate the views within the viewController?  I thought this would be automatic.  </p>

<pre><code>class WeirdFaceTests: XCTestCase {

    var viewController: ViewController?
    var tattooModel: ARModel?
    var tattooViewModel: ARViewModel?
    var mainUIModel: MainUIModel?
    var mainUIViewModel: MainUIViewModel?

    override func setUp() {
        // Put setup code here. This method is called before the invocation of each test method in the class.
        super.setUp()
        self.viewController = UIStoryboard(name: ""Main"", bundle: nil).instantiateViewController(withIdentifier: ""PrimaryViewController"") as! ViewController

        self.tattooModel = ARModel(imageName: ""blank"", tattooType: .new)
        self.tattooViewModel = ARViewModel(tattooModel: tattooModel!, delegate: viewController!)

        self.mainUIModel = MainUIModel()
        self.mainUIViewModel = MainUIViewModel(model: mainUIModel!, delegate: viewController!)
    }
</code></pre>
",https://stackoverflow.com/questions/57048166/all-viewcontroller-views-are-nil-in-unit-testing,"['swift', 'unit-testing']",362,False,0,1
Unable to disable Msurguy Honeypot in Unit test in Laravel,"<p>I am developing a Laravel application. I am doing unit testing on my application as well. I am also implementing Honeypot on the forms as well using this package, <a href=""https://github.com/msurguy/Honeypot"" rel=""nofollow noreferrer"">https://github.com/msurguy/Honeypot</a>. It is working when I submit the form from the browser. But the thing is I need to disable it in the unit test. I am trying to do it following what is mentioned in the docs like this.</p>

<pre><code>Honeypot::disable();
</code></pre>

<p>But when I run my test, I got this error. </p>

<pre><code>ErrorException: Non-static method Msurguy\Honeypot\Honeypot::disable() should not be called statically
</code></pre>

<p>What is wrong? Is the documentation wrong or how can I possibly do that?
That is what exactly mentioned in the docs.</p>
",https://stackoverflow.com/questions/54043741/unable-to-disable-msurguy-honeypot-in-unit-test-in-laravel,"['laravel', 'honeypot']",107,True,0,1
Re-instantiate interface reference on run time with the underlying type,"<p>I'm using interfaces for unit testing in my project.
My interface have functions as well as properties.
I will be creating the object of interface class at the app startup as dependency and will be using throughout the application life cycle.
Is it possible to re-instantiate the class pointing to interface on run time with the underlying type?</p>

<p>For example.
This is what i do at app startup.</p>

<pre><code>IPerson iperson = new Person();
</code></pre>

<p>Now once my API's are getting called i want to reinstatement this object again as per business logic.
So again in my API logic how would i know what object type my interface is pointing to?
Can i do something like this</p>

<pre><code>// Type could be anything like Person,Person1,Person2 as all these classes implementing IPerson
Type p = iperson.Type 
 iperson = new p();
</code></pre>
",https://stackoverflow.com/questions/58625035/re-instantiate-interface-reference-on-run-time-with-the-underlying-type,['c#'],64,False,0,1
Unexpected error while Controller unit test,"<p>I am learning unit testing. I have implemented unit test for the spring boot controller in my sample project. When I run the test class, every time it returns 400 status (Expected 200). After i did a research and I have found that <code>if(entity.getStatusCode().equals(HttpStatus.OK)) {</code> is line which gives exception. It might be because it uses return of Service2.</p>

<p>However, code is working fine without running test cases. I have attached MyController and MyControllerTest classes.</p>

<p><strong>My Controller</strong></p>

<pre><code>@RestController
@RequestMapping(""/user"")
public class UserController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserManagementService userManageService;
@Autowired
private AdminManagementService adminManageService;
@Autowired
private AuthenticateManagementService authService;

@PutMapping(""/change-password"")
public ResponseEntity&lt;?&gt; changePassword(@RequestHeader(""Authorization"") String token, 
        @RequestBody PasswordChangeRequestDTO passwordChangeRequestDTO) {
    ResponseDTO finalResponse = new ResponseDTO();
    try {
        LOGGER.info(""Changing user password."");
        KeycloakLoginResponseDTO keycloakResponse = authService.auhtenticate(passwordChangeRequestDTO.getLoginRequestDTO());
        ResponseEntity&lt;?&gt; logoutEntity = authService.logout(token, keycloakResponse.getSession_state());
        if(logoutEntity.getStatusCode().equals(HttpStatus.OK)) {
            LOGGER.info(""User password matched"");
        }
        String userId = adminManageService.getUserByName(token, passwordChangeRequestDTO.getLoginRequestDTO().getUsername());
        ResponseEntity&lt;?&gt; entity = userManageService.changePassword(token, passwordChangeRequestDTO, userId);
        LOGGER.info(""USER : "" + """" +""has successfully changed password."");
        finalResponse.setMessageCode(HttpStatus.OK);
        finalResponse.setMessage(""Password changed successfully"");
        finalResponse.setError(false);
        ResponseEntity&lt;ResponseDTO&gt; finalEntity = ResponseEntity.ok().body(finalResponse);
        return finalEntity;
    }catch (Exception e) {
        e.printStackTrace();
        LOGGER.error(""Error has occured while changing password of USER : "" + """" + ""."");
        finalResponse.setMessageCode(HttpStatus.EXPECTATION_FAILED);
        finalResponse.setMessage(""Oops! Looks like you have entered the wrong password in the 'Old Password' field"");
        finalResponse.setMessageDetail(e.getMessage());
        finalResponse.setError(true);
        ResponseEntity&lt;ResponseDTO&gt; finalEntity = ResponseEntity.badRequest().body(finalResponse);
        return finalEntity;
    }
}
}
</code></pre>

<p><strong>Controller Unit test class</strong></p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private UserManagementService userManageService;
@MockBean
private AdminManagementService adminManageService;
@MockBean
private AuthenticateManagementService authService;

@InjectMocks
private UserController userController;

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

@Test
public void testChangePasswordhappyPath() throws Exception {
    PasswordChangeRequestDTO passwordChangeRequestDTO = new PasswordChangeRequestDTO();
    LoginRequestDTO loginRequestDTO = new LoginRequestDTO();
    loginRequestDTO.setClient_id(""test_client"");
    loginRequestDTO.setGrant_type(""test_grant_type"");
    loginRequestDTO.setPassword(""test_password"");
    loginRequestDTO.setUsername(""test_user"");
    CredentialsRequestDTO credentialsRequestDTO = new CredentialsRequestDTO();
    credentialsRequestDTO.setTemporary(false);
    credentialsRequestDTO.setType(""password"");
    credentialsRequestDTO.setValue(""test_password"");
    passwordChangeRequestDTO.setLoginRequestDTO(loginRequestDTO);
    passwordChangeRequestDTO.setCredentialsRequestDTO(credentialsRequestDTO);

    ResponseEntity&lt;String&gt; mockResponse = new ResponseEntity&lt;String&gt;("""", HttpStatus.OK);
    when(userManageService.changePassword(""Token"", passwordChangeRequestDTO, ""UserId"")).thenReturn(mockResponse);
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(passwordChangeRequestDTO);

    mockMvc.perform(put(""/user/change-password"", passwordChangeRequestDTO)
            .accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON)
            .header(""Authorization"", ""Token"")
            .content(json)
            .characterEncoding(""utf-8""))
        .andExpect(status().isOk()).andReturn();
}
}
</code></pre>

<p>What am i doing wrong here. Is there anything to add to my <code>MyControllerTest</code> class or How can i cover this test case. Any help would be grateful.</p>

<p><strong>UPDATED</strong></p>

<p>I have also added <code>e.printStackTrace()</code></p>

<pre><code>java.lang.NullPointerException
at com.mycode.controller.UserController.changePassword(UserController.java:39)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:919)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
at com.mycode.controller.UserControllerTest.testChangePasswordhappyPath(UserControllerTest.java:71)
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.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.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>
",https://stackoverflow.com/questions/56108881/unexpected-error-while-controller-unit-test,"['rest', 'unit-testing', 'spring-boot', 'junit']",114,False,0,0
How to write unit tests for EntityManager transaction?,"<p>I am trying to write a unit test for a existing function that updates a value of a DB field using EntityManager. My unit test should verify that the class updates the value correctly. The current code looks like this:</p>

<pre><code>public class MyClass {
    MyClass(EntityManager em) {
      this.em = em;
    }

    void updateValue() {
      em.getTransaction().begin();
      TypedQuery query = em.createQuery(""select a from ..."", MyResult.class);
      List&lt;MyResult&gt; results = query.getResultList(); 

      MyResult result = results.get(0);
      result.setInterestingValue(1);
      em.getTransaction().commit();
    }
}
</code></pre>

<p>My current approach for the unit testing:</p>

<pre><code>@Mock EntityManager em;
@Mock TypedQuery query;

publid void test() {
   MyClass myClass = new MyClass(em);
   MyResult result = new MyResult();
   ArrayList&lt;MyResult&gt; resultList = new ArrayList&lt;&gt;();
   resultList.add(result);

   when(em.getTransaction()).thenReturn(mock(EntityTransaction.class));
   when(em.createQuery(anyString(), any())).thenReturn(query);
   when(query.getResultList()).thenReturn(resultList);

   myClass.updateValue();

   assertEquals(1, result.getInterestingValue());
}
</code></pre>

<p>My unit test above verifies that the MyResult instance is updated. However, it doesn't verify that the value is actually updated through EntityManager. In other words, I'd like to test if EntityManager is correctly used in the existing code. For example, even if I call commit() before setInterestinvValue(1), my test will still pass. Is there a good way to test it?</p>
",https://stackoverflow.com/questions/57046281/how-to-write-unit-tests-for-entitymanager-transaction,"['java', 'unit-testing', 'jpa', 'mockito', 'entitymanager']",1130,True,0,1
Importing a function from a different folder for unit testing throws an error for an exterior function call,"<p>I'm new to unit testing, learning with unittest. I'm trying to run a unit test from a file in a separate tests folder, using import to bring in the function I want to test. 
When I run the test, I get a FileNotFoundError. The error points to a file that the main.py file should open, but for the test, I'm only importing the function translate. </p>

<p>I've tried setting up an <code>__init__.py</code> file with <code>__all__ = [""translate""]</code> - no change.   </p>

<p>Here's my file structure:</p>

<pre><code>|
|--dictionary_app
|   |--main.py
|   |--data.json
|
|--tests
    |--integration
    |
    |--unit
        |--test_1.py
</code></pre>

<p>Code from main.py:</p>

<pre><code>#Get data from a JSON file
data = json.load(open(""data.json""))

    def translate(w):
        w = w.lower()
        if w in data:
            return data[w]
        elif w.capitalize() in data:
            return data[w.capitalize()]
        elif len(difflib.get_close_matches(w, data.keys())) &gt; 0:
            yes_no = input(""Did you mean {} instead? Enter Y if yes, or N if 
                no: "".format(difflib.get_close_matches(w, data.keys())[0]))
            if yes_no == ""Y"":
                return data[difflib.get_close_matches(w, data.keys())[0]]
            elif yes_no == ""N"":
                return ""This word does not appear in the Archives.""
            else:
                return ""Query not understood.""
        else:
            return ""This word does not appear in the Archives.""

    def main():
        #calls translate
</code></pre>

<p>This line in test.py produces the error:
<code>from dictionary_app.main import translate</code></p>

<p>My results</p>

<blockquote>
  <p>FileNotFoundError: [Errno 2] No such file or directory: 'data.json'</p>
</blockquote>

<p>I didn't expect the import to pull in the line opening data.json.</p>
",https://stackoverflow.com/questions/56409988/importing-a-function-from-a-different-folder-for-unit-testing-throws-an-error-fo,"['python-3.x', 'unit-testing', 'tdd']",315,False,0,1
How to mock window.gapi.load() in jest for vuejs,"<p>I have used google auth in my vuejs application. Also I am using vue-test-utils for unit testing.</p>

<p>Problem occurs when I need to mock google auth methods like window.gapi.load(), window.gapi.auth2.init(), etc ...</p>

<p>I tried using jest.fn(), but it didnt work. Also I tried this : </p>

<pre><code>window.gapi = {
  load() { }
}
</code></pre>

<p>Beyond this I couldn't proceed. Also mocking google api's are bit of a grey area. Not much docs are available online.</p>

<h2>Login.vue:</h2>

<pre><code>&lt;template&gt;
  &lt;div class=""center login__wrapper""&gt;
    &lt;div fluid fill-height login&gt;
      &lt;div id=""my-signin2""&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;
</code></pre>

<p></p>

<pre><code>export default {
  name: ""Login"",

 data() {
   return {

   }
 },

 methods: {
   onSuccess(GoogleUser) {
     this.$router.push(""/homepage"");
  },

   onFailure() {
     console.log(""try again)
  },

   renderButton() {
     this.init();
     let self = this;
     window.gapi.signin2.render(""my-signin2"", {
       scope: ""profile email"",
       width: 240,
       height: 50,
       longtitle: true,
       theme: ""dark"",
       onsuccess: this.onSuccess,
       onfailure: this.onFailure
     });
    },

  init() {
   window.gapi.load(""auth2"", function() {
     window.gapi.auth2.init({
       client_id: xyz,
       ux_mode: ""redirect""
     });
    });
   }
  },

 mounted() {
   this.renderButton();
  }
 };
&lt;/script&gt;
</code></pre>

<p>When I run npm run test:unit, should throw no error. 
I need to mock the following methods:</p>

<p>1) window.gapi.load()</p>

<p>2) window.gapi.auth2.init()</p>

<p>3) window.gapi.signin2.render()</p>

<p>4) renderButton()</p>

<p>5) onSuccess(), onFailure()</p>

<p>It becomes more difficult as these methods do not return anything. Please help me out here</p>
",https://stackoverflow.com/questions/57857388/how-to-mock-window-gapi-load-in-jest-for-vuejs,"['vue.js', 'jestjs', 'google-authentication', 'vue-test-utils', 'google-api-js-client']",424,False,4,0
How to make Spring boot webflux to start on default Netty rather than Jetty while testing,"<p>I have a somewhat similar gradle and spring webflux config up as described in <a href=""https://stackoverflow.com/questions/47746024/why-spring-webflux-is-choosing-jetty-by-default-and-then-failing"">Why spring webflux is choosing jetty by default and then failing?</a></p>

<p>But our goal is to have in memory Amazon dynamo db + spring webflux on netty (and NOT jetty) for our unit testing ( we already have production dynamo db with spring webfux on netty ). I am able to run unit tests using in-memory dynamo db but as soon as I enable springboot webflux, it starts complaining :</p>

<pre class=""lang-java prettyprint-override""><code>   Caused by: java.lang.NoClassDefFoundError: org/eclipse/jetty/servlet/ServletHolder
    at org.springframework.boot.web.embedded.jetty.JettyReactiveWebServerFactory.createJettyServer(JettyReactiveWebServerFactory.java:176) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.web.embedded.jetty.JettyReactiveWebServerFactory.getWebServer(JettyReactiveWebServerFactory.java:106) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext$ServerManager.&lt;init&gt;(ReactiveWebServerApplicationContext.java:202) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext$ServerManager.get(ReactiveWebServerApplicationContext.java:221) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.createWebServer(ReactiveWebServerApplicationContext.java:90) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.onRefresh(ReactiveWebServerApplicationContext.java:79) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    ... 62 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.eclipse.jetty.servlet.ServletHolder
</code></pre>

<p>I have tried following in my build.gradle :</p>

<pre><code> configurations {
    // exclude Reactor Jetty /Tomcat 
    compile.exclude  group: 'org.springframework.boot',module: 'spring-boot-starter-jetty'
    testcompile.exclude  group: 'org.springframework.boot',module: 'spring-boot-starter-jetty'
    //compile.exclude group: 'javax.servlet' , module: 'servlet-api' //&lt;--tried servlet jar exclusion also
}

.....
testCompile ('com.amazonaws:DynamoDBLocal:1.11.477')
....//event tried this ( and is probably wrong)
testCompile(""org.springframework.boot:spring-boot-starter-test:$springBootVersion"") {
        exclude  group: 'org.springframework.boot', module: 'spring-boot-starter-jetty' //by both name and group
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'

    }
</code></pre>

<p>I checked dependency graph :</p>

<pre><code>\--- com.amazonaws:DynamoDBLocal:1.11.477
    +--- org.antlr:antlr4-runtime:4.7.2
    +--- commons-cli:commons-cli:1.2
    +--- org.apache.commons:commons-lang3:3.8.1
    +--- com.almworks.sqlite4java:libsqlite4java-linux-i386:1.0.392
    |    \--- com.almworks.sqlite4java:sqlite4java:1.0.392
    +--- com.almworks.sqlite4java:libsqlite4java-linux-amd64:1.0.392
    |    \--- com.almworks.sqlite4java:sqlite4java:1.0.392
    +--- com.almworks.sqlite4java:sqlite4java-win32-x64:1.0.392
    |    \--- com.almworks.sqlite4java:sqlite4java:1.0.392
    +--- com.almworks.sqlite4java:sqlite4java-win32-x86:1.0.392
    |    \--- com.almworks.sqlite4java:sqlite4java:1.0.392
    +--- com.almworks.sqlite4java:libsqlite4java-osx:1.0.392
    |    \--- com.almworks.sqlite4java:sqlite4java:1.0.392
    +--- com.amazonaws:aws-java-sdk-core:1.11.477 (*)
    +--- com.amazonaws:aws-java-sdk-dynamodb:1.11.477 (*)
    +--- org.apache.logging.log4j:log4j-api:2.6.2 -&gt; 2.11.2
    +--- org.apache.logging.log4j:log4j-core:2.6.2 -&gt; 2.11.2
    |    \--- org.apache.logging.log4j:log4j-api:2.11.2
      +--- org.eclipse.jetty:jetty-client:8.1.12.v20130726 -&gt; 9.4.18.v20190429
    |    +--- org.eclipse.jetty:jetty-http:9.4.18.v20190429
    |    |    +--- org.eclipse.jetty:jetty-util:9.4.18.v20190429
    |    |    \--- org.eclipse.jetty:jetty-io:9.4.18.v20190429
    |    |         \--- org.eclipse.jetty:jetty-util:9.4.18.v20190429
    |    \--- org.eclipse.jetty:jetty-io:9.4.18.v20190429 (*)
    +--- org.eclipse.jetty:jetty-server:8.1.12.v20130726 -&gt; 9.4.18.v20190429
    |    +--- javax.servlet:javax.servlet-api:3.1.0 -&gt; 4.0.1
    |    +--- org.eclipse.jetty:jetty-http:9.4.18.v20190429 (*)
    |    \--- org.eclipse.jetty:jetty-io:9.4.18.v20190429 (*)
    +--- org.mockito:mockito-core:1.10.19 -&gt; 2.23.4
    |    +--- net.bytebuddy:byte-buddy:1.9.3 -&gt; 1.9.12

</code></pre>

<p>So what I need is to force webflux to have Netty as server. I think it is getting overridden by dynamodb dependency or some jar transitivity.</p>
",https://stackoverflow.com/questions/56783116/how-to-make-spring-boot-webflux-to-start-on-default-netty-rather-than-jetty-whil,"['unit-testing', 'spring-boot', 'amazon-dynamodb', 'spring-webflux']",2343,True,4,3
How to fix the error from my unit-testing class?,"<p>I have an homework where I need to create a J2EE application web. In my team, I'm the one that need to prepare the unit-tests, but I have a lots of errors in them and I don't know how to solve them so I would like to request some help please.</p>

<p>Class Customer:</p>

<pre><code>public class Customer {

private int CustomerID;
private String email;

public int getCustomerID() {
    return CustomerID;
}

public void setCustomerID(int CustomerID) {
    this.CustomerID = CustomerID;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

}
</code></pre>

<p>Class CustomerDAO:</p>

<pre><code>private final DataSource myDataSource;
public CustomerDAO(DataSource dataSource) {
    this.myDataSource = dataSource;
}


public Customer LoginCustomer(int customerID, String email) throws DAOException {
    Customer result = null;

    String sql = ""SELECT * FROM CUSTOMER WHERE CUSTOMER_ID = ? AND EMAIL = ?"";
    try (Connection connection = myDataSource.getConnection(); 
        PreparedStatement stmt = connection.prepareStatement(sql)) {

        stmt.setInt(1, customerID);
                    stmt.setString(2, email);

        try (ResultSet rs = stmt.executeQuery()) {
            if (rs.next()) {
                String name = rs.getString(""NAME"");
                String address = rs.getString(""ADDRESSLINE1"");

                result = new Customer();
                                    result.setCustomerID(customerID);
                                    result.setEmail(email);
            } 
        }
    }  catch (SQLException ex) {
        Logger.getLogger(""DAO"").log(Level.SEVERE, null, ex);
        throw new DAOException(ex.getMessage());
    }

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

<p>Class DAO:</p>

<pre><code>public class DAO {

private final DataSource myDataSource;

public DAO(DataSource dataSource) {
    this.myDataSource = dataSource;
}
    public int addOrder(int ordernum, int idcustomer, int   idproduct, int quantity, int shippingcost, Date salesDate, Date shippingDate, String company) throws SQLException {
    int result = 0;
    String sql = ""INSERT INTO PURCHASE_ORDER VALUES=(?,?,?,?,?,?,?,?) "";
    try (Connection connection = myDataSource.getConnection();
            PreparedStatement stmt = connection.prepareStatement(sql)) {
        stmt.setInt(1, ordernum);
        stmt.setInt(2, idcustomer);
        stmt.setInt(3, idproduct);
        stmt.setInt(4, quantity);
        stmt.setInt(5, shippingcost);
        stmt.setDate(6, (java.sql.Date) salesDate);
        stmt.setDate(7, (java.sql.Date) shippingDate);
        stmt.setString(8, company);
        result = stmt.executeUpdate();
    }
    return result;
}
public int deleteOrder(int OrderNum) throws SQLException {
    int result = 0;
    String sql = ""DELETE FROM PURCHASE_ORDER WHERE ORDER_NUM = ?"";
    try (Connection connection = myDataSource.getConnection();
            PreparedStatement stmt = connection.prepareStatement(sql)) {
        stmt.setInt(1, OrderNum);
        result = stmt.executeUpdate();
    }
    return result;
}
public int changeOrder(int Qte, int ordernum) throws SQLException {
    int result=0;
    String sql = ""UPDATE PURCHASE_ORDER SET QUANTITY = ? WHERE ORDER_NUM=?"";
    try (Connection connection = myDataSource.getConnection();
            PreparedStatement stmt = connection.prepareStatement(sql)) {
        stmt.setInt(1, Qte);
        stmt.setInt(2, ordernum);
        result=stmt.executeUpdate();
    }
    return result;
}
</code></pre>

<p>Class DataSouceFactory:</p>

<pre><code>public class DataSourceFactory {

public enum DriverType {
    embedded, server
};

// Choic du type de driver : embedded ou serveur
private static final DriverType TYPE = DriverType.embedded;

/**
 * Renvoie la source de données (server ou embbeded)
 *
 * @return la source de données
 */
public static DataSource getDataSource() {

    ds.setDatabaseName(""sample"");
    ds.setUser(""app"");
    ds.setPassword(""app"");
    // The host on which Network Server is running
    ds.setServerName(""localhost"");
    // port on which Network Server is listening
    ds.setPortNumber(1527);
    return ds;
}

}
</code></pre>

<p>Class Product:
    public class Product {</p>

<pre><code>private int idproduct;
private int idmanufacturer;
private String productcode;
private int purchasecost;
private int quantityonhand;
private int markup;
private String available;
private String description;

public Product(int idproduct, int idmanufacturer, String productcode, int purchasecost, int quantityonhand, int markup, String available, String description){
    this.idproduct=idproduct;
    this.idmanufacturer=idmanufacturer;
    this.productcode=productcode;
    this.purchasecost=purchasecost;
    this.quantityonhand=quantityonhand;
    this.markup=markup;
    this.available=available;
    this.description=description;
}

//GETTER

public int getIdProduct() {
    return idproduct;
}

public int getIdManufacturer(){
    return idmanufacturer;
}

public String getProductCode(){
    return productcode;
}

public int getPurchaseCost(){
    return purchasecost;
}

public int getQuantityOnHand(){
    return quantityonhand;
}

public int getMarkup(){
    return markup;
}

public String getAvailable(){
    return available;
}

public String getDescription(){
    return description;
}
}
</code></pre>

<p>Class PurchaseOrder:</p>

<pre><code>public class PurchaseOrder {

private int ordernum;
private int idcustomer;
private int idproduct;
private int quantity;
private int shippingcost;
private Date salesDate;
private Date shippingDate;
private String company;

public PurchaseOrder(int ordernum, int idcustomer, int idproduct, int quantity, int shippingcost, Date salesDate, Date shippingDate, String company) {
    this.ordernum=ordernum;
    this.idcustomer=idcustomer;
    this.idproduct=idproduct;
    this.quantity=quantity;
    this.shippingcost=shippingcost;
    this.salesDate=salesDate;
    this.shippingDate=shippingDate;
    this.company=company;
}

//GETTER

public int getOrderNumber() {
    return ordernum;
}

public int getIdCustomer() {
    return idcustomer;
}

public int getIdProduct(){
    return idproduct;
}

public int getShippingCost(){
    return shippingcost;
}


public Date getSalesDate() {
    return salesDate;
}

public Date getShippingDate() {
    return shippingDate;
}

public String getCompany() {
    return company;
}



}
</code></pre>

<p>Class DAOException:</p>

<pre><code>public class DAOException extends Exception {

/**
 * Creates a new instance of &lt;code&gt;DAOException&lt;/code&gt; without detail
 * message.
 */
public DAOException() {
}

/**
 * Constructs an instance of &lt;code&gt;DAOException&lt;/code&gt; with the specified
 * detail message.
 *
 * @param msg the detail message.
 */
public DAOException(String msg) {
    super(msg);
}
}
</code></pre>

<p>Unit-testing class:</p>

<pre><code>public class DAOTest {

private DAO myDAO;
private DataSource myDataSource;
private static Connection myConnection;

/**
 * Test for the data base
 */
@Before
//Test la création de la BDD.
public void createBDD() throws SQLException {
    myDataSource = getDataSource();
    myConnection = myDataSource.getConnection();
    myDAO = new DAO(myDataSource);
}

@After
//Test la destruction de la BDD.
public void deleteBDD() throws SQLException {
    myConnection.close();
    myDAO = null;
}

@Test
//Test le remplissage de la BDD à partir d'un fichier sql.
private void fillBDD(String file, Connection myConnection) throws SQLException {
    String path = DAOTest.class.getResource(file).getFile();
    SqlFile fileSQL = new SqlFile(new File(path));
    fileSQL.setConnection(myConnection);
    fileSQL.execute();
    fileSQL.closeReader();
}

/**
 * Test for the class dataSourceFactory
 */
//Test l'acquisition de la source de donnée.
@Test
public void getDataSource() throws DAOException {
    org.hsqldb.jdbc.JDBCDataSource ds = new org.hsqldb.jdbc.JDBCDataSource();
    ds.setDatabase(""jdbc:hsqldb:mem:testcase;shutdown=true"");
    ds.setUser(""username"");
    ds.setPassword(""password"");
    return ds;
}

/**
 * Test for the class CustomerDAO
 */
@Test
// Test si le login fonctionne
public void logIN() throws DAOException {
    int customerID = 1;
    String email = ""test@example.com"";
    assertEquals(customerID, myDAO.identification(email));
}

/**
 * Test for the class ???
 */
@Test
//Test le calcule du prix du produit.
public void finalPrice() {
    float price = 10;
    int quantity = 1;
    float discountRate = 0;
    float shippingcost = 10;
    float markup = 0;
    assertEquals(price * quantity * 0.01 * (1 - discountRate) + shippingcost, ""Méthode qui calcule le prix final"");
}
}
</code></pre>

<p>I don't know if it can help, but we made a git for it here: <a href=""https://github.com/Selena00/ProjetTechnoWeb"" rel=""nofollow noreferrer"">https://github.com/Selena00/ProjetTechnoWeb</a></p>

<p>Well the first problem that I have in the unit-testing classs is the fact that when I do a ""throws DAOException"", I have an error conserning its location.</p>

<p>Same in with ""private DAO myDAO"", it says that the symbol DAO can't be found. And that problem is present everywhere where I create a new ""DAO"".
Again I have a problem with the test ""fillBDD"", where it again says that the symbol SqlFile isn't found.</p>

<p>Finally in the test ""getDataSource"", it says in the first line that the package org.hsqlsb.jsbc does not exist.</p>

<p>In all of the above case, the only thing that it proposed me was to search for depencies in the Maven repositories but without success.</p>

<p>Afterwards if some people can give me some advice about how to do the tests: ""addOrder"", ""deleteOrder"" and ""changeOrder"", I would really be grateful. For those three tests I don't know how to begin :/.</p>

<p>Thanks in advance for those who would take the time to help me :D.</p>
",https://stackoverflow.com/questions/55686550/how-to-fix-the-error-from-my-unit-testing-class,"['java', 'database', 'unit-testing', 'exception', 'netbeans']",480,False,0,0
How to assign gmock function to specific function pointer?,"<p>I'm working on unit testing two dlls with Gtest and Gmock in C++:<br>
A.dll and B.dll, both are written in C and I cannot modify them.</p>

<p>A.dll's <code>init</code> function uses B.dll's functions as arguments via function pointers. I want to mock B's functions (as they are hardware dependent).</p>

<p>I created a test fixture class for A.dll that dynamically loads the functions <code>init</code> and <code>calc</code>. The following code gives a quick overview of the functions of interest:</p>

<pre><code>class TestFixture : public ::testing::Test {
    // dynamically loads functions from A.dll and assigns
    // them to function pointers init_ptr and calc_ptr.
};

// function pointer typedef for use with B.dll's functions
typedef int (*funcPtr)(int, int);

// Loaded from A.dll    
void init(funcPtr func1, funcPtr func2) {
    // internally set functions in A.dll to be used in calculate
}

// Loaded from A.dll
int calculate(int a, int b) {
    // returns a+b + a+b
    return func1(func2(a,b), func2(a,b));
}

// Inside B.dll, should be mocked
int add(int a, int b) { return a+b; }

// Dummy class for B.dll
class B {
    virtual ~B() {}
    virtual int add(int a, int b) = 0;    
};

class MockB : public B {
virtual ~MockB() {}
    MOCK_METHOD(int, add, (int a, int b));
};

// Following example test run is the goal:
TEST_F(TestFixture, AddTest) {
    MockB b;

    // want to use mocked add function here
    init_ptr(mockedAdd, mockedAdd);

    EXPECT_CALL(b, add(_,_)).Times(3);
    EXPECT_EQ(calc_ptr(2,3), 10);
}
</code></pre>

<p>When I tried to create a dummy B and a MockB class, I didn't manage to assign the mocked methods to the function pointers that <code>init_ptr(funcPtr, funcPtr)</code> requires. Is there a way to achieve this with Gmock (or a similar framework)?</p>
",https://stackoverflow.com/questions/57072085/how-to-assign-gmock-function-to-specific-function-pointer,"['c++', 'function-pointers', 'googlemock']",2835,True,3,1
Cannot see boost unit test namespace and class names in Visual Studio test explorer window,"<p>I'm developing a CMake project in Visual Studio 2019, and I want to perform unit testing with <code>boost::test</code> by using the Visual Studio Test Explorer.</p>

<p>I've the following <code>CMakeLists.txt</code> that defines a boost unit test project for some code:</p>

<pre><code>cmake_minimum_required (VERSION 3.10.0)

include(CTest)

enable_testing()

project (datatest)

message (STATUS ""Building project ${PROJECT_NAME}"")

set (CMAKE_RUNTIME_OUTPUT_DIRECTORY ${TEST_OUTPUT_DIRECTORY})
set (Boost_USE_STATIC_LIBS ON)
set (Boost_USE_MULTITHREADED ON)
unset (Boost_INCLUDE_DIR CACHE)
unset (Boost_LIBRARY_DIRS CACHE)
set (CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH})
find_package (Boost COMPONENTS unit_test_framework log system REQUIRED)

include_directories (${CMAKE_SOURCE_DIR}/src ${Boost_INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR})

set (TEST_SRC
  stdafx.cpp
  IconTest.cpp
  AttitudeTest.cpp
  LLAtest.cpp
  Model3DTest.cpp
  PlayerTest.cpp
  TimeDateTest.cpp
  )

add_executable (${PROJECT_NAME} ${TEST_SRC})

# Creating a function for easily adding tests
#
# Parameters:
#  ModuleName: Name of the module. It should be the same as the file name.
#  TestNames: List of names for tests for that file
function(create_file_tests MODULE_NAME MODULE_TESTS)
foreach (SINGLE_TEST ${MODULE_TESTS})
  message (STATUS ""Adding test DataTest.${MODULE_NAME}.${SINGLE_TEST}"")
  add_test(NAME ""DataTest.${MODULE_NAME}.${SINGLE_TEST}"" COMMAND ${PROJECT_NAME} --run_test=${MODULE_NAME}/${SINGLE_TEST} --catch_system_error=yes)
endforeach(SINGLE_TEST)
endfunction(create_file_tests)

# Creating tests for every file
set (MODULE_NAME IconTest)
set (MODULE_TESTS Constructor)
create_file_tests(${MODULE_NAME} ""${MODULE_TESTS}"")

set (MODULE_NAME AttitudeTest)
set (MODULE_TESTS DefaultConstructor ValueConstructor SetRoll SetPitch SetYaw)
create_file_tests(${MODULE_NAME} ""${MODULE_TESTS}"")

set (MODULE_NAME LLATest)
set (MODULE_TESTS DefaultConstructor ValueConstructor SetLatitude SetLongitude SetAltitude)
create_file_tests(${MODULE_NAME} ""${MODULE_TESTS}"")

set (MODULE_NAME Model3DTest)
set (MODULE_TESTS Constructor)
create_file_tests(${MODULE_NAME} ""${MODULE_TESTS}"")

set (MODULE_NAME PlayerTest)
set (MODULE_TESTS DefaultConstructor SetLLA01 SetLLA02)
create_file_tests(${MODULE_NAME} ""${MODULE_TESTS}"")

set (MODULE_NAME TimeDateTest)
set (MODULE_TESTS DefaultConstructor)
create_file_tests(${MODULE_NAME} ""${MODULE_TESTS}"")

target_link_libraries (${PROJECT_NAME} data ${Boost_LIBRARIES})
target_compile_features (${PROJECT_NAME} PUBLIC cxx_std_17)
</code></pre>

<p>I define the <code>BOOST_TEST_MODULE</code> in file <code>stdafx.cpp</code>:</p>

<pre><code>#define BOOST_TEST_MODULE DataTest

#include ""stdafx.hpp""
</code></pre>

<p>And then I define the name of test suite in test files, for example:</p>

<pre><code>#include ""stdafx.hpp""
#include ""Data/LLA.hpp""

BOOST_AUTO_TEST_SUITE(LLATest);

BOOST_AUTO_TEST_CASE(DefaultConstructor) {
  Data::LLA lla;
  BOOST_CHECK_EQUAL(lla.getLatitude(), 0.0);
  BOOST_CHECK_EQUAL(lla.getLongitude(), 0.0);
  BOOST_CHECK_EQUAL(lla.getAltitude(), 0.0);
}

BOOST_AUTO_TEST_CASE(ValueConstructor) {
  double lat{ 0.3 };
  double lon{ 0.5 };
  double alt{ 93 };
  Data::LLA lla(lat, lon, alt);
  BOOST_CHECK_EQUAL(lla.getLatitude(), lat);
  BOOST_CHECK_EQUAL(lla.getLongitude(), lon);
  BOOST_CHECK_EQUAL(lla.getAltitude(), alt);
}

BOOST_AUTO_TEST_CASE(SetLatitude) {
  Data::LLA lla;
  double angle{ 0.5 };
  lla.setLatitude(angle);
  BOOST_CHECK_EQUAL(lla.getLatitude(), angle);
  BOOST_CHECK_EQUAL(lla.getLongitude(), 0.0);
  BOOST_CHECK_EQUAL(lla.getAltitude(), 0.0);
}

BOOST_AUTO_TEST_CASE(SetLongitude) {
  Data::LLA lla;
  double angle{ 0.5 };
  lla.setLongitude(angle);
  BOOST_CHECK_EQUAL(lla.getLatitude(), 0.0);
  BOOST_CHECK_EQUAL(lla.getLongitude(), angle);
  BOOST_CHECK_EQUAL(lla.getAltitude(), 0.0);
}

BOOST_AUTO_TEST_CASE(SetAltitude) {
  Data::LLA lla;
  double altitude{ 0.5 };
  lla.setAltitude(altitude);
  BOOST_CHECK_EQUAL(lla.getLatitude(), 0.0);
  BOOST_CHECK_EQUAL(lla.getLongitude(), 0.0);
  BOOST_CHECK_EQUAL(lla.getAltitude(), altitude);
}

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

<p>What I can see is that the Test explorer windows works, but not too well.</p>

<p>Even if I can see and run tests from Test explorer, I can't see them in the proper way, since <code>Class Name</code> and <code>Namespace</code> fields are not defined, like in following screenshot:</p>

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

<p>So, I'd like to know how can I fill the namespace and class name fields in the proper way. What I'm doing wrong?</p>
",https://stackoverflow.com/questions/57337134/cannot-see-boost-unit-test-namespace-and-class-names-in-visual-studio-test-explo,"['visual-studio', 'unit-testing', 'cmake', 'visual-studio-2019', 'boost-test']",684,False,7,0
How do I fake the return of a built-in method in C# unit test?,"<p>I have a public static method that uses an object of Random class to generate an integer. The integer is then made the index of a List. I want to test the logic of the method while having control over what a random object's Next method returns.</p>

<pre class=""lang-cs prettyprint-override""><code>public class RandomGenerator
  {

    // a static method which produces a random selection from a List
    public static string GetRandomListMember(List&lt;string&gt; anyStringList)
    {
      Random rand = new Random();
      int randomInt = rand.Next(anyStringList.Count);
      return anyStringList[randomInt];
    }
  }
</code></pre>

<p>From my MSTest file:</p>

<pre class=""lang-cs prettyprint-override""><code>[TestClass]
  public class RandomGeneratorSpec
  {
    [TestMethod]
    public void GetRandomListMember_ListOfStrings()
    {
      List&lt;string&gt; strings = new List&lt;string&gt; { ""red"", ""yellow"", ""green"" }; 

      Mock&lt;Random&gt; mockRandom = new Mock&lt;Random&gt;();
      mockRandom.Setup(rand =&gt; rand.Next(strings.Count)).Returns(() =&gt; 2); // 2!

      string result = RandomGenerator.GetRandomListMember(strings);

      Assert.AreEqual(""green"", result);
    }
  }
</code></pre>

<p>I want mockRandom.Next to return 2 every time it runs in this test. Obviously, this isn't the way to do it. I've been searching through examples, but they all seem to utilize methods on the object and with instance methods instead of static methods.</p>

<p>How do I control what a built-in method returns while unit testing a method that utilizes it?</p>
",https://stackoverflow.com/questions/58176256/how-do-i-fake-the-return-of-a-built-in-method-in-c-unit-test,"['c#', 'unit-testing', 'testing', 'tdd', 'moq']",2155,True,2,3
Setting Up Gmock to QT (Windows),"<p>I'm trying unit testing using QT Creator. I tried doing it with linux and it works really fine, but when I start doing it in Windows. I discover the setting up is way different than what I did to linux. </p>

<p>Right now in my Windows QT Creator, I already set up gtest to my project. Everything is working fine until I started to set up googlemock. Can someone tell me how to set up googlemock in QT Creator? (windows)</p>

<p>I added some gmock files in the sources in my .pro file just like what I did to the gtest files. Also, I already add some library like libgmock.a and libgmock_main.a.</p>

<p>Here's the image of the issue results Qt</p>

<p><img src=""https://i.stack.imgur.com/ZMdz0.png"" alt=""""></p>

<pre><code>INCLUDEPATH += ""gtest/include/""
INCLUDEPATH += ""gtest/""
INCLUDEPATH += ""../../""
INCLUDEPATH += ""gmock/include/gmock/""
INCLUDEPATH += ""gmock/include/""
INCLUDEPATH += ""gmock/""
INCLUDEPATH += ""../../""
FORMS += \
    ../calculator.ui
HEADERS += \
    ../calculator.h \
    ../button.h
SOURCES += \
    ../calculator.cpp \
    ../button.cpp \
    main.cpp \
    gtest/src/gtest-typed-test.cc \
    gtest/src/gtest-test-part.cc \
    gtest/src/gtest-printers.cc \
    gtest/src/gtest-port.cc \
    gtest/src/gtest-filepath.cc \
    gtest/src/gtest-death-test.cc \
    gtest/src/gtest-all.cc \
    gtest/src/gtest.cc \
    gmock/src/gmock-spec-builders.cc \
    gmock/src/gmock-matchers.cc \
    gmock/src/gmock-cardinalities.cc \
    gmock/src/gmock-all.cc \
    gmock/src/gmock.cc \
    gmock/src/gmock-internal-utils.cc
win32:CONFIG(release, debug|release): LIBS += -L$$PWD/../../../Gmock_lib/ -lgmock_main
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/../../../Gmock_lib/ -lgmock_maind
else:unix: LIBS += -L$$PWD/../../../Gmock_lib/ -lgmock_main
INCLUDEPATH += $$PWD/../../../Gmock_lib
DEPENDPATH += $$PWD/../../../Gmock_lib
win32:CONFIG(release, debug|release): LIBS += -L$$PWD/../../../Gmock_lib/ -lgmock
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/../../../Gmock_lib/ -lgmockd
else:unix: LIBS += -L$$PWD/../../../Gmock_lib/ -lgmock
INCLUDEPATH += $$PWD/../../../Gmock_lib
DEPENDPATH += $$PWD/../../../Gmock_lib
</code></pre>

<p>main.cpp</p>

<pre><code>#include &lt;gtest/gtest.h&gt;
#include &lt;QApplication&gt;
#include ""Calculator/calculator.h""
#include ""Calculator/button.h""
#include ""Calculator/calculator.h""
#include &lt;gmock/gmock.h&gt;



TEST (sumInMemory, clearMemoryF) {
    calculator cal;
    double x = cal.sumInMemory;
       EXPECT_EQ( x , 0.0);
}

TEST (functionTest, Subtest1) {
    calculator cal;
   int x = cal.equalClicked();

   EXPECT_NE( x , -1);
}

TEST (functionTest, Subtest2) {
    calculator cal;
   double x = cal.factorSoFar;

   EXPECT_EQ( x , 0.0);
}


int main (int argc, char *argv[])
{
    QApplication a(argc, argv);
    ::testing::InitGoogleTest(&amp;argc, argv);
            return RUN_ALL_TESTS();
}
</code></pre>
",https://stackoverflow.com/questions/56983270/setting-up-gmock-to-qt-windows,"['qt', 'googlemock']",387,True,2,2
Mocking current_app in Flask unit pytest,"<p>I want to unit test following function:</p>

<pre><code>from flask import current_app

def fuu():
    current_app.logger.info('hello world')
    any = current_app.config['any']
</code></pre>

<p>Without any special context handling I receive following error message:</p>

<pre><code>E           This typically means that you attempted to use functionality that needed
E           to interface with the current application object in some way. To solve
E           this, set up an application context with app.app_context().  See the
E           documentation for more information.
</code></pre>

<p>After reading about Flask context, I came up with a <em>working</em> solution:</p>

<pre><code>@classmethod
def setUpClass(cls):
    app = app_factory.create_app()
    ctx = app.app_context()
    ctx.push()
    cls.app = app
</code></pre>

<p>But the point is that I do not want to deal with any flask contexts in <strong>UNIT tests</strong>. I want to have a plain unit test, in which all collaborators can be mocked, so that the <em>system under test</em> just deals with mocked instance, in this case for <code>current_app</code> as well. 
Having flask context is pretty fine for integration testing, but not for unit testing.</p>

<p>I am searching for something similar like this:</p>

<pre><code> @patch('flask.current_app')
</code></pre>

<p>Is there any way to achieve this?</p>

<p><strong>EDIT #1</strong></p>

<p>@Gabriel C</p>

<p>service.py</p>

<pre><code>from flask import current_app

def fuu():
    current_app.logger.info('hello world')
</code></pre>

<p>service_test.py</p>

<pre><code>import unittest
from unittest.mock import patch

class TestService(unittest.TestCase):

@patch('flask.current_app')
def test_generate_image_happy_path(self, mock):
    from service import fuu
    fuu()
    assert 1 == 1
</code></pre>

<p>This fails for the same exact reason:</p>

<pre><code>E           RuntimeError: Working outside of application context.
</code></pre>
",https://stackoverflow.com/questions/57947935/mocking-current-app-in-flask-unit-pytest,"['unit-testing', 'flask', 'mocking', 'pytest']",5641,True,7,2
How to get Hibernate Envers with Spring integration testing?,"<p><strong>Is there some way to get Hibernate Envers to run <em>immediately</em> on the call to save or update instead of going at the end of the transaction ?</strong></p>

<p>I have a <code>@Transactional</code> annotation on my (effectively end-to-end test). Since the code doesn't contain test methods I'm unable to put ""flush"" or whatever in it, (short of editing non-test code, which is not the desire). </p>

<p><strong>I'm not sure how to get Envers log working on the calls. I need it to work  as I'm using the Envers audit tables to check old entries at runtime, and would like to create test cases for this functionality.</strong> </p>

<p>I have the following code for unit testing :</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(""/src/webapp"")
@EnableWebMvc
@Transactional
@TestPropertySource(locations= {""classpath:/config/common.properties""}, properties = {""...""})
@ContextConfiguration(locations = {""...""})
public class Test {
    @Autowired
    private WebApplicationContext wac;

    @Autowired
    private UserDetailsService detailsService;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
            .build();
    }

    ...
}
</code></pre>
",https://stackoverflow.com/questions/58199711/how-to-get-hibernate-envers-with-spring-integration-testing,"['spring', 'hibernate', 'hibernate-envers']",706,False,2,0
How do you access the data returned by a controller when run in unit tests?,"<p>I have a Asp .net core 2.2 web api.  I am trying to set up unit testing on a number of the controllers.   I have it working to he point where it does call the controller</p>

<p><strong>Controller</strong></p>

<pre><code>[HttpGet(""list"")]
public ActionResult Get([FromQuery] string q = null)
    {
        if (q != null)
            return Ok(new ClientListResponse(ClientHelper.FindClientByClientIdOrClientName(_configurationDbContext.Clients, q)));

        return Ok(new ClientListResponse(_configurationDbContext.Clients.ToList()));
    }
</code></pre>

<p><strong>Test calling it</strong></p>

<pre><code>var allClients = controller.Get();  
</code></pre>

<p><strong>Issue</strong></p>

<p>Now when i look at it in debug everything looks fine. I can see that value contains the correct object being returned.</p>

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

<p>However when it try to access the variables they don't exist.</p>

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

<p>I am suspecting that this has something to do with the response being an ActionResult.  I have tried to convert it to everything i can think of.</p>

<p>How do you access the data returned by a controler when run in unit tests?</p>
",https://stackoverflow.com/questions/54145910/how-do-you-access-the-data-returned-by-a-controller-when-run-in-unit-tests,"['c#', 'unit-testing', 'asp.net-core', 'nunit']",760,True,2,1
Mocking the AWS SDK in Golang?,"<p>I am in a situation where I need to mock elements of the Lambda, API Gateway and S3 SDK packages for unit testing.</p>
<p>I initially thought this wouldn't be such a bad idea but right now having to implement some in-memory data storage and mimic the entire AWS logic for those services seems impossible (or at least really time consuming).</p>
<p>So basically my mock-implementation looks something like this</p>
<pre><code>package awsmock

type Lambda struct {
    lambda.Lambda
    data map[string]*LambdaFunction
}

func (svc *Lambda) CreateFunction(...) (...) {
    // mimic the AWS logic but save to svc.data
}

// etc
</code></pre>
<p>Is there any better way you could think of when it comes to mocking AWS SDK? If there isn't, I could write a library and post it on Github so other can use it and improve it too, but I hope I can manage without reimplementing this.</p>
",https://stackoverflow.com/questions/54872392/mocking-the-aws-sdk-in-golang,"['amazon-web-services', 'go', 'mocking', 'aws-sdk', 'aws-sdk-go']",2449,False,2,0
__attribute__((weak) ) function result in undefined reference,"<p>I am currently trying to set up CMock for unit testing the STM32 using MinGW and CMake. In my config file, I set the :weak: option so that the generated mock would give me weak functions. One example is:</p>

<pre><code>#if defined (__IAR_SYSTEMS_ICC__)
#pragma weak HAL_TIM_IC_Init
#else
HAL_StatusTypeDef  __attribute__((weak)) HAL_TIM_IC_Init(TIM_HandleTypeDef* htim);
#endif

HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef* htim)
{
  ...
}
</code></pre>

<p>However, when I compile, it gives me undefined reference to HAL_TIM_IC_Init error.</p>

<p>If I remove the <code>weak</code> attributes, then it would not give me the undefined reference error. But because I need to override some function provided by the HAL layer, I need to make the mocked library as weak, otherwise it will give me multiple definition errors.</p>

<p>So my question is why the weak attribute caused the undefined reference error and how can I work around it? </p>
",https://stackoverflow.com/questions/55240919/attribute-weak-function-result-in-undefined-reference,"['c', 'stm32', 'weak-linking', 'cmock']",872,True,2,1
Python unit testing: psycopg2 query coverage,"<p>We're doing unit testing via the usual unittest module of python. This works very well with coverage, but it does not really help to find out if queries are tested well. Is there any tool to collect coverage information for queries used in psycopg2? Some of our queries are quite complex and as such can have multiple paths, depending on the data that is currently in the database.</p>

<p>I'd split up the queries, but that would have a bigger performance impact, as the query planner will not be able to optimize as well as in a single query.</p>

<p>[TL;DR]: Is there any tool to collect coverage information for queries used in psycopg2?</p>
",https://stackoverflow.com/questions/59323586/python-unit-testing-psycopg2-query-coverage,"['python', 'unit-testing', 'code-coverage', 'psycopg2']",104,False,1,0
Mocking interface doesn&#39;t make sense?,"<p>I am new to unit testing and it feels like I am missing something really big here. I would like to test the result of DoSomethingWithArray below:</p>

<pre><code>class Traffic:ITraffic
{
    private HugeArray _hugeArray;
    public Traffic(HugeArray hugeArray)
    {
        _hugeArray = hugeArray;

    }

    public int DoSomethingWithArray()
    {
        var ret = 0;
        //Here some code that does something with big array and stores some integer values in ret
        return ret;
    }
}

class HugeArray
{
    //This is my custom data structure;
}

interface ITraffic
{
    int DoSomethingWithArray();
}
</code></pre>

<p>I am using Nunit and from what i read it's better to mock interfaces than to mock classes. My problem is that what I'd like to test is the CONCRETE functioning of DosomethingWithArray in the class Traffic, I am having a hard time conceptualizing how the interface ITraffic can fit in.
What am i missing here ?</p>

<p><strong>EDIT</strong> Here is how I would test my class</p>

<pre><code>[TestFixture]
public class TrafficTests
{
    private Traffic _traffic;
    private const int size = 1000000;
    private const int key = 1851925790;

    [OneTimeSetUp]
    public void Setup()
    {
        var hugeArray = new HugeArray(size);
        //Some Setups to create an edge case, not  relevant to my question
        hugeArray.AddValue(size - 1, Int.MaxValue);
        hugeArray.AddValue(size - 2, key);
        //This is the object I want to test, 
        _traffic = new Traffic(hugeArray);
    }

    [Test]
    public void DoSomethingWithArray_Test()
    {
        Assert.DoesNotThrow(() =&gt;
                            {
                                var ret = _traffic.DoSomethingWithArray();
                                Assert.AreEqual(ret, 233398);
                            });
    }



} 
</code></pre>

<p>my question is: Does this approach seem correct? is the object created for the the test okay or should i mock the interface ITraffic instead ? </p>
",https://stackoverflow.com/questions/56636861/mocking-interface-doesnt-make-sense,"['c#', 'unit-testing', 'nunit']",61,True,1,1
How should I unit test a method that contains GET calls to external services,"<p>I am coding unit tests in my Go API with Gin Gonic. </p>

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

<pre><code>func getKeys(c *gin.Context) {
    var meters []models.Meter

    metadataOperation, err := metadata.GetOperation(""AC123456"")
    if err != nil {
        sendInternalError(err, c)
        return
    }
    meter, err := metadata.GetMeter(""12345"")
    // Other instructions
    // ...
    // operation = ...
    c.JSON(http.StatusOK, operation)
}
</code></pre>

<p>Here is GetOperation method:</p>

<pre><code>func GetOperation(operationID string) (Operation, error) {
    var operation Operation
    var url = metadataAPIURL + ""/v2/operations/"" + operationID
    tr := &amp;http.Transport{
        TLSClientConfig: &amp;tls.Config{InsecureSkipVerify: true},
    }
    client := &amp;http.Client{Transport: tr}
    req, err := http.NewRequest(""GET"", url, nil)

    if err != nil {
        return Operation{}, err
    }
    req.SetBasicAuth(metadataAPIUser, metadataAPIPassword)
    res, err := client.Do(req)
    if err != nil {
        return Operation{}, err
    }
    if res.StatusCode != 200 {
        return Operation{}, errors.New(res.Status)
    }
    err = json.NewDecoder(res.Body).Decode(&amp;operation)
    if err != nil {
        return Operation{}, err
    }
    return operation, nil
}
</code></pre>

<p>Thing is <code>metadata.GetOperation(""AC123456"")</code> will make a GET request to an external service.</p>

<p>As I understand unit testing, I can't have any external dependencies. </p>

<p>In my case, test is passing, but it is making a GET request to my production server which is not the wanted result.</p>

<p>If I want to use mocks, I should have an interface, and switch between dependency, and mock.</p>

<p>It should be great to test <code>GetOperation</code> method, but for <code>getKeys</code> method, it seems unclear to me how should I do it.</p>

<p>How should I deal with this situation? Can anyone give me an example / tuto about this case.</p>
",https://stackoverflow.com/questions/58990417/how-should-i-unit-test-a-method-that-contains-get-calls-to-external-services,"['unit-testing', 'go', 'testing', 'mocking']",926,True,1,2
"Boost unit test fixture inheriting test class, to have access to protected methods?","<p>I have worked with Google Test/GTest previously, which I am sure allowed your text fixture class to inherit the class you were testing, so it could have access to the protected methods of the class being tested (without them needing to be exposed as public).</p>

<p>I am trying to achieve the same thing with Boost unit test, but it won't allow me to access a protected method (even though my test fixture class inherits from the class being tested).</p>

<p>Is there a way for test fixture classes to access protected methods of classes being tested in Boost Test? If not, what is the best way to expose private/protected methods for unit testing?</p>
",https://stackoverflow.com/questions/54134664/boost-unit-test-fixture-inheriting-test-class-to-have-access-to-protected-metho,"['c++', 'boost', 'googletest', 'boost-test']",755,True,1,1
Functional testing with Golang,"<p>I have a webservice written in Golang.</p>

<p>I need to refactor it because it is poorly written. </p>

<p>I have seen Golang works with the format <code>TestMethodName(t *testing.T)</code>. This is great for unit testing, but in my case, methods will change a lot because of the refactoring.</p>

<p>That's why I want to write functional testing, so that I can test each endpoint, and check that output has correct format, without being dependant of functions</p>

<p>How should I do it with Golang ?</p>

<p>Is there any framework that helps me with functional tests ? In another stack, like PHP / Laravel for instance, I can swap PostgreSQL with a SQLite, or In Memory testing, which is very practical for this kind of tests.</p>
",https://stackoverflow.com/questions/55954042/functional-testing-with-golang,"['go', 'testing', 'functional-testing']",4208,True,1,1
Disable @CreationTimestamp in testing class,"<p>So I'm using Hibernate's annotations <code>@CreationTimestamp</code> and <code>@UpdateTimestamp</code>. It works fine, but I have this case when unit testing where I need to create objects in specific dates. </p>

<p>I think it is not possible to deactivate this annotations so the first thing I thought was remove them and do something like this:</p>

<pre><code>@PrePersist
public void prePersist() {
    if (createdDate == null) {
        createdDate = new Date();
    }
}
</code></pre>

<p>I don't like it this way because I'll have to do a refactor of my entities just for one test case.</p>

<p>The other solution I think it can be better is to create an sql file with the data I need and execute it with Spring before when running my tests.</p>

<p>What do you think is the best way to do this?</p>
",https://stackoverflow.com/questions/58642218/disable-creationtimestamp-in-testing-class,"['java', 'spring', 'hibernate']",1468,True,1,3
How to generically handle test assertions,"<p>I would like to log all assertions when unit testing  without being too code intrusive.
Ideally I would like a way to hook any test assertion like Assert.IsTrue and if it fails then log the assertion and message to my application's log (using log4net).</p>

<p>Logging is especially useful in parallel testing scenarios. Unless I used a try catch throw for each test I cant see a way to do it - too much code bloat?</p>

<p>I am sure many people have a similar requirement.
I am using the latest Visual Studio 17 and Resharper
MSTestV2 test framework and adaptor v1.4.0.
Any ideas? Am I missing the obvious?</p>

<p>Thanks in advance
Kind regards
Terry</p>
",https://stackoverflow.com/questions/54212006/how-to-generically-handle-test-assertions,"['c#', 'unit-testing', 'visual-studio-2017', 'mstest']",68,False,1,1
Should unit tests tests the functionality of a method?,"<p>I am writing unit tests but the part that confuses me most is whether it should test the functionality or not?</p>

<p>For example, if there is a method which does two things </p>

<ol>
<li>Deletes files from a folder</li>
<li>Returns whether the folder is empty or not</li>
</ol>

<pre><code>public bool DeleteFTPFiles(string xyz)
{
    ...

    path = GetFTPPath(xyz);
    DeleteFolderFiles(path);
    return IsFtpFolderEmpty(path);
}
</code></pre>

<p><code>DeleteFolderFiles</code> - deletes files based on some logic. </p>

<p>Now, if I have to do unit testing for this method(<code>DeleteFTPFiles</code>). 
Do I have to create folder structure and add some files through my unit tests as an Arrange test?</p>

<p>Assert whether files are deleted based on the condition?</p>

<p>Also, test if <code>IsFtpFolderEmpty</code> returns true or false based on whether it is empty or not?</p>

<p>If so, how is this different from Integration tests?</p>
",https://stackoverflow.com/questions/56121144/should-unit-tests-tests-the-functionality-of-a-method,"['c#', 'unit-testing', 'testing', 'automated-tests']",138,True,1,2
cannot read &#39;pipe&#39; of undefined,"<p>i am trying to do unit test for a component in angular. i am new to the unit testing and i am currently facing the below issue</p>

<p>My component has select statement as follows:</p>

<pre><code>this.store.select(getInfo)
    .pipe(takeWhile(() =&gt; this.isLive)
    )
    .subscribe((data) =&gt; {
      this.text = data;

    }); 
</code></pre>

<p>My unit test case is written as follows:</p>

<pre><code>fdescribe(‘TestComponent', () =&gt; {
  let component: TestComponent;
  let fixture: ComponentFixture&lt;TestComponent&gt;; 

  const testStore = jasmine.createSpyObj('Store', ['select']);

  beforeEach(async(() =&gt; {

    TestBed.configureTestingModule({
      declarations: [TestComponent
        ],
      imports: [MaterialModule, FiltersModule],
      providers: [
        {provide: Store, useValue: testStore }],

      schemas: [NO_ERRORS_SCHEMA]
    })

      .compileComponents();
  }));

  beforeEach(() =&gt; {


    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  });

  it('should create Test component', async() =&gt; {
    let initialState = {
         data: {
    “name: “xyz”,
    “age” : 20

    } , 
      info: [1]
    };

    testStore.select.and.returnValues(

       of(initialState.info)
     );
     fixture.detectChanges();
     await fixture.whenStable();
    expect(component).toBeTruthy();
  });
  it('should have at least 1 info’, async() =&gt; {
    let initialState = {
         data: {
    “name: “xyz”,
    “age” : 20

    } , 
      info: [1]
    };

    testStore.select.and.returnValues(

       of(initialState.info)
     );

    fixture.detectChanges();
    await fixture.whenStable();

    console.log(""text is "",component.text);
    });

});
</code></pre>

<p>this is a very naive test. i am just trying to get the basic idea before proceeding to write more complex tests. 
So ,the issue here i am facing is . it prompts me an error saying:
TypeError: Cannot read property 'pipe' of undefined and this happens only for the ''should create Test component' testcase . the other testcase logs in the message as expected.</p>

<p>I am unable to understand where am i going wrong.</p>
",https://stackoverflow.com/questions/58088077/cannot-read-pipe-of-undefined,"['angular', 'typescript', 'karma-jasmine']",719,True,1,1
How to write Integration Tests for MEAN application,"<p>Currently, I'm creating a project that incorporates the MEAN stack, Docker, and Travis CI. I'm using Travis CI to automate builds for unit testing, integration testing, etc. I'm using Docker to help create a test environment. I've already successfully created unit tests thanks to resources via Medium. However, I haven't found many resources on writing integration tests for a MEAN application. I want to create tests to see if I get expected values in the Angular application when it connects to the REST API endpoints from Express, and the Express application is connected to a MongoDB server. Does anyone have any resources or advice on how to write these tests, and to execute them in a Dockerized test environment?</p>
",https://stackoverflow.com/questions/54030604/how-to-write-integration-tests-for-mean-application,"['mongodb', 'docker', 'express', 'continuous-integration', 'mean']",36,True,1,1
Dynamic testing for any camunda bpmn process,"<p>I am working on a Camunda java code and i am looking for a testing methodology that i can use to test any of my bpmn processes.</p>

<p>i have made some google search and i found on Camunda documentation some ideas about unit testing but it is do test for a specific bpmn model .
i need one to test any bpmn model (just by passing name of bpmn file and id of process etc) 
the strategy should take into account the integration with DB to get candidate (user&amp;group) for any expected path.i know maybe i can't do that but i have a large model and it will be time waste to test all of it in traditional ways.</p>
",https://stackoverflow.com/questions/57075027/dynamic-testing-for-any-camunda-bpmn-process,"['testing', 'bpmn', 'camunda']",954,True,1,1
"How to add classes in my unit test, referencing doesn&#39;t give access","<p>I'm a newbie trying to work out a small issue in Visual Studio 2019...</p>

<p>When i create a new project for unit testing in Visual Studio, I'm right clicking reference in solution manager and selecting my main project in the reference manager, which then populates my references with the correct project.
However i don't have access to the main projects classes, I can't call any of the methods etc.</p>

<p>I have checked my access specifiers are all public... 
I have tried adding using projectName; just to see...</p>

<p>I am following a old course so maybe somethings changed but I've gone over the content quite a few times and I'm stumped...</p>

<p>Thanks for any assistance</p>
",https://stackoverflow.com/questions/59252138/how-to-add-classes-in-my-unit-test-referencing-doesnt-give-access,"['c#', 'unit-testing', 'visual-studio-2019']",166,False,1,0
How to properly unit test code inside of a Python function,"<p>How can I unit test variables/values that are inside a function?</p>

<p>This is a rather basic question about unit testing (I am using pytest) that is I want to make sure all my code behaves as expected.</p>

<p>There must be a proper way to do that, but I didn't find out. As of yet, I try to split up my code in as many functions as possible to get as many return values as possible that I can test. But I am not able to test inside those functions.</p>

<p>Here I can only test if the return value <code>interp_function</code> is working as expected, but in no way to test the rest of the code.</p>

<pre><code>def multidim_interp_function(grid = None, max_error_in_mm=1,
                         max_error_in_deg=1):

    def interp_function(array_of_pts):
        fct_list = create_interp(grid)
        max_error = [max_error_in_mm]*3
        if len(grid) == 6:
            max_error.extend([max_error_in_deg]*3)
    return np.column_stack([error*fct_list[i](array_of_pts) for i,error in enumerate(max_error)])

return interp_function
</code></pre>
",https://stackoverflow.com/questions/58788214/how-to-properly-unit-test-code-inside-of-a-python-function,"['python', 'unit-testing', 'pytest']",1851,True,1,2
Jest encountered an unexpected token SyntaxError: Unexpected token {,"<p>Hi I am using jest + enzyme for unit testing of reactjs application and having my company owned libraries in JavaScript(ES6) as node_modules, while transforming these node_modules, it is throwing below error 
<a href=""https://i.stack.imgur.com/Sxp3Y.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Sxp3Y.png"" alt=""enter image description here""></a>
<a href=""https://i.stack.imgur.com/wHNOp.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/wHNOp.png"" alt=""enter image description here""></a>
It is throwing error at import ""{""</p>

<p>I am using below as jest transformer: 
<a href=""https://i.stack.imgur.com/6juZj.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/6juZj.png"" alt=""enter image description here""></a></p>

<p>I am using as below jest config:
<a href=""https://i.stack.imgur.com/HdWGI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/HdWGI.png"" alt=""enter image description here""></a></p>

<p>Below is my babel.config.js:
<a href=""https://i.stack.imgur.com/U0Agc.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/U0Agc.png"" alt=""enter image description here""></a>
And below are my dependencies: 
  ""babel-core"": ""7.0.0-bridge.0"",
 ""@babel/core"": ""^7.2.2"",
  ""@babel/preset-env"": ""^7.3.1"",
    ""@babel/preset-react"": ""^7.0.0"",
    ""@babel/preset-typescript"": ""^7.1.0"",
 ""babel-jest"": ""^23.6.0"",
    ""babel-loader"": ""^7.1.5"",
  ""enzyme"": ""^3.3.0"",
""jest"": ""^23.6.0"",
""ts-jest"": ""23.10.5"",</p>

<p>Please do let me know if I am missing anything or what babel plugin/preset is required to get rid of this error.</p>
",https://stackoverflow.com/questions/54624009/jest-encountered-an-unexpected-token-syntaxerror-unexpected-token,"['reactjs', 'unit-testing', 'jestjs', 'babeljs', 'enzyme']",1181,False,0,0
Why I can&#39;t create Mock in Laravel,"<p>Last days I work on Unit Testing in PHP Laravel. I am very new in tests, but I generaly read about how they should be make... but in fact I can't write it properly. Still got some errors. Here is my class ( method ) I want to test ( mock ):</p>

<pre><code>class ApiHelper
{
    private $model_locations;

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

    public function calcAllDistances(string $location)
    {
        $request_data = $this-&gt;validLatLong($location);
        if(!$request_data) {
            return null;
        }
        $user_lat = $request_data[0];
        $user_lng = $request_data[1];
        $all_locations = $this-&gt;model_locations::all()-&gt;toArray();
        $all_distances = [];

        foreach($all_locations as $single_location) {
            $point = new \stdClass;
            $point_lat = $single_location['lat'];
            $point_lng = $single_location['lng'];
            $distance = $this-&gt;calcDistance($user_lat,$user_lng,$point_lat,$point_lng);
            $point-&gt;name = $single_location['name'];
            $point-&gt;lat = $point_lat;
            $point-&gt;lng = $point_lng;
            $point-&gt;distance = $distance;
            array_push($all_distances,$point);
        }

        return $all_distances;
    }
</code></pre>

<p>We mock <code>calcAllDistances()</code> method.</p>

<p>Here is my test example;</p>

<pre><code>public function testCalcAllDistances()
{
    $double = Mockery::mock(Locations::class)-&gt;shouldReceive('all')-&gt;with('')-&gt;andReturn(5)-&gt;getMock();
    $this-&gt;app-&gt;instance('App\Locations', $double);
    $object_under_tests = new \App\Helpers\ApiHelper($double);

    $result = $object_under_tests-&gt;calcAllDistances('21.132312,21.132312');

    $expected_result = [2.3, 4.7, 8.9];

    $this-&gt;assertEquals($expected_result, $result);
}
</code></pre>

<p>And no matter of what , I still got errors like :</p>

<pre><code>1) Tests\Unit\ApiHelper::testCalcAllDistances
Mockery\Exception\BadMethodCallException: Static method Mockery_0_App_Locations::all() does not exist on this mock object

D:\xampp4\htdocs\api\api\app\Helpers\ApiHelper.php:26
D:\xampp4\htdocs\api\api\tests\Unit\ApiHelperTest.php:41

Caused by
Mockery\Exception\BadMethodCallException: Received Mockery_0_App_Locations::all(), but no expectations were specified
</code></pre>

<p>I swear with my soul, tried everything found in internet.... but I am still unable to write test. Basicly I want to mock Eloquent method all() to return given by me values, to make calcAllDistances() method work. Tried a lot, makePartial() etc but nothing helped me. 
Would be very thankful for help</p>
",https://stackoverflow.com/questions/56958072/why-i-cant-create-mock-in-laravel,"['laravel', 'unit-testing', 'mockery']",502,True,0,1
Unit testing features missing for .NET Core in VS 2019 and Visual Studio Installer?,"<p>I just added a MSTest .NET Core unit test project to a solution in VS 2019 but there now don't appear to be any features for adding a new unit test file to that project.</p>

<h3>Missing Add > Unit test... context menu option</h3>

<p>Steps to reproduce missing context menu issue:</p>

<ul>
<li>In Visual Studio 2019, add a new 'MSTest Project (.NET Core)' project to an existing solution</li>
<li>Right click on the name of the new test project in Solution Explorer</li>
<li>See if the option for 'Add > Unit test...' is present?</li>
</ul>

<p>That option, which was present in earlier versions of VS (and that's still present in VS2019 for full unit test projects targeting the full .NET framework projects) is missing for me:</p>

<p><a href=""https://i.stack.imgur.com/APwgU.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/APwgU.png"" alt=""VS2019 Context menu without &#39;Add &gt; Unit test...&#39; option""></a></p>

<h3>Missing unit test templates</h3>

<p>Steps to reproduce missing unit test template issue:</p>

<ul>
<li>In Visual Studio 2019, add a new 'MSTest Project (.NET Core)' project to an existing solution</li>
<li>Right click on the name of the new test project in Solution Explorer</li>
<li>Select 'Add > New item...' </li>
<li>See if there are any C# related testing options?</li>
</ul>

<p>I'm not seeing any unit test templates whatsoever:
<a href=""https://i.stack.imgur.com/6ALGx.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/6ALGx.png"" alt=""Add New Item dialog filtered for test showing no results""></a></p>

<h3>What I've tried</h3>

<p>I thought the issue might be that I <a href=""https://stackoverflow.com/a/42975299/1879019"">hadn't got the unit testing workload installed</a> for VS2019, but looking at the 'Individual components' option in the Visual Studio Installer for VS2019 the option for 'Testing tools core features' seems to have disappeared too:</p>

<p><a href=""https://i.stack.imgur.com/JJ041.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/JJ041.png"" alt=""VS2019 installer with no test options""></a></p>

<p>These are the same options for VS2017 for comparison:
<a href=""https://i.stack.imgur.com/Nkx41.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/Nkx41.png"" alt=""VS2017 installer showing Testing tools core features option""></a></p>

<p>I know that the 'Create Unit Test' context menu option <a href=""https://stackoverflow.com/q/42876897/1879019"">is not expected to be present in VS2019</a> yet, but to my knowledge the normal unit testing functionality and templates should be there?</p>

<p>(PS: I appreciate I can just write unit tests from scratch, I'm just asking if the functionality in VS has changed)</p>
",https://stackoverflow.com/questions/55703609/unit-testing-features-missing-for-net-core-in-vs-2019-and-visual-studio-install,"['c#', 'unit-testing', '.net-core', 'mstest', 'visual-studio-2019']",5674,False,6,0
Unit test a non returnable function which randomly generates numbers,"<p>Am new in unit testing, I have a function which doesn't return anything and generates numbers randomly from a certain number to another,  I read about the mocking library but it's still confusing to me, how can I unit test this <strong>function</strong>.</p>

<p><strong>What I want to test</strong> </p>

<ol>
<li>Testing if numbers are generated between <code>1000</code> and <code>8876</code>.</li>
<li>Checking the positions of different numbers with a 4 -digit values are not equal to each other. e.g <code>1234</code>, this number is allowed because it has no repetitions. but <code>1123</code> is not allowed because it has a number repeated in different positions. That's what the <code>while</code> loop is doing.</li>
</ol>

<p>I tried to read similar questions e.g <a href=""https://stackoverflow.com/questions/26091330/how-to-validate-a-unit-test-with-random-values"">link 1</a>  <a href=""https://stackoverflow.com/questions/15940389/in-python-how-to-do-unit-test-on-a-function-without-return-value"">link 2</a> but I couldn't connect to this scenario </p>

<pre><code>def num(self): 



                    random = randint(1000, 8876) 

                    random = list(map(int, str(random))) 

                    while random[0] == random[1] or random[0] == random[2] or random[0] == random[3] or random[1] == random[2] or random[1] == random[3] or random[2] == random[3]: 

                            random = randint(1000, 8876) 

                            random = list(map(int, str(random))) 

                    num = """" 

                    self.num = int(num.join(map(str,random))) 
</code></pre>
",https://stackoverflow.com/questions/56312756/unit-test-a-non-returnable-function-which-randomly-generates-numbers,"['python-3.x', 'unit-testing', 'mocking']",75,True,0,2
How to define table loading order with DBIc Schema deploy(),"<p>I am wrapping a database schema using the DBIc Schema to help with unit testing the code.</p>

<p>Based on the original database I used <code>dbidump</code> to to generate the schema from the database:</p>

<pre><code>dbicdump -o dump_directory=./lib -o components='[""InflateColumn::DateTime""]' -o debug=1 Test::Schema 'dbi:mysql:dbname=mcdowall_test' 'test'
</code></pre>

<p>There are 2 InnoDB tables <code>table_a</code> and <code>table_b</code>. The issue is that <code>table_a</code> has a foreign key constraint on table <code>table_b</code>:</p>

<pre><code>CREATE TABLE `table_b` (
  `table_b_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `source_id` INT UNSIGNED NULL,
  PRIMARY KEY (`table_b_id`),
  KEY (`source_id`))
ENGINE = InnoDB;

CREATE TABLE `table_a` (
  `table_a_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `source_id` INT UNSIGNED NULL DEFAULT NULL,
  PRIMARY KEY (`table_a_id`),
  KEY (`table_a_id`),
  CONSTRAINT `fk_ab`
    FOREIGN KEY (`source_id`)
    REFERENCES `table_b` (`source_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;
</code></pre>

<p>This means that the when using <code>deploy()</code> to install the schema during testing it installs the tables in alphabetical order:</p>

<pre><code>use Test::Schema

my $schema = Test::Schema-&gt;connect($dsn, $user, $pass, \%opts);
$schema-&gt;deploy();
</code></pre>

<p>This raises the following SQL error as <code>table_b</code> does not exist when <code>table_a</code> is getting created:</p>

<pre><code>ERROR 1215 (HY000): Cannot add foreign key constraint
</code></pre>

<p>Is there a way to get the <code>deploy()</code> function to either pre-check the foreign key dependencies or specify specific tables to be inserted first?</p>

<p>Ideally <code>table_b</code> should be installed first and then <code>table_a</code>.</p>
",https://stackoverflow.com/questions/54328169/how-to-define-table-loading-order-with-dbic-schema-deploy,"['mysql', 'perl', 'foreign-keys', 'dbix-class']",67,True,0,1
How to write separately business logic in API controller as helper class or handler using interfaces,"<p>I'm developing .net RESTful WebAPI with API controller with actions, using entity framework. </p>

<p>It will auto generate the controller, So I need to write a Business logic in controller(<code>EmployeeDetailController</code>) to helper(<code>EmployeeDetailHandler</code>) class and connect with Interface(<code>IEmployeeDetailHandler</code>). </p>

<p>So need to connect <code>Dbcontext</code> to helper class(<code>EmployeeDetailHandler</code>) without depending on controller to test the unit testing with xunit. </p>

<p>How can i Write Handler class and the controller class?</p>

<p>This is my Controller(API controller with actions, using entity framework). </p>

<p>I need to write the logic inside this in separately on helper class by connecting interface to controller class.</p>

<pre><code>[Route(""api/[controller]"")]
[ApiController]
public class EmployeeDetailController : ControllerBase
{
    private readonly AuthenticationContext _context;

    public EmployeeDetailController(AuthenticationContext context)
    {
        _context = context;
    }

    // GET: api/EmployeeDetail
    [HttpGet]
    public IEnumerable&lt;EmployeeDetail&gt; GetEmployeeDetails()
    {
        return _context.EmployeeDetails;
    }

    // GET: api/EmployeeDetail/5
    [HttpGet(""{id}"")]
    public async Task&lt;IActionResult&gt; GetEmployeeDetail([FromRoute] int id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var employeeDetail = await _context.EmployeeDetails.FindAsync(id);

        if (employeeDetail == null)
        {
            return NotFound();
        }

        return Ok(employeeDetail);
    }

    // PUT: api/EmployeeDetail/5
    [HttpPut(""{id}"")]
    public async Task&lt;IActionResult&gt; PutEmployeeDetail([FromRoute] int id, [FromBody] EmployeeDetail employeeDetail)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != employeeDetail.EId)
        {
            return BadRequest();
        }

        _context.Entry(employeeDetail).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!EmployeeDetailExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

    // POST: api/EmployeeDetail
    [HttpPost]
    public async Task&lt;IActionResult&gt; PostEmployeeDetail([FromBody] EmployeeDetail employeeDetail)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.EmployeeDetails.Add(employeeDetail);
        await _context.SaveChangesAsync();

        return CreatedAtAction(""GetEmployeeDetail"", new { id = employeeDetail.EId }, employeeDetail);
    }

    // DELETE: api/EmployeeDetail/5
    [HttpDelete(""{id}"")]
    public async Task&lt;IActionResult&gt; DeleteEmployeeDetail([FromRoute] int id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var employeeDetail = await _context.EmployeeDetails.FindAsync(id);
        if (employeeDetail == null)
        {
            return NotFound();
        }

        _context.EmployeeDetails.Remove(employeeDetail);
        await _context.SaveChangesAsync();

        return Ok(employeeDetail);
    }

    private bool EmployeeDetailExists(int id)
    {
        return _context.EmployeeDetails.Any(e =&gt; e.EId == id);
    }
  }
</code></pre>

<p>}</p>

<p>This is my Context class</p>

<pre><code>public class AuthenticationContext : IdentityDbContext
{
    public AuthenticationContext(DbContextOptions options):base(options {}
    public DbSet&lt;ApplicationUser&gt; ApplicationUsers { get; set; }
    public DbSet&lt;EmployeeDetail&gt; EmployeeDetails { get; set; }
}
</code></pre>

<p>This is dB Model</p>

<pre><code>public class EmployeeDetail
{
    [Key]
    public int EId { get; set; }
    [Required]
    [Column(TypeName = ""Nvarchar(100)"")]
    public string EmployeeName { get; set; }
    [Required]
    [Column(TypeName = ""Nvarchar(10)"")]
    public string PhoneNo { get; set; }
    [Required]
    [Column(TypeName = ""Nvarchar(10)"")]
    public string BDay { get; set; }
    [Required]
    [Column(TypeName = ""Nvarchar(10)"")]
    public string Nic { get; set; }
}
</code></pre>

<p>Expect is relevant handler class( service/Hepler) with interfaces.</p>
",https://stackoverflow.com/questions/57851474/how-to-write-separately-business-logic-in-api-controller-as-helper-class-or-hand,"['c#', 'entity-framework', 'asp.net-web-api']",900,True,0,1
Execute Find/Update Xunit test cases without using AsNoTracking(),"<p>I am using following Nuget packages in my Unit test project created in .Net core 2.0 application.</p>

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

<p>I have created a InMemory database for Unit Testing.</p>

<p>Whenever I execute a unit test case that includes Update operations , I get an exception </p>

<blockquote>
  <p>""the instance of entity type 'tablename' cannot be tracked because another instance with the same key value for {Id} ia already being tracked.When attaching existing entities,enure that only once entity instance with a  given key value is attached"".</p>
</blockquote>

<p>This is due to <code>FindByAsync</code> method which contains <code>AsNoTracking()</code> method.
Method looks something like as shown below.</p>

<pre><code>public virtual FindByAsync()
{
     Query= Query.AsNoTracking().AsExpandable.().Where(predicate);
}
</code></pre>

<p>When I comment this <code>AsNoTracking()</code> function. The Unit test case succeeds.</p>

<p>Any ideas, suggestions or workarounds that will help me execute failing test cases successfully.</p>
",https://stackoverflow.com/questions/54802140/execute-find-update-xunit-test-cases-without-using-asnotracking,"['c#', 'asp.net-mvc', 'entity-framework', '.net-core']",254,False,0,1
Cannot setup the function with out parameter using lambda expression,"<p>I've found loads of questions to the error message, but not one that matches my specific case.</p>

<p>I have a method with this signature in a cache implementation:</p>

<pre><code>public bool TryGet(TKey key, out TValue returnVal, Func&lt;TKey, TValue&gt; externalFunc = null)
</code></pre>

<p>I have a class derived from that with TKey : CompositeKey and TValue : string.</p>

<p>I'm trying to mock it for unit testing like this:</p>

<pre><code>_cacheMock
    .Setup(x =&gt; x.TryGet(It.IsAny&lt;CompositeKey&gt;(), out It.Ref&lt;string&gt;.IsAny, It.IsAny&lt;Func&lt;CompositeKey, string&gt;&gt;()))
    .Returns((CompositeKey key, out string s, Func&lt;CompositeKey, string&gt; fetchOne) =&gt; { s = """"; return true; });
</code></pre>

<p>I get a compilation error for the <code>.Returns</code> line:    </p>

<blockquote>
  <p>""Cannot convert lambda expression to type 'bool' because it is not a
  delegate type""</p>
</blockquote>

<p>If I remove the ""out"" modifier it compiles OK - but of course doesn't match the signature of the call and I can't get the out value out.</p>

<p>Is there a way to fix the Returns() part of the statement without modifying the TryGet() method itself?</p>
",https://stackoverflow.com/questions/54689844/cannot-setup-the-function-with-out-parameter-using-lambda-expression,"['c#', 'lambda', 'moq']",131,True,0,1
Mock Child Actors Akka Java with Specific Ids,"<p>I am working with <code>Akka 2.5.23</code>. I have a parent actor that <code>forwards</code> a <code>Register Message</code> to a child and the child replies to the <code>original sender</code> with an <code>Initialized message</code>. </p>

<p>I am facing some tough time unit testing this code flow. I am trying to <a href=""https://doc.akka.io/docs/akka/2.5/testing.html#externalize-child-making-from-the-parent"" rel=""nofollow noreferrer"">externalize child creation</a> for the parent but cannot seem to figure out how to pass define the name of the <code>child actor</code> while creating the child actor</p>

<p>Below is my <code>ParentActor</code></p>

<pre><code>public class ParentActor extends AbstractLoggingActor {

    private final Function&lt;ActorRefFactory, ActorRef&gt; childMaker;

    public ParentActor() {
        this.childMaker = arg -&gt; {
            return context().actorOf(ChildActor.props(""ID"", appContext), ""ACTOR_NAME"");
        };
    }

    private void handleRegisterMessage(RegisterMessage message){

        childMaker.apply(context());

        // what I generally do:
        // context().actorOf(ChildActor.props(message.getUniqueId(), ""TransChild-"" + message.getUniqueId());

    }
}
</code></pre>

<p>Below is my <code>ChildActor</code>:</p>

<pre><code>public class ChildActor extends AbstractLoggingActor {

    private final String uniqueId;

    public ChildActor(String uniqueId){
        this.uniqueId = uniqueId;
    }

    public static Props props(String uniqueId) {
        return Props.create(ChildActor.class, uniqueId);
    }
}
</code></pre>

<p>Can anyone help me with this?</p>

<blockquote>
  <p>he Ids are generated based on input message. The parent creates a child actor with a specific id (derived from message). That unique ID is passed to the child via <code>Props</code> and the child on <code>PreStart()</code> performs operations based on the passed uniqueId via Props</p>
</blockquote>
",https://stackoverflow.com/questions/59427544/mock-child-actors-akka-java-with-specific-ids,"['java', 'akka']",64,False,0,2
Can unit/integration tests have no assert? And what about this particular case?,"<p>Scenario: I have some integration tests. One of them tests a delete. So I've done:</p>

<pre><code>@Test
@Order(6)
public void delete() {
    rfxCriteriRepository.delete(rfxCriteriEconomico.getIdrfxcriteri());
}
</code></pre>

<p>to simply test if the method throws no exception. Than, to be sure that the delete is successfull, I've added:</p>

<pre><code>@Test
@Order(7)
public void getDelete() {
    RfxCriteri rfxCriteriEconomicoDb = rfxCriteriRepository.findByIdrfxcriteri(
        rfxCriteriEconomico.getIdrfxcriteri()
    );

    Assertions.assertNull(rfxCriteriEconomicoDb);
}
</code></pre>

<p>My idea is that the first test tests the code. If the code is well written, it should throw no exception, and the test pass. The second test tests that the delete effectively deleted the entry from the database. IMHO they are two separate tests.</p>

<p>Do you think every test must have an <code>assert</code>? Or do you think these two tests should be an unique test? Can someone point me to some guide about unit testing that says something about it?</p>
",https://stackoverflow.com/questions/56056186/can-unit-integration-tests-have-no-assert-and-what-about-this-particular-case,"['unit-testing', 'testing', 'integration-testing', 'assert']",629,True,0,2
Using Jest to write tests for function,"<p>I have a function called <code>addToShoppingList</code> and its job is to add the product a user inputs to a shopping list (currently, just an array). I am working on tests using Jest to check if my function is working, but am currently stuck:</p>

<p>index.js</p>

<pre><code>const fetchData = async (product, numOfProducts) =&gt; {
  const res = await fetch( ... );
  const data = await res.json();
  return data;
};

// user input for products looks like 'butter 2' 
// selecting Breaskstone's butter (from mockData below)
const addToShoppingList = async (product, numOfProducts = 10, getProducts = fetchData) =&gt; {
  const shoppingList = [];

  const item = product.slice(0 ,-2); // i.g. 'butter'
  const i = +product.split(' ').pop() - 1; // i.g. '2' which becomes 1, the index number in array 
  const data = await getProducts(item, numOfProducts);

  // i, which is the index, is used to grab specific item from list of products
  let products = data.items[i].productInfo.name; 
  let manufacturers = data.items[i].productInfo.manufacturer;

  const chosenItem = `${products} from ${manufacturer}`

  shoppingList.push(chosenItem);

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

<p>This isn't great code, but I'm trying to learn how to write tests for the functions above - I am currently using Jest and have this written down so far, but have been getting error messages (which I've been googling and trying to fix). Would love to get tips from unit testing experts on what I'm doing incorrectly:</p>

<p>index.test.js</p>

<pre><code>const mockData = {
  items: [
    {
      productInfo: {
        name: 'Butter',
        manufacturer: 'Land O Lakes'
      },
    },
    {
      productInfo: {
        name: 'Butter',
        manufacturer: 'Breakstone'
      },
    },
    {
      productInfo: {
        name: 'Butter',
        manufacturer: 'Kerrygold',
      },
    }
  ]
};

describe('addToShoppingList', () =&gt; {
  const mockProducts = jest.fn();
  mockGetBooks.mockReturnValue(mockData);

   it('should call fetch with correct arguments', async () =&gt; {
     await addToShoppingList('product 1', 'numOfResults', mockProducts);
     expect(mockProducts).toBeCalledWith('product 1', 'numOfResults');
   });
});
</code></pre>

<p>I would like to test if my <code>addToShoppingList</code> function is working using the <code>mockData</code> I have created above.</p>
",https://stackoverflow.com/questions/58807874/using-jest-to-write-tests-for-function,"['javascript', 'unit-testing', 'jestjs']",182,False,0,1
Good practices for refactoring initialization of a lot of variables in one method,"<p>I am writing a rest controller along with crud service, which will use legacy code, which is still used in different places in application. Its purpose is to export an Excel file.
I am refactoring a bit, in order to have cleaner code (as clean as it is possible in this situation, I don't want to re-write the whole app) and for easier unit testing.</p>

<p>So, let's say, I have a method which calls a lot of services with parameters based on filter (input) and then uses it to generate excel file. What would be a good practice to clean it? </p>

<p>I would appreciate some tips and tricks, as well as, good discussion ;)</p>

<pre><code>    @Override
    public Downloadable&lt;Workbook&gt; getExcel(ExcelFilterTO filter) {

    List&lt;String&gt; someList= someService.getString(filter.getParam1(), filter.getParam2()).stream().collect(toList());

    List&lt;Integer&gt; someList2 = someService.getInt(filter.getParam1(), filter.getParam2(), filter.getParam3(), filter.getParam4());

       TranslationSet translationsSet = translationService.getTranslationsSet(filter.getParam4(),
            TranslationsGroup.SOME_TYPE);

       SomeClass classObject = someService.doSomething(filter.getParam1());

    ...
    ...
    String fileSuffix = ExcelUtils.EXCEL_EXPORT_FILE_NAME_SUFFIX;

    ResourceBundle resourceBundle = ResourceBundle  .getBundle(BundleNames.getBundle(filter.getParam2()).getName());


    Workbook workbook = excelExport.exportExcel(someList, someList2 , fileSuffix, translationsSet, filter.getParam3());

    String fileName = excelExport.getExcelFileName(resourceBundle, someList3, filter.param6(), classObject);

    return new DownloadableResource&lt;&gt;(fileName, XLS.getContentType(), workbook);
    }`
</code></pre>
",https://stackoverflow.com/questions/55496432/good-practices-for-refactoring-initialization-of-a-lot-of-variables-in-one-metho,['java'],147,False,-1,2
Should we modify a function signature for unit testing?,"<p>Suppose we have a function <code>add()</code> as below:</p>

<pre><code>void add(int a, int b) {
    int sum=a+b;
    cout&lt;&lt;sum;
    sendSumToStorage(sum);
}
</code></pre>

<p>This simple function adds to input values, prints the sum to the console and also sends it to some external storage (say, a file).  This is how we ideally want it in the application (meaning, we don't want it to <em>return anything</em>).</p>

<p>For purposes of unit testing, is it valid (from a design perspective) if we modify the function signature so that it returns the <code>sum</code>?  We could then have a test like:</p>

<pre><code>bool checkAdd() {
    int res=add(3, 4);
    if(res==7) return true;
    else return false;
}
</code></pre>

<p>Better yet, is this (<em>returning a value</em>) the only way we could unit test it?  Is there some <em>valid</em> way in which we could unit test the <code>add()</code> function without changing the function signature?</p>
",https://stackoverflow.com/questions/56373047/should-we-modify-a-function-signature-for-unit-testing,"['c++', 'unit-testing', 'testing']",391,True,0,3
Boilerplate Vue Project Fails on router-link and router-view,"<p>I used <code>vue create</code> to create a new view project with Babel, TypeScript, Router and Unit Testing. I then installed axios using npm.</p>

<p>Having done no other changes, I served the application by navigating to the src directory and running <code>vue serve</code>.</p>

<p>The resulting boilerplate application fails to load with the following error:</p>

<blockquote>
  <p>[Vue warn]: Unknown custom element:  - did you register
  the component correctly? For recursive components, make sure to
  provide the ""name"" option.</p>
  
  <p>found in</p>
  
  <p>--->  at App.vue
         </p>
</blockquote>

<p>My own research shows that this error usually happens when you fail to call Vue.Use(). However, my router.ts file does so:</p>

<pre><code>import Vue from 'vue';
import Router from 'vue-router';
import Home from './views/Home.vue';

Vue.use(Router);

export default new Router({   routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () =&gt; import(/* webpackChunkName: ""about"" */ './views/About.vue'),
    },   ], });
</code></pre>

<p>Does anyone know what is wrong here? Given I haven't changed anything, could it be a config issue?</p>
",https://stackoverflow.com/questions/54000527/boilerplate-vue-project-fails-on-router-link-and-router-view,['vue.js'],142,True,0,2
Issues handling Angular error in unit test,"<p>I am still coming up to speed on Angular. I searched and found very little. Most helpful was: <a href=""https://stackoverflow.com/questions/4144686/how-to-write-a-test-which-expects-an-error-to-be-thrown-in-jasmine"">How to write a test which expects an Error to be thrown in Jasmine?</a></p>

<p>Here is my issue after reading the above post.</p>

<p>I am unit testing a method that throws an error. I want to catch the error so that I know that the unit test was successful. Here is my function call:</p>

<pre><code>        expect(function(){instance.selectMember(event);}).toThrow();
</code></pre>

<p>and the line generating the error:</p>

<pre><code>        throw new Error('member not found: ' + member.id);
</code></pre>

<p>What I got was as follows</p>

<pre><code>Expected function to throw an Error.
</code></pre>

<p>Followed by:</p>

<pre><code>Failed: member not found: 42
Error: member not found: 42
</code></pre>

<p>So it failed because it didn't get an error, but then displayed the error???</p>

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

<pre><code>        expect(function(){instance.selectMember(event);}).toThrow(new Error('member not found: 42'));
</code></pre>

<p>and</p>

<pre><code>        expect(function(){instance.selectMember(event);}).toThrowError('member not found: 42');
</code></pre>

<p>with the same results.</p>

<p>How do I know my unit test triggered the error correctly?</p>
",https://stackoverflow.com/questions/58238353/issues-handling-angular-error-in-unit-test,"['angular', 'typescript', 'unit-testing', 'jasmine']",364,True,0,1
Deal with Null object references through Interfaces,"<p>I have an object <code>Foo</code> which I do not own (third-party assembly) and want to pass through an interface <code>IFoo</code>.</p>

<p>Before passing everything via interfaces, I had a <code>Function TryGet(Name As String) as Foo</code>. This function would return <code>Nothing</code> when the name could not be found.</p>

<p>Now refactoring everything into interfaces, I have <code>Function TryGet(Name As String) as IFoo</code>.</p>

<p>The implemenation of <code>IFoo</code> is:</p>

<pre><code>Public Class SuperFoo
    Implements IFoo

    Private ThisFoo As Foo

    Private Sub New()
    End Sub

    Public Sub New(MyFoo As Foo)
        Me.ThisFoo = MyFoo
    End Sub

    Public Property Value As String Implements IFoo.Value
        Get
            Return Me.ThisFoo.Value
        End Get
        Set(value As String)
            Me.ThisFoo.Value = value
        End Set
    End Property

End Class

Class AnotherClass

    Function TryGet(Name as String) as IFoo
        Dim MyFoo as Foo = InitialTryGetFunction(Name)
        Return New SuperFoo(MyFoo)
    End Function

End Class
</code></pre>

<p>So that I maintain my original code logic, I would like to be able to make the reference to the <code>SuperFoo</code> object null when <code>InitialTryGetFunction</code> returns a null reference.</p>

<p>Obviously I could just add some code to <code>If</code> the <code>Return New SuperFoo(MyFoo)</code> statement, but I was wondering if this could be done from the <code>SuperFoo</code> constructor?</p>

<p>Also, am I doing the switch to interfaces (mostly for the purpose of Unit Testing) correctly?</p>
",https://stackoverflow.com/questions/57281137/deal-with-null-object-references-through-interfaces,"['vb.net', 'interface']",44,True,0,2
ANTLR : Tree parsing giving unexpected results,"<p>I'm trying to create my own ANTLR4 grammar so that I can parse some expressions, such as :</p>
<blockquote>
<p><i>STARTS_WITH(this.sequence, &quot;startSeq&quot;)</i></p>
<p><i>ENDS_WITH(&quot;sequenceToTest&quot;, &quot;endSeq&quot;)</i></p>
</blockquote>
<p>(I have a mix of constants and variables as function parameters).</p>
<p>The Lexer and Parser Rules have been created, but when I try to display the function <i>ToStringTree</i>, it seems like the tree is parsed in a wrong way.</p>
<p>I am using Antlr 4 with ASP.Net Core 2.1.</p>
<p><b>The grammar file :</b></p>
<pre><code>grammar expression;

expression : bool_function (OPERATOR bool_function)* ;

bool_function : (FUNCTION_NAME PAR_OPEN parameter (COMMA parameter)* PAR_CLOSE) ;

parameter : constant | current_object_field ;

constant : DOUBLE_QUOTE ANY_BUT_DOUBLE_QUOTE DOUBLE_QUOTE ;

current_object_field : THIS ALPHANUM ;

WHITESPACE : (' ' | '\t' | '\n' |'\r' )+ -&gt; skip ;

COMPARATOR : ('==' | '&lt;=' | '&gt;=' | '&lt;&gt;') ;

OPERATOR : ('&amp;&amp;' | '||') ;

PAR_OPEN : '(' ;

PAR_CLOSE : ')' ;

COMMA : ',' ;

DOLLAR : '$' ;

DOUBLE_QUOTE : '&quot;' ;

THIS : 'this.' ;

NUMBER : [0-9]+ ;

ALPHANUM : [a-zA-Z_0-9]+ ;

ANY_BUT_DOUBLE_QUOTE    : ~('&quot;')+ ;

FUNCTION_NAME : ('STARTS_WITH' | 'ENDS_WITH' | 'CONTAINS' | 'EQUALS') ;
</code></pre>
<p><b>The unit testing, trying to parse one basic expression :</b></p>
<pre><code>        try
        {
            expressionParser expressionParser = Setup(&quot;STARTS_WITH(this.sequence, \&quot;startSeq\&quot;)&quot;);
            expressionParser.ExpressionContext expressionContext = expressionParser.expression();

            var a = expressionContext.ToStringTree(expressionParser);
        }
        catch (Exception e)
        {
            var a = e.Message;
            throw;
        }
</code></pre>
<p>The output I receive for parsing my expression via <i>ToStringTree</i> is the following :</p>
<pre><code>(expression (bool_function STARTS_WITH(this.sequence,  &quot; startSeq &quot; )))
</code></pre>
<p>But I would expect a result, going deeper, such as :</p>
<pre><code>(expression (bool_function STARTS_WITH((parameter(current_objet_field this.sequence)),(parameter(constant &quot;startSeq&quot;)))))
</code></pre>
<p>Are there any obvious mistakes in the way I defined my Lexer/Parser ?</p>
",https://stackoverflow.com/questions/56547422/antlr-tree-parsing-giving-unexpected-results,"['c#', 'antlr', 'antlr4']",348,True,0,1
(Jasmine)How do I programmatically select/pass the value &lt;select&gt; tag and trigger the change event in Angular 4?,"<p>I am working on an angular application and I am using Jasmine for unit testing it. I am new to Jasmine.</p>

<p>What I want is to test <code>&lt;select&gt;</code> tag for (change) event and the change event is triggered when the user selects a value from the drop-down list.</p>

<p>code to be tested:</p>

<pre><code>// template
&lt;select class=""selectTerminal""(change)=""onChangeTerminal($event.target.value)""&gt;
  &lt;option value="""" disabled&gt;Select Terminal&lt;/option&gt;
  &lt;option *ngFor=""let terminal of terminalList"" [value]=""terminal.id""&gt;{{terminal.terminalCode}}&lt;/option&gt;
&lt;/select&gt;

//function called when the change event is triggered.
onChangeTerminal(id) {

  // `id` comes as `undefined` upon `ng test`, but works fine with `ng serve` since the value is selected manually from the dropdown list.
  this.terminalId = id; 
  this.wharfService.getWharfOrderByTerminalId(id).subscribe(res =&gt; {
  }, (error) =&gt; {
    // handle error
  });
}
</code></pre>

<blockquote>
  <p>what I am so far able to do is trigger the change event so that the
  function is being called. But, I am not able to select/pass the value
  programmatically, which should be passed as arguments to the method
  that takes id upon selecting the value from the dropdown list.</p>
</blockquote>

<p>How do I set the value of select options before triggering the change event?</p>
",https://stackoverflow.com/questions/55119346/jasminehow-do-i-programmatically-select-pass-the-value-select-tag-and-trigge,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'jasmine-jquery']",514,False,0,1
No value at JSON path $[0].nom?,"<p>I'm currently developping a rest api web service and i have to test them using  unit testing, so i cannot figure out how to test the RESTFul API with Spring using Mockito and Junit, first of all i have preapared the class in which i created two method with @Before and @Test, when i turned in debugging mode the method in the the controle ""getEmployeDTOList"" always return null therefore the console show me Exception NullPointerException.</p>

<p>the class EmployeControllerTest:</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
public class EmployeControllerTest {

    private MockMvc mockMvc;
    @InjectMocks
    private EmployeController employeController ; 
    @Mock
    private EmployeService employeService ;
    @Mock
     IConverter converterDto ; 

    @Before
    public void setUp() throws Exception{
        MockitoAnnotations.initMocks(this);
        mockMvc=MockMvcBuilders.standaloneSetup(employeController).build();
    }
    @Test
    public void testgetAllEmployee() throws Exception{
        List&lt;Employe&gt; employes= Arrays.asList(

                new Employe(""BOUROUNIA"", ""HICHEM"", ""h.bourounia"", ""9dfd1be37de137f146ca990310a1483c"",true)
                ,new Employe(""BRADAI"", ""ALI"", ""a.bradai"", ""830ddf1b7e8e34261f49d20e5e549338"",true) );
            when(employeService.findAll()).thenReturn(employes);
            mockMvc.perform(get(""/employe/dto""))
            .andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath(""$"", hasSize(2)))
         .andExpect(jsonPath(""$[0].nom"", is(""BOUROUNIA"")))
         .andExpect(jsonPath(""$[0].prenom"", is(""HICHEM"")))
         .andExpect(jsonPath(""$[0].login"", is(""h.bourounia"")))
         .andExpect(jsonPath(""$[0].mp"", is(""9dfd1be37de137f146ca990310a1483c"")))
         .andExpect(jsonPath(""$[0].actif"", is(true)))
         .andExpect(jsonPath(""$[1].nom"", is(""BRADAI"")))
         .andExpect(jsonPath(""$[1].prenom"", is(""ALI"")))
         .andExpect(jsonPath(""$[1].login"", is(""a.bradai"")))
         .andExpect(jsonPath(""$[1].mp"", is(""830ddf1b7e8e34261f49d20e5e549338"")))
         .andExpect(jsonPath(""$[1].actif"", is(true))).andReturn().getResponse().getContentAsString();

        verify(employeService,times(1)).findAll();
        verifyNoMoreInteractions(employeService);        
}
    }
</code></pre>

<p>this is Employecontroller:</p>

<pre><code>@CrossOrigin(origins = ""*"", allowedHeaders = ""*"")
@RestController
@RequestMapping(""/employe"")
public class EmployeController {
@GetMapping(""/dto"")
public List&lt;EmployeDTO &gt; getEmployeDTOList(){
    try {
        List&lt;Employe&gt; listemp=employeService.findAll();


        return  listemp.stream()
            .filter(Objects::nonNull)
            .map(emp -&gt;converterDTO.convertToDto(emp))
            .collect(Collectors.toList());


    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
} 
}
</code></pre>

<p>error that i got: </p>

<blockquote>
  <p>java.lang.AssertionError: No value at JSON path ""$[0].id"":
  com.jayway.jsonpath.PathNotFoundException: Expected to find an object
  with property ['id'] in path $[0] but found 'null'. This is not a json
  object according to the
  JsonProvider:'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'</p>
</blockquote>
",https://stackoverflow.com/questions/54551150/no-value-at-json-path-0-nom,"['json', 'spring-boot', 'junit', 'mockito', 'hamcrest']",1126,False,-1,1
Angular unit test routerLink state,"<p>Im passing data between angular (version 8) components A &amp; B using <a href=""https://medium.com/ableneo/how-to-pass-data-between-routed-components-in-angular-2306308d8255"" rel=""nofollow noreferrer""><code>state</code></a>, example:</p>

<pre><code>&lt;a routerLink=""/componentB"" [state]=""{data: {hello: 'world'}}""&gt;Go To ComponentB&lt;/a&gt;
</code></pre>

<p>In ComponentB, i'm reading data:</p>

<pre><code>ngOnInit() {
  this.data = history.state.data.hello;
}
</code></pre>

<p>Everything is working in live webapp, but I can't seem to replicate the same in the jasmine test.
Unit test goes like this:</p>

<pre><code>setup();
...
fixture.nativeElement.querySelector(`a`).click();

fixture.whenStable().then(() =&gt; {
  expect(fixture.nativeElement.querySelector(`p`)).toContain('world');
}
</code></pre>

<p>Navigation worked, prior to adding <code>this.data = ...</code> to <code>ngOnInit()</code>, but now there is null pointer exception. Effectively <code>state</code> is <code>null</code>, but I can't figure out why. Everything is working when running webapp live, but Jasmine unit test is failing.</p>

<p>I know I can add <code>history.pushState({data: {hello: 'world'}}, '', '');</code> to setup, but I want for real data to be passed from componentA to componentB during unit testing. What am I missing? Why data from one component does not transfer into another via <code>state</code>?</p>
",https://stackoverflow.com/questions/59326630/angular-unit-test-routerlink-state,"['angular', 'unit-testing', 'jasmine', 'angular-router', 'angular-routerlink']",572,False,0,1
Mocking find($collection) in repository pattern in Laravel with Mockery,"<p>I'm doing unit testing and my repository has this method:</p>

<pre class=""lang-php prettyprint-override""><code>/**
 * @param int|Collection $id
 * @return MyModel|Collection|null
 */
 public function find($id);
</code></pre>

<p>I tried this:</p>

<pre class=""lang-php prettyprint-override""><code>$this-&gt;package_repo = Mockery::mock(PackageRepositoryInterface::class);
$this-&gt;app-&gt;instance('Package', $this-&gt;package_repo);
// ...
$this-&gt;ticket_repo-&gt;shouldReceive(""find"")-&gt;with(collect([]))-&gt;andReturn(/*...*/);

//...

echo $this-&gt;ticket_repo-&gt;find(collect([]));  // Failed here.
</code></pre>

<p>The test immediately failed, and I think it's because the 2 collections in the <code>shouldReceive</code> expectation statement and the actual <code>find</code> statement are distinct objects.</p>

<p>If I want to mock the behavior of <code>$this-&gt;ticket_repo-&gt;find($ids)</code>, what should I do?</p>

<p>Or rather, if there is a better way to design a testable algorithm, how would it be? Because I would like to have all the ids to I want to find be in an array, and be constructed into a single SQL select query, instead of a few hundred separate ones, for performance purposes.</p>

<p>Also asked here: <a href=""https://laracasts.com/discuss/channels/testing/mocking-findcollection-in-repository-pattern-in-laravel-with-mockery#"" rel=""nofollow noreferrer"">https://laracasts.com/discuss/channels/testing/mocking-findcollection-in-repository-pattern-in-laravel-with-mockery#</a></p>
",https://stackoverflow.com/questions/56525501/mocking-findcollection-in-repository-pattern-in-laravel-with-mockery,"['php', 'laravel', 'phpunit', 'mockery']",473,False,0,1
How to write a unit tests for Bot Framework nodejs v4 dialogs,"<p>I looking for an example to write unit test cases for bot builder dialogs for V4 Sdk. I came across a blog but that is for v3 (<a href=""https://www.microsoft.com/developerblog/2017/01/20/unit-testing-for-bot-applications/"" rel=""nofollow noreferrer"">https://www.microsoft.com/developerblog/2017/01/20/unit-testing-for-bot-applications/</a>)
Are there any examples or patterns to follow if I need dialogs to be unit tested for conversation flow? I have looked at the option of using new emulator and transcript files but, that is more for about functional flow and designers to look at mock ups where dialogs are not really tested. </p>

<p>I came across <a href=""https://learn.microsoft.com/en-us/javascript/api/botbuilder-core/testadapter?view=botbuilder-ts-latest"" rel=""nofollow noreferrer"">Test Adapter</a> but trying to find how can I run the example form the page with my local bot instance. </p>
",https://stackoverflow.com/questions/55109967/how-to-write-a-unit-tests-for-bot-framework-nodejs-v4-dialogs,"['unit-testing', 'botframework', 'azure-cognitive-services']",746,True,0,1
How to expect httpReq.request.headers.get(&#39;authorization&#39;).toBeTruthy()?,"<p>I am having a problem to get the unit testing of interceptor done because it tells me that httpReq.request.headers.get('authorization').toBeTruthy() must be tobefalsy().even i am giving the token to it and then attaching that token with the authorization Token Header as shown in the following code but this gives me error. This is interceptor service code:</p>

<p>`</p>

<pre><code>export class TokenInterceptorService implements HttpInterceptor {
    constructor(private auth: CoreService) {
    }
    intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler) {
        if (this.auth.getToken()) {
            req = req.clone({
                setHeaders: {
                    authorization: `Token ${this.auth.getToken()}`
                }
            });
        }
        return next.handle(req);
    }
}
</code></pre>

<p>`</p>

<p>i have tried different approaches to make this correct and even i have debugged this code token is coming but when we expect this to be truthy this tells me that token is null </p>

<p>this is code of spec file</p>

<p>`</p>

<pre><code> it('should add a Authorization token to the authorization header', () =&gt; {
        coreService.setToken('this is my dummy token');
        const token = coreService.getToken();
        const spy = coreSpy.getToken();
        const someData = { data: 'someData ' };
        http.get('localhost:3000/anonymous/user').subscribe((data) =&gt; {
            expect(data).toEqual(someData);
        });
        const httpReq = httpTestingController.expectOne('localhost:3000/anonymous/user');
        expect(httpReq.request.method).toBe('GET');
        expect(httpReq.request.headers.get('authorization')).toBeTruthy();
        expect(httpReq.request.headers.get('authorization')).toBe(`Token ${token}`);
        httpReq.flush(someData);
        httpTestingController.verify();
    });
</code></pre>

<p>`</p>

<p>expected result is that it must tell me that this is true that we get authorization.</p>
",https://stackoverflow.com/questions/54019269/how-to-expect-httpreq-request-headers-getauthorization-tobetruthy,"['angular', 'unit-testing', 'angular6', 'angular-services', 'angular-http-interceptors']",207,False,-1,1
Accessing a resource by its path rather than its byte content - VB.NET,"<p>I'm writing a function which performs some operations from a DOCX file (building a custom TOC from it).</p>

<p>I'm a beginner in <strong>unit testing</strong>, and as far as I understand, it should be designed to check functionality <strong>independently</strong>. </p>

<p>I added a DOCX file as a <strong>resource</strong> in VS and configured it to be <strong>copied</strong> in the output directory.</p>

<p>The resource file is named <code>testDOCXFile</code> and can be accessed this way as an array of <code>Bytes</code>:</p>

<pre><code>Dim content As My.Resources.testDOCXFile
</code></pre>

<p>The problem: the <strong>function</strong> I want to check <strong>requires</strong> a <strong>String</strong> describing the <strong>path to a given file</strong>.</p>

<p>Is there a ""good-practice-compliant"" way to <strong>get a path</strong> to this <strong>resource</strong>, <strong>without</strong> using <strong>string constants</strong> as shown below:</p>

<pre><code>' Don't Repeat Yourself!
Dim contentPath = _
    IO.Path.Combine(Assembly.GetExecutingAssembly().Location,
                    ""Resources"", ""testFile.docx"")
</code></pre>
",https://stackoverflow.com/questions/55355745/accessing-a-resource-by-its-path-rather-than-its-byte-content-vb-net,"['vb.net', 'visual-studio', 'unit-testing']",51,False,0,0
sp_executesql returns a sql query with string fields for non-string in Entity Framework 6,"<p>I am trying to execute Stored Procedure by creating in SQL Server 17.0 first and pulling it into Entity Framework 6.0 for Unit Test purpose using Microsoft Unit Testing Framework</p>

<p>Below is the Stored Procedure I created in the Backend.</p>

<pre><code>    CREATE PROCEDURE [dbo].[sp_GetInteger]
    (
        @name VARCHAR(255)
    )
    AS
    DECLARE @Sql NVARCHAR(MAX)
    DECLARE @parameters NVARCHAR(MAX)

    SET FMTONLY OFF

    SET @Sql = 'SELECT ID, AGE, DOB FROM DETAILS WHERE NAME = @name'

    set @parameters='@name VARCHAR(255) = NULL'

    IF @Sql &lt;&gt; ''
    BEGIN
        EXEC sp_Executesql @Sql,@parameters,@name=@name
    END
    ELSE
    BEGIN
        SELECT '' AS ID, '' AS AGE, '' AS DOB
    END
</code></pre>

<p>In Entity Framework, after pulling the SP, it is generating a class as below</p>

<pre><code>public partial class sp_GetInteger_Result
{
    public string ID { get; set; }
    public string AGE { get; set; }
    public string DOB { get; set; }
}
</code></pre>

<p>In Unit Test class, I am executing as below</p>

<pre><code>[TestMethod]
public void Test_GetInteger()
{
    var result = db.sp_GetInteger(""John"").FirstOrDefault();
}
</code></pre>

<p>Here the class generated in EF is having fields with string datatypes though it is <code>int</code> and <code>datetime</code> in the backend table.</p>

<p>Whenever I generate EF entities, I need to modify the <code>_Result</code> class and my project and I cannot go everywhere and modify the datatypes and get the result.</p>

<p>I appreciate your help in advance.</p>
",https://stackoverflow.com/questions/59153530/sp-executesql-returns-a-sql-query-with-string-fields-for-non-string-in-entity-fr,"['c#', 'sql-server', 'entity-framework']",153,False,0,0
Angular 7 unit testing dependency injection not working in ngOnInit,"<p>I am using Angular 7 with and Angular CLI version 7.3.4.  I am unit testing a component with 2 service injections all important code is included below. I included the stub which is causing errors, the spec file, and the important part of the component in question. Despite this, I am still getting this error ""TypeError: this.spreading.getSpreadingDays is not a function"" I am aware that fixture.detectchanges() is what causes ngOnInit to be called, but the function should be defined since I injected the service.  I am sure it is a silly error, but I have looked at a number of tutorials and I cannot figure out what is wrong with my code. Any suggestions would be appreciated.</p>

<p>Spec file</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { SpreadSignUpComponent } from './spread-sign-up.component';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { AuthService } from 'src/app/core/services/auth.service';
import { SpreadingService } from 'src/app/core/services/spreading.service';
import { AuthServiceStub } from 'src/app/core/testing/auth.service.stub';
import { SpreadingServiceStub } from 'src/app/core/testing/spreading.service.stub';

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

  let authService: AuthService;
  let spreadingService: SpreadingService;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        { provide: AuthService, useValue: AuthServiceStub },
        { provide: SpreadingService, useValue: SpreadingServiceStub }
      ],
      declarations: [ SpreadSignUpComponent ],
      schemas: [ NO_ERRORS_SCHEMA ],
    })
    .compileComponents();

    authService = TestBed.get(AuthService);
    spreadingService = TestBed.get(SpreadingService);
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>stub class:</p>

<pre><code>import { SpreadingService } from '../services/spreading.service';
import { of } from 'rxjs';
import { SpreadingDay } from 'src/app/shared/models/spreadingDay';
import { I } from 'src/app/shared/testing/interfaceBuilder';

export class SpreadingServiceStub implements I&lt;SpreadingService&gt; {

  getSpreadingDays() {
    return of([]);
  }

  getSpreadingDaysForUser() {
    return of([]);
  }

  setSpreadingDay(
    spreadingDay: SpreadingDay
  ) {
    return &lt;Promise&lt;void&gt;&gt;{};
  }

  addVolunteerToDay(
    spreadingDay: SpreadingDay,
    userID: string,
  ) {
    return &lt;Promise&lt;void&gt;&gt;{};
  }

  removeVolunteerFromDay(
    spreadingDay: SpreadingDay,
    userID: string,
  ) {
    return &lt;Promise&lt;void&gt;&gt;{};
  }

  addRequestToDay(
    spreadingDay: SpreadingDay,
    userID: string,
    first: string,
    last: string,
  ) {
    return &lt;Promise&lt;void&gt;&gt;{};
  }
}
</code></pre>

<p>component:</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { SpreadingService } from 'src/app/core/services/spreading.service';
import { SpreadingDayReturn, SpreadingDay } from 'src/app/shared/models/spreadingDay';
import { Observable } from 'rxjs';
import { AuthService } from 'src/app/core/services/auth.service';

@Component({
  selector: 'app-spread-sign-up',
  templateUrl: './spread-sign-up.component.html',
  styleUrls: ['./spread-sign-up.component.scss']
})
export class SpreadSignUpComponent implements OnInit {

  spreadingDays$: Observable&lt;SpreadingDayReturn[]&gt;;

  constructor(
    private auth: AuthService,
    private spreading: SpreadingService,
  ) { }

  ngOnInit() {
    this.spreadingDays$ = this.spreading.getSpreadingDays();
  }
</code></pre>
",https://stackoverflow.com/questions/55270100/angular-7-unit-testing-dependency-injection-not-working-in-ngoninit,"['angular', 'typescript', 'unit-testing', 'dependency-injection', 'ngoninit']",3278,True,4,1
Django Custom User Manager Unit Test - NoneType object is not callable,"<p>This all started when I downloaded coverage.py and started testing my django project. Everything is fine, however I'm lacking coverage on a custom user manager I set up in Models.py</p>

<p>Here's the full code.</p>

<p><strong>models.py</strong></p>

<pre><code>from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
from django.utils.translation import ugettext_lazy as _

class UserManager(BaseUserManager):
    """"""Define a model manager for User model with no username field.""""""

    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """"""Create and save a User with the given email and password.""""""
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)

        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        """"""Create and save a regular User with the given email and password.""""""
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        """"""Create and save a SuperUser with the given email and password.""""""
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)


class CustomUser(AbstractUser):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    # profile_image = models.ImageField(upload_to=""users/profile_pic"", blank=True)
    is_pastor = models.BooleanField(default=True)
    home_church = models.ForeignKey(
        'church.Church',
        on_delete=""CASCADE"",
        blank=True,
        null=True)

    username = None
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager() ## This is the new line in the User model. ##
</code></pre>

<p>I'm attempting to test the ""_create_user"" function in the UserManager. Here is my code</p>

<p><strong>test.py</strong></p>

<pre><code>class UserManagerTestCase(TestCase):

def test_main_create_user(self):
    manager = UserManager()
    user = manager._create_user('jdoe@gmail.com', 'password123')
    self.assertTrue(isinstance(user, User))
</code></pre>

<p>Unfortunately, when I call the '_create_user' function I get a Type Error: 'NoneType' object is not callable.</p>

<p>This is strange, because the model manager works as expected when creating users and I confirmed with print statements that both the email and **extra_fields arguments are not None. </p>

<p>Some research online said this might because the Manager is not designed to be called directly. Is that the case? If so, how should you handle unit testing?</p>
",https://stackoverflow.com/questions/57582172/django-custom-user-manager-unit-test-nonetype-object-is-not-callable,"['python', 'django', 'testing']",1006,True,4,1
Unable to read the metadata of AndroidManifest.xml in unit test cases,"<p>I am writing local unit testcases for my android application.
In one of the test cases, i need to read the contents of metadata defined in the AndroidManifest.xml</p>

<p>I can easily read the data by calling these methods - metadata.getString() / metadata.getBoolean()
while running the application</p>

<p>I Cannot access the same in unit testing.
the values of the all the keys defined in maifest appears to be null here.</p>

<p>In the below code, object <strong>ai is created properly, 
res is null,
aM is null,</strong></p>

<p><strong>metadata is not null and it has the values for hub_url, enable_transmission and authentication as defined in manifest file.</strong></p>

<p><strong>Its strange that when i try to access contents of metadata in variable a, b and c, all are null</strong></p>

<pre><code>    val context = ApplicationProvider.getApplicationContext&lt;Context&gt;()
    val ai = context!!.packageManager.getApplicationInfo( context.packageName, PackageManager.GET_META_DATA)
    val res = ai.metaData.getBoolean( context.getString(R.string.enable_transmission))

    val aM = ai.metaData.get( context.getString(R.string.enable_transmission))
    val metadata = ai.metaData!!;

    val a = metadata.getString(context.getString(R.string.hub_url))
    val b = metadata.get(context.getString(R.string.enable_transmission));
    val c = metadata.get(context.getString(R.string.authentication));
</code></pre>

<p>Here is the manifest file content</p>

<pre><code> &lt;application&gt;

    &lt;meta-data
        android:resource=""@string/basic""
        android:name=""@string/authentication""
        android:value=""@string/basic"" /&gt;

    &lt;meta-data
        android:resource=""@string/hub_url""
        android:name=""@string/hub_url""
        android:value=""@string/hub_url"" /&gt;

    &lt;meta-data
        android:resource=""@bool/enable""
        android:name=""@string/enable_transmission""
        android:value=""@bool/enable"" /&gt;


&lt;/application&gt;
</code></pre>
",https://stackoverflow.com/questions/54089781/unable-to-read-the-metadata-of-androidmanifest-xml-in-unit-test-cases,"['android', 'kotlin']",513,False,4,1
Unable to read the metadata of AndroidManifest.xml in unit test cases,"<p>I am writing local unit testcases for my android application.
In one of the test cases, i need to read the contents of metadata defined in the AndroidManifest.xml</p>

<p>I can easily read the data by calling these methods - metadata.getString() / metadata.getBoolean()
while running the application</p>

<p>I Cannot access the same in unit testing.
the values of the all the keys defined in maifest appears to be null here.</p>

<p>In the below code, object <strong>ai is created properly, 
res is null,
aM is null,</strong></p>

<p><strong>metadata is not null and it has the values for hub_url, enable_transmission and authentication as defined in manifest file.</strong></p>

<p><strong>Its strange that when i try to access contents of metadata in variable a, b and c, all are null</strong></p>

<pre><code>    val context = ApplicationProvider.getApplicationContext&lt;Context&gt;()
    val ai = context!!.packageManager.getApplicationInfo( context.packageName, PackageManager.GET_META_DATA)
    val res = ai.metaData.getBoolean( context.getString(R.string.enable_transmission))

    val aM = ai.metaData.get( context.getString(R.string.enable_transmission))
    val metadata = ai.metaData!!;

    val a = metadata.getString(context.getString(R.string.hub_url))
    val b = metadata.get(context.getString(R.string.enable_transmission));
    val c = metadata.get(context.getString(R.string.authentication));
</code></pre>

<p>Here is the manifest file content</p>

<pre><code> &lt;application&gt;

    &lt;meta-data
        android:resource=""@string/basic""
        android:name=""@string/authentication""
        android:value=""@string/basic"" /&gt;

    &lt;meta-data
        android:resource=""@string/hub_url""
        android:name=""@string/hub_url""
        android:value=""@string/hub_url"" /&gt;

    &lt;meta-data
        android:resource=""@bool/enable""
        android:name=""@string/enable_transmission""
        android:value=""@bool/enable"" /&gt;


&lt;/application&gt;
</code></pre>
",https://stackoverflow.com/questions/54089781/unable-to-read-the-metadata-of-androidmanifest-xml-in-unit-test-cases,"['android', 'kotlin']",513,False,4,1
CMockery Compilation unknown type name &quot;jmp_buf&quot;,"<p>I am trying to add unit testing framework cMockery to my C project. I have downloaded and installed the cMockery into global include path. But after <code>#include &lt;cmockery.h&gt;</code> in my source file, cmake throws the following issue. It seems the same thing will be thrown if I use <code>cMocka</code> as well. Am I missing some packages? </p>

<p>Edit: Google search for <code>""/usr/include/google/cmockery.h:365:8: error: unknown type name ‘jmp_buf’""</code> returned exactly <s>0 results</s> (Now 1 result pointing to this question). As well as searching for <code>unknown type name 'jmp_buf'</code> only explains what is it. Not how to fix it or why does it happen inside cmockery.</p>

<pre><code>/usr/bin/cmake --build /home/.../data-structures-c/cmake-build-debug --target data_structures_c -- -j 3
Scanning dependencies of target data_structures_c
[ 50%] Building C object CMakeFiles/data_structures_c.dir/main.c.o
In file included from /home/.../data-structures-c/main.c:3:
/usr/include/google/cmockery.h:365:8: error: unknown type name ‘jmp_buf’
 extern jmp_buf global_expect_assert_env;
        ^~~~~~~
make[3]: *** [CMakeFiles/data_structures_c.dir/build.make:63: CMakeFiles/data_structures_c.dir/main.c.o] Error 1
make[2]: *** [CMakeFiles/Makefile2:73: CMakeFiles/data_structures_c.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:85: CMakeFiles/data_structures_c.dir/rule] Error 2
make: *** [Makefile:118: data_structures_c] Error 2
</code></pre>

<p>OS: Manjaro Archlinux</p>

<p>Cmake, make, gcc, g++ all installed. </p>

<p>My <code>CMakeList.txt</code> is also very standard, bare minimum with a single c source </p>

<pre><code>cmake_minimum_required(VERSION 3.12)
project(data_structures_c C)
set(CMAKE_C_STANDARD 99)
add_executable(data_structures_c main.c)
</code></pre>

<p>I would like to know how to solve this issue in order to compile my code.</p>
",https://stackoverflow.com/questions/55614090/cmockery-compilation-unknown-type-name-jmp-buf,"['cmake', 'cmockery']",1761,True,4,1
Jasmine unit testing with Istanbul,"<p>I am doing unit testing with Jasmin and Istanbul.</p>

<p>I try to do unit testing on the following method:</p>

<pre><code> getDiploma(spinnerMessage: string): Observable&lt;DiplomaModel&gt; {
        const diploma = this.diplomasState.diploma;
        if (diploma) {
            // Return diploma info from store
            return observableOf(diploma);
        } else {
            // Get and return diploma info from backend
            return this.http.get&lt;DiplomaModel&gt;(this.apiDiploma, spinnerMessage).pipe(map((result) =&gt; {
                return this.setDiplomasInStore(result);
            }));
        }
    }
</code></pre>

<p>And my unit test looks like this:</p>

<pre><code> it('It should return diploma from the backend when snapshot exist ', () =&gt; {

            diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
            const diplomaState = diplomaService.getDiplomaSnapshot();
            expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));

            // tslint:disable-next-line:no-commented-code
            /*  const response = [{ mock: 'mock' } as any];
             diplomaService['getDiplomaSnapshot'] = response;
             diplomaService.getDiplomaState().subscribe(i =&gt; {
                 expect(i).toEqual(response);
             }); */
        });

it('It should return diploma if snapshot doenst exist', () =&gt; {
    const apiString = 'api/register/teachers/current/diploma';
    const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
    const spyDocument = spyOn(diplomaService, 'getDiploma').and.callThrough();

    diplomaStoreServiceMock.returnState({});
    const response = { 'mock': 'mockResult' };
    afwHttp.setupOnlyResponse(response, 200);
    diplomaService.getDiploma('spinnerText').subscribe(result =&gt; expect(result['mock']).toEqual('mockResult'));
    afwHttp.returnOnlyResponse();
    expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
    expect(spyDocument).toHaveBeenCalledWith('spinnerText');
});
</code></pre>

<p>But in Istanbul I get still a red line on this line:</p>

<pre><code> return observableOf(diploma);
</code></pre>

<p>with a I and if I hover over the I is says:</p>

<p>if Path not taken.</p>

<p>So how to solve this?</p>

<p>Thank you.</p>

<p>but that is why I have two methods. But you mean this method:</p>

<pre><code>it('It should return diploma from the backend when snapshot exist ', () =&gt; {



     diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();
        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });
</code></pre>

<p>What I have to change about this test method?</p>

<p>You mean like this:</p>

<pre><code> it('It should return diploma from the backend when snapshot exist ', () =&gt; {

        diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();
        diplomaService.getDiploma('spinnerText');
        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });
</code></pre>

<p>I also tried like this:</p>

<pre><code>it('It should return diploma from the backend when snapshot exist ', () =&gt; {
    const response = [{ mock: 'mock' } as any];
    diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
    const diplomaState = diplomaService.getDiplomaSnapshot();
    diplomaService.getDiploma('spinnerText').subscribe( i =&gt; {
        expect(i).toEqual(response);

    });
    expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
});
</code></pre>

<p>And if I add this method:</p>

<pre><code>  it('It should return diploma', () =&gt; {
        const response = [{ mock: 'mock' } as any];
        diplomaService.getDiploma('spinnerText').subscribe( i =&gt; {
            expect(i).toEqual(response);

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

<p>I get this error:</p>

<blockquote>
  <p>ERROR in
  apps/register/src/app/shared/services/src/diploma.service.spec.ts(67,31):
  error TS2345: Argument of type 'any[]' is not assignable to parameter
  of type 'Expected'.   Type 'any[]' is not assignable to
  type 'ObjectContaining'.
      Property 'jasmineMatches' is missing in type 'any[]'.</p>
</blockquote>

<p>So I have now three methods:</p>

<pre><code> it('It should return diploma from the backend when snapshot exist ', () =&gt; {
        diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();
        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });

    it('It should return diploma', () =&gt; {
        const response = [{ mock: 'mock' } as any];
        diplomaService.getDiploma('spinnerText').subscribe( i =&gt; {
            expect(i).toEqual(response);

        });
    });


    it('It should return diploma if snapshot doenst exist', () =&gt; {
        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        const spyDocument = spyOn(diplomaService, 'getDiploma').and.callThrough();
        const response = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(response, 200);
        diplomaService.getDiploma('spinnerText').subscribe(result =&gt; expect(result['mock']).toEqual('mockResult'));
        afwHttp.returnOnlyResponse();
        expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
        expect(spyDocument).toHaveBeenCalledWith('spinnerText');
    });
</code></pre>

<p>This is the hole test file:</p>

<pre><code>describe('Services: DiplomaService', () =&gt; {


    let afwHttp: AfwHttpMock;
    let diplomaService: DiplomaService;
    let diplomaStoreServiceMock: DiplomaStoreServiceMock;
    let feedbackStoreServiceMock: FeedbackStoreServiceMock;
    let multiFileUploadServiceMock: MultiFileUploadServiceMock;




    beforeEach(() =&gt; {
        afwHttp = new AfwHttpMock();
        diplomaStoreServiceMock = new DiplomaStoreServiceMock();
        multiFileUploadServiceMock = new MultiFileUploadServiceMock();
        feedbackStoreServiceMock = new FeedbackStoreServiceMock();
        diplomaService = new DiplomaService(afwHttp as any,
            diplomaStoreServiceMock as any,
            feedbackStoreServiceMock as any,
            multiFileUploadServiceMock as any);
    });

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


    it('It should return diplomadocumentList', () =&gt; {
        // tslint:disable-next-line:no-duplicate-string
        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        const spyDocumentList = spyOn(diplomaService, 'getDiplomaDocumentList').and.callThrough();
        const response = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(response, 200);

        const result2 = diplomaService.getDiplomaDocumentList('spinnerText');
        result2.subscribe(() =&gt; {
            expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
            expect(spyDocumentList).toHaveBeenCalledWith('spinnerText');
        });
        afwHttp.returnOnlyResponse();
    });


    // tslint:disable-next-line:no-commented-code

    it('It should return diploma from the backend when snapshot exist ', () =&gt; {
        diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();

        diplomaService.getDiploma('spinnerText').subscribe(result =&gt; expect(result['mock']).toEqual('mockResult'));

        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });

   // tslint:disable-next-line:no-commented-code
   /*  it('It should return diploma', () =&gt; {
        const response = [{ mock: 'mock' } as any];
        diplomaService.getDiploma('spinnerText').subscribe( i =&gt; {
            expect(i).toEqual(response);

        });
    }); */


    it('It should return diploma if snapshot doenst exist', () =&gt; {
        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        const spyDocument = spyOn(diplomaService, 'getDiploma').and.callThrough();
        const response = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(response, 200);
        diplomaService.getDiploma('spinnerText').subscribe(result =&gt; expect(result['mock']).toEqual('mockResult'));
        afwHttp.returnOnlyResponse();
        expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
        expect(spyDocument).toHaveBeenCalledWith('spinnerText');
    });

    // tslint:disable-next-line:no-identical-functions
    it('It should save diploma record to database', () =&gt; {

        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'post').and.callThrough();
        const spyDocument = spyOn(diplomaService, 'saveDiplomaMetaData').and.callThrough();
        const response = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(response, 200);

        const result2 = diplomaService.saveDiplomaMetaData(false, 'spinnerText');
        result2.subscribe(() =&gt; {
            expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
            // tslint:disable-next-line:no-commented-code
            expect(spyDocument).toHaveBeenCalledWith(false, 'spinnerText');
        });
        afwHttp.returnOnlyResponse();
    });

    it('It should save documents for  diploma record', fakeAsync(() =&gt; {
        const spy = spyOn(multiFileUploadServiceMock, 'syncFilesWithBackend').and.callThrough();
        const spyFeedback = spyOn(feedbackStoreServiceMock, 'addErrorMessage');

        multiFileUploadServiceMock.setResponse([{ error: 'error' }]);


        diplomaService.saveDocumentForDiploma([{} as any], () =&gt; { }, MultiFileUploadResourcesModel.keys, { key: 'diploma', value: 'document' });

        expect(spy).toHaveBeenCalledWith('api/register/teachers/current/diploma/documents', [{}],
            MultiFileUploadResourcesModel.keys.bijlageToevoegenSpinnerTekst,
            MultiFileUploadResourcesModel.keys.bijlageVerwijderenSpinnerTekst
        );

        tick();
        expect(spyFeedback).toHaveBeenCalled();
    }));

    // tslint:disable-next-line:no-identical-functions
    it('should return document list ', fakeAsync(() =&gt; {
        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        const spyDocumentList = spyOn(diplomaService, 'getDiplomaDocumentList').and.callThrough();
        const response = { 'mock': 'mockResult' };

        multiFileUploadServiceMock.setResponse([{}]);
        afwHttp.setupOnlyResponse(response, 200);

        const result2 = diplomaService.getDiplomaDocumentList('spinnerText');
        result2.subscribe(() =&gt; {
            expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
            expect(spyDocumentList).toHaveBeenCalledWith('spinnerText');
            expect(spyDocumentList).not.toBeNull();

        });
        afwHttp.returnOnlyResponse();

    }));

    // tslint:disable-next-line:no-identical-functions
    it('It should return diplomaSnapshot', () =&gt; {
        diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();
        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });
});
</code></pre>

<p>I have it now like this:</p>

<pre><code>it('It should return diploma from the snapshot as an observable ', () =&gt; {

        const expected = { code: '00100-00101', test: 'test' };
        afwHttp.setupOnlyResponse(expected, 200);
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        diplomaStoreServiceMock.returnState({diploma: expected});


        diplomaService.getDiploma('spinnerText').subscribe(result =&gt; expect(result['mock']).toEqual('mockResult'));
        afwHttp.returnOnlyResponse();
        expect(spyHttp).not.toHaveBeenCalledWith();

    });
</code></pre>

<p>But then I will get this error:</p>

<blockquote>
  <p>Services: DiplomaService > It should return diploma from the snapshot
  as an observable Expected undefined to equal 'mockResult'. Error:
  Expected undefined to equal 'mockResult'.
      at 
      at SafeSubscriber._next (<a href=""http://localhost:9877/src/app/shared/services/src/diploma.service.spec.ts?:65:93"" rel=""nofollow noreferrer"">http://localhost:9877/src/app/shared/services/src/diploma.service.spec.ts?:65:93</a>)
      at SafeSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (<a href=""http://localhost:9877/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/rxjs/_esm5/internal/Subscriber.js?:196:1"" rel=""nofollow noreferrer"">http://localhost:9877/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/rxjs/_esm5/internal/Subscriber.js?:196:1</a>)
      at SafeSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next
  (<a href=""http://localhost:9877/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/rxjs/_esm5/internal/Subscriber.js?:134:1"" rel=""nofollow noreferrer"">http://localhost:9877/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/rxjs/_esm5/internal/Subscriber.js?:134:1</a>)</p>
</blockquote>

<p>Ah, oke.</p>

<p>I have it now like this:</p>

<pre><code> it('It should return diploma from the snapshot as an observable ', () =&gt; {

        const expected = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(expected, 200);
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        diplomaStoreServiceMock.returnState({diploma: expected});


        diplomaService.getDiploma('spinnerText').subscribe(result =&gt; expect(result['mock']).toEqual('mockResult'));
        afwHttp.returnOnlyResponse();
        expect(spyHttp).not.toHaveBeenCalledWith();

    });
</code></pre>

<p>and it works</p>
",https://stackoverflow.com/questions/54389597/jasmine-unit-testing-with-istanbul,"['angular', 'typescript', 'unit-testing', 'jasmine', 'istanbul']",126,False,0,0
"Jasmine testing, .not.toHaveBeenCalled();","<p>I am doing unit testing with Jasmine, and Instanbul. I am testing a submit form. And I have already several unit tests for it. But now I want that if: </p>

<pre><code>this.allowSubmitAgain = false; this method:

this.diplomaService.saveDiplomaMetaData(false, this.resources.opslaanSpinnerTekst).pipe(map(() =&gt; {
</code></pre>

<p>not will be executed. Because on this line in instanbul:</p>

<pre><code>if (this.allowSubmitAgain) {
</code></pre>

<p>it says E: else path not taken.</p>

<p>This is the whole method:</p>

<pre><code>diplomaDataSubmitted() {
        if (this.formModel &amp;&amp; this.formModel.form.valid) {

            this.formService.formStoreService.hideValidationSummary(this.formName);
            Eif (this.allowSubmitAgain) {
                this.allowSubmitAgain = false;
                this.diplomaService.saveDiplomaMetaData(false, this.resources.opslaanSpinnerTekst).pipe(map(() =&gt; {
                    const documents: DocumentModel[] = this.formModel.getAngularFormControl(DiplomaFormKeysModel.keys.diplomasUpload).value.files;

                    this.diplomaService.saveDocumentForDiploma(documents, () =&gt; {
                        this.router.navigateByUrl(RoutesRegisterModel.pathnameMyRegisterRouteDiplomas).then(() =&gt; {
                            this.feedbackService.addSuccessMessageOnMainPortal(
                                {
                                    key: this.resourceKeys.succesvolWijziging,
                                    value: this.resources.succesvolWijziging,
                                }
                            );
                        });
                    }, (error: any) =&gt; {
                        this.allowSubmitAgain = true;
                        observableThrowError(error);
                    }, this.resources, this.resourceKeys);
                })).subscribe(() =&gt; { }, (error: any) =&gt; {
                    this.allowSubmitAgain = true;
                    observableThrowError(error);
                });
            }
        } else {
            this.formService.formStoreService.showValidationSummary(this.formName);

        }
    }
</code></pre>

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

<pre><code>it('should not allow submit beaucse form has errors', fakeAsync(() =&gt; {

        // Arrange
        const spySaveMetaDataDiploma = spyOn(diplomaServiceMock, 'saveDiplomaMetaData');

        diplomaServiceMock.returnErrorResponse();
        // Act
        component.diplomaDataSubmitted();
        fixture.detectChanges();

        // Assert
         expect(spySaveMetaDataDiploma).not.toHaveBeenCalled();
        console.log('testcase');
        expect(component.allowSubmitAgain).toBe(false);


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

<p>But I get this error:</p>

<pre><code>TypeError: Cannot read property 'subscribe' of undefined.
</code></pre>

<p>So how to fix that?</p>

<p>Thank you</p>

<p>I have it now like this:</p>

<pre><code>it('should not allow submit beaucse form has errors', fakeAsync(() =&gt; {

        // Arrange

        const spySaveDiploma = spyOn(diplomaServiceMock, 'saveDiplomaMetaData').and.callThrough();

        // Act
        component.allowSubmitAgain = false;

        // Assert

        console.log('testcase');
        expect(component.allowSubmitAgain).toBe(false);
        expect(spySaveDiploma).not.toHaveBeenCalled();

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

<p>And I don't get errors.</p>

<p>But in the code coverage of Istanbul. The 'else path not taken' is still visible.</p>

<p>Eif (this.allowSubmitAgain) {</p>

<p>So on this line it still says else path not taken.</p>

<p>if I do it like this:</p>

<pre><code> it('should not allow submit again beaucse form has errors', fakeAsync(() =&gt; {

        const spySaveDiploma = spyOn(diplomaServiceMock, 'saveDiplomaMetaData').and.callThrough();

        component.diplomaDataSubmitted();
        component.allowSubmitAgain = false;
        fixture.detectChanges();

        console.log('testcase');
        expect(component.allowSubmitAgain).toBe(false);
        expect(spySaveDiploma).not.toHaveBeenCalled();
    }));
</code></pre>

<p>I get this error:</p>

<pre><code>Expected spy saveDiplomaMetaData not to have been called.
</code></pre>

<p>But what I have to do ?</p>
",https://stackoverflow.com/questions/54452904/jasmine-testing-not-tohavebeencalled,"['javascript', 'unit-testing', 'jasmine', 'code-coverage', 'istanbul']",2661,False,3,0
google test with visual studio 2019 and cmake,"<p>I am trying to setup google test with visual studio 2019 and cmake.</p>

<p>This is my CMakeFileLists.txt content:</p>

<pre><code>cmake_minimum_required(VERSION 3.0)
project(test_me)

# GTest
enable_testing()
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIRS})

# Unit Tests
# Add test cpp file
add_executable( runUnitTests tests.cpp)
# Link test executable against gtest &amp; gtest_main
target_link_libraries(runUnitTests ${GTEST_BOTH_LIBRARIES})
add_test( runUnitTests runUnitTests )
</code></pre>

<p>My tests.cpp file looks like this:</p>

<pre><code>#include &lt;gtest/gtest.h&gt;

TEST(ABC, TEST1) {
    EXPECT_EQ(true, true);
}

TEST(ABC, TEST2) {
    ASSERT_TRUE(2 == 2);
}
</code></pre>

<p>this minimal example is from another stackoverflow question:
<a href=""https://stackoverflow.com/questions/53583286/cmake-file-for-integrated-visual-studio-unit-testing/53585782#53585782"">CMake file for integrated Visual Studio unit testing</a></p>

<p>Thats what I get after I have build the application:
<a href=""https://i.stack.imgur.com/UW0xW.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/UW0xW.png"" alt=""enter image description here""></a></p>

<p>a single Test with the name runUnitTests. However in the picture of the answer from the question above I would expect to see the name of each test function. Something like this:</p>

<pre><code>runUnitTests
- ABC
  - TEST1
  - TEST2
</code></pre>

<p>I have tested it with a new visual studio solution and added a google unit test project. Pasting the test functions into this projects results into this picture:</p>

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

<p>So this works fine. It must have something to do with the <code>open a local folder</code> method which I am using to handle my cmake project.</p>
",https://stackoverflow.com/questions/56511117/google-test-with-visual-studio-2019-and-cmake,"['c++', 'visual-studio', 'unit-testing', 'cmake', 'googletest']",7528,True,7,1
"vuejs unit testing, default installation says no test specified","<p>On Windows 7. Installed a fresh vue project using the VueJS UI utility. Set unit testing / Jest enabled. Added babel. </p>

<p>running ""npm test"" at the command line returns <code>'Error: no test specified'</code>. </p>

<p>I have the typical <code>""scripts"": { ""vue-cli-service test:unit"" }</code> set up in my package.json file. </p>

<p>jest.config.js has the expected matching pattern:</p>

<pre><code>{  testMatch: [
    '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
  ] }
</code></pre>

<p>So, it's not finding even the example file located in tests/unit/example.spec.js.</p>

<p>Curiously, I CAN get it to find tests I run directly from the node_modules directory, using <code>vue-cli-service</code>:</p>

<pre><code>node_modules\.bin\vue-cli-service test:unit
</code></pre>

<p>from there I get a babel transpile problem (it fails to recognize the ES6 <code>import</code> command in the <code>example.spec.js</code> file) .. which is another nightmare, perhaps not for this post.</p>

<p>Tried updating npm (using <code>6.9.2</code>). Vue cli version is <code>3.8.2</code>. Tried deleting the node_modules directory. 
Any help is most appreciated. </p>

<p>After running <code>npm test</code>, the error looks like this:</p>

<pre><code>&gt; testing_research@0.1.0 test C:\Users\allan.luchenitser\sandbox\testing_research
&gt; echo 'Error: no test specified'

'Error: no test specified'
</code></pre>

<p>thanks again,</p>
",https://stackoverflow.com/questions/56836435/vuejs-unit-testing-default-installation-says-no-test-specified,"['javascript', 'node.js', 'unit-testing', 'vue.js', 'babeljs']",2029,True,2,1
.netcore unit testing not running properly,"<p>I have created some unit tests for a simple c#/dotnet-core console application.
I have created the reference on the testing project but for some reason the ""dotnet test"" cmd is still reporting the following error:</p>

<blockquote>
  <p>UnitTest1.cs(12,25): error CS0103: The name 'LinkChecker' does not
  exist in the current context
  [/Users/med.bensalem/Desktop/dotnet-projects/checklinksTests/checklinksTests.csproj]
  UnitTest1.cs(19,25): error CS0103: The name 'LinkChecker' does not
  exist in the current context
  [/Users/med.bensalem/Desktop/dotnet-projects/checklinksTests/checklinksTests.csproj]</p>
</blockquote>

<p>Project structure:</p>

<pre><code>.
├── checklinksTests
│   ├── UnitTest1.cs
│   ├── checklinksTests.csproj
└── checklinksconsole
    └── code
        ├── LinkChecker.cs
        ├── Program.cs
        └── checklinksconsole.csproj
</code></pre>

<p>Please find below the code I project source code:</p>

<p><strong>Main application - checklinksconsole:</strong></p>

<p><em>checklinksconsole.csproj - file:</em>
    </p>

<pre><code>  &lt;PropertyGroup&gt;
    &lt;OutputType&gt;Exe&lt;/OutputType&gt;
    &lt;TargetFramework&gt;netcoreapp2.2&lt;/TargetFramework&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=""HtmlAgilityPack.NetCore"" Version=""1.5.0.1"" /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;
</code></pre>

<p><em>Program.cs - file:</em></p>

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

namespace checklinksconsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var site = ""https://www.google.com"";
            var client = new HttpClient();
            var body = client.GetStringAsync(site);
            Console.WriteLine(body.Result);

            Console.WriteLine();
            Console.WriteLine(""Links:"");
            var links = LinkChecker.GetLinks(body.Result);
            links.ToList().ForEach(Console.WriteLine);
        }
    }
}
</code></pre>

<p><em>LinkChecker.cs - file:</em></p>

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

namespace checklinksconsole
{
    public class LinkChecker
    {
        public static IEnumerable&lt;string&gt; GetLinks(string page)
        {
            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(page);
            var links = htmlDocument.DocumentNode.SelectNodes(""//a[@href]"")
                .Select(n =&gt; n.GetAttributeValue(""href"", string.Empty))
                .Where(l =&gt; !String.IsNullOrEmpty(l))
                .Where(l =&gt; l.StartsWith(""http""));
            return links;
        }
    }
}
</code></pre>

<p><strong>Unit testing - checklinksTests:</strong></p>

<p><em>checklinksTests.csproj - file:</em></p>

<pre><code>&lt;Project Sdk=""Microsoft.NET.Sdk""&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;netcoreapp2.2&lt;/TargetFramework&gt;

    &lt;IsPackable&gt;false&lt;/IsPackable&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=""Microsoft.NET.Test.Sdk"" Version=""15.9.0"" /&gt;
    &lt;PackageReference Include=""xunit"" Version=""2.4.0"" /&gt;
    &lt;PackageReference Include=""xunit.runner.visualstudio"" Version=""2.4.0"" /&gt;
  &lt;/ItemGroup&gt;

  &lt;ItemGroup&gt;
    &lt;ProjectReference Include=""..\checklinksconsole\code\checklinksconsole.csproj"" /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;
</code></pre>

<p><em>UnitTest1.cs - file:</em></p>

<pre><code>using System;
using Xunit;

namespace checklinksTests
{
    public class UnitTest1
    {
        [Fact]
        public void WithoutHTTPAtTheStartOfTheLink_NoLinks()
        {
            var links = LinkChecker.GetLinks(""&lt;a href=\""google.com\"" /&gt;"");
            Assert.Equal(links.Count(),0);
        }

        [Fact]
        public void WithHTTPAtTheStartOfTheLink_LinkParses()
        {
            var links = LinkChecker.GetLinks(""&lt;a href=\""http://google.com\"" /&gt;"");
            Assert.Equal(links.Count(),1);
            Assert.Equal(links.First(), ""google.com"");
        }
    }
}
</code></pre>

<p>Any idea on what is wring with my code.</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/56566243/netcore-unit-testing-not-running-properly,"['c#', '.net-core', 'xunit.net']",161,True,2,1
How to mock req.session on Mocha/Chai API Unit Test,"<p>Using Mocha/Chai for REST API unit testing, I need to be able to mock <code>req.session.someKey</code> for a few of the end points. How can I go about mocking <code>req.session</code>?</p>

<p>I'm working on writing REST API unit tests for a NodeJS Express app that utilizes express-session. Some of these endpoints require the use of data stored in <code>req.session.someKey</code>, the endpoint is setup to return a 400 if <code>req.session.someKey</code> is undefined so I need to be able to mock it in order for the test to complete successfully.</p>

<p>Example code:</p>

<pre><code>router.get('/api/fileSystems', utilities.apiAuth, (req, res) =&gt; {
  let customer = req.session.customer;
  let route = (customer === 'NONE') ? undefined : customer;

  if(route == undefined){
    res.status(400).send('Can't have customer of undefined');
  } else {
    let requestOptions = setRequestOptions(route);
    queryFileSystemInfo(requestOptions, (info) =&gt; {
      res.status(200).send(info);
    });

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

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

<pre><code>describe('/GET /api/fileSystems', () =&gt; {
  it('It should return information about the filesystem for a customer'), (done) =&gt; {
    chai.request(server)
      .get('api/fileSystems')
      .set('customer', '146')
      .end((err, res) =&gt; {
        res.should.have.status(200);
        done();
      });
  });
});
</code></pre>

<p>I attempted to use the <code>.set()</code> in order to set req.session but I believe that .set just sets the headers so I don't believe that I can update it that way unless I'm missing something.</p>
",https://stackoverflow.com/questions/55754239/how-to-mock-req-session-on-mocha-chai-api-unit-test,"['node.js', 'express', 'mocha.js', 'chai', 'chai-http']",3793,True,2,3
How to avoid spring AOP aspect being called during test,"<p>I need to avoid an aspect being called when unit testing a class. </p>

<p>I'm working with Java 8, spring 4.3.22.RELEASE and mockito. I have a @Service and a unit test for it. I also have an @Aspect that defines a pointcut on a method in the service and it is working fine when I run my application. The problem is when I run my unit test, the aspect is called and a NullPointerException is raised because of a missing dependency in the aspect. </p>

<p>Service class:</p>

<pre class=""lang-java prettyprint-override""><code>@Service
public class ContactService {

    @Autowired
    public InContactService(ContactDao contactDao) {
        this.contactDao = contactDao;
    }

    public boolean muteCall(Long contactId) {
        return contactDao.muteCall(contactId);
    }
}
</code></pre>

<p>Service test:</p>

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

  @Mock
  private ContactDao contactDao;

  private ContactService contactService;


  @Before
  public void setUp(){
    MockitoAnnotations.initMocks(this);
    contactService = new ContactService(contactDao);
  }

  @Test
  public void testMuteCall(){
    contactService.muteCall(1L);
  }
}
</code></pre>

<p>Aspect:</p>

<pre class=""lang-java prettyprint-override""><code>
@Aspect
public class ContactAspect {

    private MeterRegistry registry;

    public void setRegistry(MeterRegistry registry) {
        this.registry = registry;
    }

    @AfterReturning(pointcut = ""execution(* com.company.ContactService.muteCall(..))"", returning = ""retVal"")
    public void checkReturnContactServiceMuteCall(JoinPoint joinPoint, boolean retVal) {
        Object[] args = joinPoint.getArgs();

      registry.counter(""my.metric.mute_call"").increment();
    }
}
</code></pre>

<p>Application context:</p>

<pre class=""lang-java prettyprint-override""><code>@Configuration
public class ApplicationContext {

    @Bean
    public MeterRegistry meterRegistry() {
      return new SimpleMeterRegistry();
    }

    @Bean
    public ContactAspect contactAspect() {
        ContactAspect aspect =   Aspects.aspectOf(ContactAspect.class);
        aspect.setRegistry(meterRegistry());
        return aspect;
    }
}
</code></pre>

<p>I expected that when the test is ran the aspect is not called. Currently I get a NullPointerException when I run the test because <code>registry</code> is not defined in the aspect.</p>
",https://stackoverflow.com/questions/58138318/how-to-avoid-spring-aop-aspect-being-called-during-test,"['java', 'spring', 'junit', 'mockito', 'spring-aop']",1767,False,2,3
Can&#39;t capture stdout with unittest,"<p>I have a python3.7 script, which takes a YAML file as input and processes it depending on the instructions within. The YAML file I am using for unit testing looks like this:</p>

<pre><code>...
tasks:
  - echo '1'
  - echo '2'
  - echo '3'
  - echo '4'
  - echo '5'
</code></pre>

<p>The script loops over tasks and then runs each one, using <code>os.system()</code> call.</p>

<p>The manual testing indicates, that the output is as expected:</p>

<pre><code>1
2
3
4
5
</code></pre>

<p>But I can't make it work in my unit test. Here's how I'm trying to capture the output:</p>

<pre><code>from application import application
from io import StringIO
import unittest
from unittest.mock import patch

class TestApplication(unittest.TestCase):
    def test_application_tasks(self):
        expected = ['1','2','3','4','5']

        with patch('sys.stdout', new=StringIO()) as fakeOutput:
            application.parse_event('some event') # print() is called here within parse_event()
            self.assertEqual(fakeOutput.getvalue().strip().split(), expected)
</code></pre>

<p>When running <code>python3 -m unittest discover -s tests</code>, all I get is <code>AssertionError: Lists differ: [] != ['1', '2', '3', '4', '5']</code>.</p>

<p>I also tried using <code>with patch('sys.stdout', new_callable=StringIO) as fakeOutput:</code> instead, but to no avail.</p>

<p>Another thing I tried was <code>self.assertEqual(fakeOutput.getvalue(), '1\n2\n3\n4\n5')</code>, and here what the unittest outputs:</p>

<pre><code>AssertionError: '' != '1\n2\n3\n4\n5'
+ 1
+ 2
+ 3
+ 4
+ 5
</code></pre>

<p>Obviously, the script works and outputs the right result, but <code>fakeOutput</code> does not capture it.</p>

<p>Using <code>patch</code> as a decorator does not work either:</p>

<pre><code>from application import application
from io import StringIO
import unittest
from unittest.mock import patch

class TestApplication(unittest.TestCase):
    @patch('sys.stdout', new_callable=StringIO)
    def test_application_tasks(self):
        expected = ['1','2','3','4','5']
        application.parse_event('some event') # print() is called here within parse_event()
        self.assertEqual(fakeOutput.getvalue().strip().split(), expected)
</code></pre>

<p>Would output absolutely the same error: <code>AssertionError: Lists differ: [] != ['1', '2', '3', '4', '5']</code></p>
",https://stackoverflow.com/questions/57429514/cant-capture-stdout-with-unittest,"['python-3.x', 'stdout', 'python-unittest']",1111,True,2,3
GraphQL Type Coercion,"<p>I am currently updating some documentation we have in relation to our unit testing for GraphQL, I have come across this sentence:</p>

<p>""GraphQL does some type coercion behind the scenes. We need to mimic this type coercion in our mock data.""</p>

<p>""One example is it will convert <a href=""https://en.wikipedia.org/wiki/Bit"" rel=""nofollow noreferrer"">bits</a> to booleans. When adding mock data from B2 that includes bits, these should be changed to booleans in the mock data files, so that the unit tests will run as expected.""</p>

<p>Unfortunately the person who originally wrote this has left our business,  I understand that there is some type coercion undertaken by GraphQL but I am keen to know why this is done? Especially during the result coercion. Does anybody have any ideas what this means?</p>
",https://stackoverflow.com/questions/58936519/graphql-type-coercion,"['graphql', 'coercion']",1274,True,2,1
Unit Testing a Vue.js Router with JEST - How to mock pages?,"<p>I am trying to unit test my router routes and, following various examples, I have come up with some test cases. I have split my router out into separate modules for routes, guards and the router itself to make it easier to test, so I'm effectively only testing the route definitions here. Here's a sample of my routes...</p>

<pre><code>import Guards from './guards'
import Views from '@/views'

export default [
    {
        path: '/',
        props: true,
        components: {
            default: Views.Pages.Wizard,
            header: Views.Headers.Wizard
        },
        children: [
            {
                path: '',
                name: 'Welcome',
                component: Views.Welcome
            },
            {
                path: 'verify-guest',
                name: 'ReCaptcha',
                component: Views.ReCaptcha
            }
        ]
    },
    {
        path: '/:postcode/:id/:address',
        props: true,
        components: {
            default: Views.Pages.Main,
            header: Views.Headers.Main
        },
        children: [
            {
                path: '',
                name: 'MyHome',
                props: true,
                component: Views.MyHome,
                beforeEnter: Guards.requireSelectedProperty
            },
            {
                path: 'improvements',
                name: 'Improvements',
                props: true,
                component: Views.Improvements,
                beforeEnter: Guards.requireSelectedProperty
            }
        ]
    }
]
</code></pre>

<p>I have written some tests and the tests to load the lading page (welcome) pass but everything else seems to fail that I try - It's as if the router only ever loads the landing page.</p>

<p>The tests look like this...</p>

<pre><code>import Helper from '../../test-helper'
import { mount, createLocalVue } from '@vue/test-utils'

import VueRouter from 'vue-router'

import App from '../../templates/app-bare.vue'
import Views from '@/views'

import routes from '@/router/routes.js'
import MockGuards from '@/router/guards.js'

jest.mock('@/router/guards.js', () =&gt; ({
    requireUser: jest.fn(),
    requireFullUser: jest.fn(),
    requireCurrentProject: jest.fn(),
    requireSelectedProperty: jest.fn()
}))

jest.mock('@/views/headers/main.vue', () =&gt; ({
    name: 'MainHeader',
    render: h =&gt; h('div')
}))

jest.mock('@/views/headers/wizard.vue', () =&gt; ({
    name: 'WizardHeader',
    render: h =&gt; h('div')
}))

jest.mock('@/views/welcome.vue', () =&gt; ({
    name: 'Welcome',
    render: h =&gt; h('span')
}))

jest.mock('@/views/my-home.vue', () =&gt; ({
    name: 'MyHome',
    render: h =&gt; h('section')
}))

const localVue = createLocalVue()
localVue.use(VueRouter)

describe('router', () =&gt; {
    let router
    let wrapper

    beforeEach(() =&gt; {
        router = new VueRouter({ base: '/', routes })
        wrapper = mount(App, {
            localVue,
            router,
            mocks: Helper.vueMockPlugins()
        })
    })

    describe('can load the landing page', () =&gt; {

        it('via a path', () =&gt; {
            router.push('/')
            expect(wrapper.find(Views.Welcome).exists()).toBeTruthy()
            expect(wrapper.find(Views.Headers.Wizard).exists()).toBeTruthy()
        })

        it('via a name', () =&gt; {
            router.push({ name: 'Welcome' })
            expect(wrapper.find(Views.Welcome).exists()).toBeTruthy()
            expect(wrapper.find(Views.Headers.Wizard).exists()).toBeTruthy()
        })
    })

    /*

    None of these work - can only ever make the router render 'Welcome'

    describe('can load the root of my home', () =&gt; {

        it('via a path', () =&gt; {
            router.push('/KT18%207LJ/1/3%20The%20Crescent/')
            console.log(wrapper.html())
            expect(wrapper.find(Views.MyHome).exists()).toBeTruthy()
            expect(wrapper.find(Views.Headers.Main).exists()).toBeTruthy()
        })

        it('via a name with parameters', () =&gt; {
            router.push({ name: 'MyHome', params: {
                id: 1,
                postcode: 'KT18 7LJ',
                address: '3 The Crescent'
            } })
            console.log(wrapper.html())
            expect(wrapper.find(Views.MyHome).exists()).toBeTruthy()
            expect(wrapper.find(Views.Headers.Main).exists()).toBeTruthy()
        })
    })

    */
})
</code></pre>

<p>Any ideas? I'm very new to JEST and unit testing with Vue at all - I've much more prior experience with Jasmine and Mocha / Chai / Sinon.</p>
",https://stackoverflow.com/questions/57558032/unit-testing-a-vue-js-router-with-jest-how-to-mock-pages,"['javascript', 'vuejs2', 'jestjs']",2807,True,2,1
Jasmine HTTP tests not getting coverage on RXJS pipeline,"<h3>Problem</h3>

<p>Hey everyone, I'm adding some Karma-Jasmine unit-testing to my Angular 2 project and I cannot for the life of me get the coverage to hit the RXJS operators in my service methods.</p>

<p>The tests are using the HttpClientTestingModule and HttpTestingController.</p>

<h3>Code</h3>

<p>Here's a simple example just using the map operator.</p>

<p>MyService:</p>

<pre><code>getAssetCount(): Observable&lt;AssetModel[]&gt; {
  return this.http
    .get('/myproject/v1/asset-count')
    .pipe(map(response =&gt; response as AssetModel[]));
}
</code></pre>

<p>MyService.spec:</p>

<pre><code>service = testBed.get(MyService);
httpMock = testBed.get(HttpTestingController);
...

it('should getAssetCount', () =&gt; {
  const dummyResponse = [{...}];
  service.getAssetCount().subscribe((response: AssetModel[]) =&gt; {
    expect(response).toEqual(dummyResponse);
    const req = httpMock.expectOne(
      '/myproject/v1/asset-count'
    );
    expect(req.request.method).toBe('GET');
    req.flush(dummyResponse);
    httpMock.verify();
  });
});
</code></pre>

<h3>Result</h3>

<p>The resulting coverage:</p>

<p><img src=""https://i.imgur.com/9DEN8uA.png"" alt=""The resulting coverage""></p>

<p>I would have thought having a subscription to the observable in the test would trigger the <em>map()</em> call, but perhaps I'm misunderstanding how these mock services work.</p>

<p>From looking around, it seems like switching to the <strong>XHRBackend</strong> instead of the HttpClientTestingModule to generate dummy 200/404/etc responses could solve the issue, but besides being more boilerplate, it seems like most people were suggesting to use the TestingModule instead. </p>
",https://stackoverflow.com/questions/54560537/jasmine-http-tests-not-getting-coverage-on-rxjs-pipeline,"['angular', 'unit-testing', 'http', 'jasmine', 'rxjs']",1376,True,6,1
Unit test checking for occurrence of edge case,"<p>I have a function for raycasting on a grid with Bresenham's algorithm. I want to optimize for specific cases when the line is orthogonal or diagonal; of course, this logic won't be returned/exposed to the user.</p>

<p>Is it possible to detect the optimization edge case throught a unit test? E.g. Look for a specific <code>Debug.WriteLine</code> marker when calling the function.</p>

<p>I'm new to unit testing and I might be missing the point (testing functionality exposed to the user) but asserting that my edge cases work as expected can be invaluable - especially when actively developing the optimizations.</p>

<p>Example of what I want to achieve:</p>

<pre><code>public IEnumerable&lt;Coordinate&gt; RayCast (Coordinate source, Coordinate direction) {
    if (direction.X == 0 || direction.Y == 0) {
        Debug.WriteLine (""Orthogonal_Edge_Case"");
        //Simple iteration across 1 axis
        ...
        yield break;
    }
    if (Math.Abs(direction.X) == Math.Abs(direction.Y)) {
        Debug.WriteLine (""Diagonal_Edge_Case"");
        //Simple diagonal iteration
        ...
        yield break;
    }        
    //Standard Bresenham's algorithm
    ...
    yield break;
}
</code></pre>

<p>...</p>

<pre><code>[TestMethod]
public void TestRayCast () {
    var source = new Coordinate (0,0);

    var orthogonal = new Coordinate (0,1);
    CoordinateUtil.RayCast (source, orthogonal);
    //Check that the Orthogonal_Edge_Case marker was emitted

    var diagonal = new Coordinate (1,1);
    CoordinateUtil.RayCast (source, diagonal);
    //Check that the Diagonal_Edge_Case marker was emitted

    //Usual tests for RayCast
    ...
}
</code></pre>

<p>Note: I'm using Visual Studio 2019's unit test kit but I'm curious if this is possible with any .NET tool</p>
",https://stackoverflow.com/questions/56206494/unit-test-checking-for-occurrence-of-edge-case,"['c#', '.net', 'unit-testing']",400,True,1,2
Unit testing of a Sitecore item using fakeDb,"<p>I am currently trying to create a unit test for an override I made, but unit testing seems a bit more difficult than I expected. </p>

<pre><code>public class Extension
{
    public fallback(HttpContext context)
    {
       return new HttpContext();
    }  

    public IEnumerable&lt;SiteDefinition&gt; RunOn =&gt; new[]
    {
       ""Some"", ""Dome"", ""Gone""
    };

    public bool AllowedOnSite(string site)
    {
        bool allowed = RunOn.Any(sd =&gt; sd.Name == site);
        return allowed;
    }

    protected bool Process(HttpContext context)
    {
        var site = Context.Site.Name;
        if (Context.Domain.Name == ""sitecore"" || !AllowedOnSite(site))
        {
            return fallback(context);
        } 
     ....

    }
</code></pre>

<p>I seem to have a problem with <code>AllowedOnSite</code>, I can unit test it by itself, but not as part of <code>Process</code>, which is needed to unit test the rest of the code. </p>

<p>How do I include <code>AllowedOnSite</code> as always <code>true</code>, as part of the unit test for <code>Process</code>?</p>

<p>Unit test: </p>

<pre><code>    [Theory]
    [CustomAutoData(""Gonw"")]
    public void AllowedOnSite_IncorrectSite_ReturnFalse(string site)
    {
        //arrange
        var processor = new MediaRequestExtensions();

        //act
        processor.AllowedOnSite(site);

        //assert
        Assert.False(processor.AllowedOnSite(site));
    }
</code></pre>

<p>This works as expected, but I don't know how to make this condition <code>true</code>, when I run the <code>Process</code> method.</p>

<pre><code>[Theory]
[CustomAutoData(""http://gonw.com"",""Gonw"")]
public void Process_RequestURLIsIncorrect_Return(string url, string name)
{
    // Arrange
    var fakeSite = new Sitecore.FakeDb.Sites.FakeSiteContext(new Sitecore.Collections.StringDictionary
    {
        { ""name"", ""Some"" },
        { ""b"", ""Dome"" },
        { ""c"", ""Gone"" }
    });
    HttpRequest httpRequest = new HttpRequest(string.Empty, url, string.Empty);
    HttpResponse httpResponse = new HttpResponse(new StringWriter());
    HttpContext httpContext = new HttpContext(httpRequest, httpResponse);

    var processor = new MediaRequestExtensionsMock
    {
        GetHttpContextFunc = () =&gt; httpContext
    };
    using (new Db())
    {
        using (new Sitecore.Sites.SiteContextSwitcher(fakeSite))
        {
            Sitecore.Context.Site.Name = name;
            // Act
            processor.Process(httpContext);

            // Assert
            Assert.Equal(string.Empty, httpContext.Response.Output.ToString());
        }
    }
}
</code></pre>

<p>I trigger the right <code>if</code> statement in this test, but if I want to trigger the next one, I shouldn't trigger the first one, which I can't seem to do. </p>

<p>Could you please advise me?</p>
",https://stackoverflow.com/questions/54028213/unit-testing-of-a-sitecore-item-using-fakedb,"['c#', 'unit-testing', 'sitecore']",256,False,1,0
Pytest mock: how to patch an import statement inside a function,"<p>I have a function which imports a module inside a function. Something like following snippet</p>

<pre><code>def parse_file(self, filename):
    if(filename.endswith(""json""):
         import custom_json_parser   # &lt;--- How to patch this.? 
         return custom_json_parser.extract_file(filename)
</code></pre>

<p>For following reasons I have to patch it,</p>

<ul>
<li>I don't have <code>custom_json_parser</code> in my environment </li>
<li>Or I don't want to unit test it again while I am unit testing <code>parse_file</code> function</li>
</ul>

<p><br>
How can we patch such dynamically imported modules.?</p>

<p>I am looking for something like the following snippet. (the following snippet is just pseudocode &amp; not correct syntax wise &amp; would give exception)</p>

<pre><code>@patch(""file_name.parse_file.custom_json_parser"", autospec=True)
def test_parse_file(self, patch_custom_json_parser)
    . . .
</code></pre>

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

<p>The import statement in a module can be easily patched. But what I am struggling though is the import statement inside a function. When a function imports a module, it will not be imported as a global module and will only reside in the local memory of the function.</p>
",https://stackoverflow.com/questions/57232776/pytest-mock-how-to-patch-an-import-statement-inside-a-function,"['python', 'unit-testing', 'mocking', 'pytest']",60,False,1,0
Create a full TestSuite per interface or per Implementation,"<p>I was wondering about what is the best practices to write tests if I have multiple implementations per interface.
<br/> 
<br/> 
Have I to replicate each test per implementations or I can create an abstract class that contains all tests about the interface and then create a simple test class per implementation that extends my abstract test class? 
<br/></p>

<p>
I am following ""The art of unit testing"" written by Osherove and he always repeat that we have to keep tests, and test suites, as simple as we can, so I don't know if adding an abstract class will increase the complexity of read tests by other developers.</p>

<p>Which one of the following example is commonly accepted and more readable?</p>

<p>Sample code:</p>

<pre><code>public interface IMyInterface() 
{
    public string MyMethod(string input);
}

public class MyClassA : IMyInterface 
{
    public string MyMethod(string input) 
    {
        return input;
    }
} 

public class MyClassB : IMyInterface 
{
    public string MyMethod(string input) 
    {
        return ""hello from MyClassB"";
    }
}

public class MyClassC : IMyInterface 
{
    public string MyMethod(string input) 
    {
        throw new NotImplementedException();
    }
}
</code></pre>

<p>TestSuite 1:</p>

<pre><code>[TestFixture]
public class MyClassATest {

    [Test]
    public void MyMethod_WhenCalled_ReturnsANotNullString() 
    {
        //arrange
        MyClassA sut = new MyClassA();

        //act
        string result = sut.MyMethod(""hi"");

        //assert
        Assert.IsNotNull(result);
    }
} 

[TestFixture]
public MyClassBTest {

    [Test]
    public void MyMethod_WhenCalled_ReturnsANotNullString() 
    {
        //arrange
        MyClassA sut = new MyClassB();

        //act
        string result = sut.MyMethod(""hi"");

        //assert
        Assert.IsNotNull(result);
    }
}

[TestFixture]
public MyClassCTest {

    [Test]
    public void MyMethod_WhenCalled_ReturnsANotNullString() 
    {
        //arrange
        MyClassA sut = new MyClassC();

        //act
        string result = sut.MyMethod(""hi"");

        //assert
        Assert.IsNotNull(result);
    }
}
</code></pre>

<p>TestSuite 2:</p>

<pre><code>[TestFixture]
public abstract class IMyInterfaceTest&lt;TImplementation&gt; where TImplementation : IMyInterface {

    [Test]
    public void MyMethod_WhenCalled_ReturnsANotNullString() 
    {
        //arrange
        TImplementation sut = new MyClassC();

        //act
        string result = sut.MyMethod(""hi"");

        //assert
        Assert.IsNotNull(result);
    }
}

[TestFixure]
public class MyClassATest : IMyInterfaceTest&lt;MyClassA&gt; {}
[TestFixure]
public class MyClassATest : IMyInterfaceTest&lt;MyClassB&gt; {}
[TestFixure]
public class MyClassATest : IMyInterfaceTest&lt;MyClassC&gt; {}
</code></pre>
",https://stackoverflow.com/questions/58447904/create-a-full-testsuite-per-interface-or-per-implementation,"['c#', 'unit-testing']",54,True,1,1
How to fix &quot;Module is not available!&quot; when unit testing a Hybrid Angular app,"<p>I have a hybrid angular app and unit testing with Karma-Jasmine but we hit a small problem. I have a factory and component that is downgraded as an AngularJS app with:</p>

<pre><code>angular
    .module('app.admin.branding')
    .factory('brandingFactory', downgradeInjectable(BrandingFactory));

</code></pre>

<pre><code>angular
    .module('app.admin.branding')
    .directive('BrandNameComponent', downgradeComponent({
        component: BrandNameComponent
    }));
</code></pre>

<p>but it returns a <code>Module 'app.admin.branding' is not available!</code> upon running <code>ng test</code></p>

<p>so the solution was adding brackets.</p>

<pre><code>angular
    .module('app.admin.branding', [])
</code></pre>

<p>for both the component and factory. It works and the unit tests runs but when running on the browser and navigates to a page where the component is used an unknown error occurs and redirected to the main page. </p>

<p>So we just removed the brackets for both classes as it affected our production app. How do we fix our unit test error <code>Module 'app.admin.branding' is not available</code> or is there any workaround with the brackets approach so that it won't redirect?</p>
",https://stackoverflow.com/questions/57648602/how-to-fix-module-is-not-available-when-unit-testing-a-hybrid-angular-app,"['javascript', 'angularjs', 'angular', 'jasmine', 'karma-jasmine']",1138,False,1,2
How to Increment Count of Shared Ptr from Raw Ptr,"<p>I am working on class unit testing and encountered this problem - a premature deletion of <code>Device* device</code>/mock:</p>

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

<pre><code>Effect::~Effect()
{
    for (auto it = infoList.begin(); it != infoList.end(); ++it)
    {
         (*it)-&gt;device-&gt;Remove(this, (*it)-&gt;position);
         delete *it;
    }
    infoList.clear();
}

HRESULT Effect::Add(Device* device, ULONG position)
{
    Info* info = new Info;
    info-&gt;device = device;
    info-&gt;position= position;

    auto result = device-&gt;Add(position);
    if (result == E_FAIL) return E_FAIL;

    //some other methods being called from 'device'

    infoList.push_back(info);
}
</code></pre>

<p>And my test:</p>

<pre><code>class EffectTest: public ::testing::Test
{
public:
    void SetUp()
    {
        sut_ = std::make_unique&lt;Effect&gt;();
        deviceMock_ = std::make_shared&lt;DeviceMock&gt;();
    }

protected:
    std::unique_ptr&lt;Effect&gt; sut_;
    std::shared_ptr&lt;DeviceMock&gt; deviceMock_;
};


TEST_F(EffectTest, Add)
{
    EXPECT_CALL(*deviceMock_, Add(_).WillRepeatedly(Return(S_OK));
    EXPECT_CALL(*deviceMock_, Remove(_, _)).WillRepeatedly(Return(S_OK));

    sut_-&gt;Add(deviceMock_.get(), 90);
}
</code></pre>

<p>Since I am only passing a raw pointer (mock) <code>deviceMock_.get()</code> in Effect::Add(), reference count is not incremented. Test tears down earlier than the actual SUT so deviceMock_ is already deleted when Effect destructor is called.  My problem is.. device is still being called in Effect's destructor and therefore causes a crash:</p>

<pre><code>(*it)-&gt;device-&gt;Remove(this, (*it)-&gt;position);
</code></pre>

<p>Any thoughts on what I can do to force the <code>deviceMock_</code> to stay alive when <code>~Effect</code> is called?
Can I force deviceMock_ reference count to increment only with the raw pointer <code>Device* device</code>??</p>

<p>Please do note though that <strong>I CANNOT CHANGE THE FUNCTION SIGNATURE</strong> OF:</p>

<pre><code>HRESULT Effect::Add(Device* device, ULONG position)
</code></pre>

<p>Since this is an <strong>API</strong>.</p>

<p>Help please! Thanks!</p>
",https://stackoverflow.com/questions/57567194/how-to-increment-count-of-shared-ptr-from-raw-ptr,"['c++', 'pointers', 'googletest', 'googlemock']",251,True,1,2
How to properly run consecutive tests querying a Flask-SQLAlchemy database?,"<p>I'm setting up unit-testing for a Flask project using SQLAlchemy as ORM. For my tests I need to setup a new test database every time I run a single unit-test. Somehow, I cannot seem to run consecutive tests that query the database, even though if I run these tests in isolation they succeed.</p>

<p>I use the <code>flask-testing</code> package, and follow their documentation <a href=""https://pythonhosted.org/Flask-Testing/"" rel=""nofollow noreferrer"">here</a>. </p>

<p>Here is a working example to illustrate the problem:</p>

<p><code>app.py:</code></p>

<pre class=""lang-py prettyprint-override""><code>from flask import Flask


def create_app():
    app = Flask(__name__)
    return app


if __name__ == '__main__':
    app = create_app()
    app.run(port=8080)

</code></pre>

<p><code>database.py:</code></p>

<pre class=""lang-py prettyprint-override""><code>from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
</code></pre>

<p><code>models.py:</code></p>

<pre class=""lang-py prettyprint-override""><code>from database import db


class TestModel(db.Model):
    """"""Model for testing.""""""

    __tablename__ = 'test_models'
    id = db.Column(db.Integer,
                   primary_key=True
                   )
</code></pre>

<p><code>test/__init__.py:</code></p>

<pre class=""lang-py prettyprint-override""><code>from flask_testing import TestCase

from app import create_app
from database import db


class BaseTestCase(TestCase):
    def create_app(self):
        app = create_app()
        app.config.update({
            'SQLALCHEMY_DATABASE_URI': 'sqlite:///:memory:',
            'SQLALCHEMY_TRACK_MODIFICATIONS': False,
            'TESTING': True
        })
        db.init_app(app)
        return app

    def setUp(self):
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
</code></pre>

<p><code>test/test_app.py:</code></p>

<pre class=""lang-py prettyprint-override""><code>from models import TestModel
from test import BaseTestCase
from database import db


test_model = TestModel()


class TestApp(BaseTestCase):
    """"""WebpageEnricherController integration test stubs""""""

    def _add_to_db(self, record):
        db.session.add(record)
        db.session.commit()
        self.assertTrue(record in db.session)

    def test_first(self):
        """"""
        This test runs perfectly fine
        """"""
        self._add_to_db(test_model)
        result = db.session.query(TestModel).first()
        self.assertIsNotNone(result, 'Nothing in the database')

    def test_second(self):
        """"""
        This test runs fine in isolation, but fails if run consecutively
        after the first test
        """"""
        self._add_to_db(test_model)
        result = db.session.query(TestModel).first()
        self.assertIsNotNone(result, 'Nothing in the database')


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

<p>So, I can run <code>TestApp.test_first</code> and <code>TestApp.test_second</code> fine if run in isolation. If I run them consecutively, the first test passes, but the second test fails with:</p>

<pre><code>=================================== FAILURES ===================================
_____________________________ TestApp.test_second ______________________________

self = &lt;test.test_app.TestApp testMethod=test_second&gt;

    def test_second(self):
        """"""
        This test runs fine in isolation, but fails if run consecutively
        after the first test
        """"""
        self._add_to_db(test_model)
        result = db.session.query(TestModel).first()
&gt;       self.assertIsNotNone(result, 'Nothing in the database')
E       AssertionError: unexpectedly None : Nothing in the database
</code></pre>

<p>Something is going wrong in the database setup and teardown, but I cannot figure out what. How do I set this up correctly?</p>
",https://stackoverflow.com/questions/56001939/how-to-properly-run-consecutive-tests-querying-a-flask-sqlalchemy-database,"['python', 'unit-testing', 'sqlalchemy', 'flask-sqlalchemy', 'flask-testing']",1059,True,1,1
Cant bind to formGroup since it isn&#39;t a known property of &#39;form&#39;,"<p>I am new to Angular Unit Testing.. I am trying to test a Modal Component and I keep getting the following error: 
""Can't bind to 'formGroup' since it isn't a known property of 'form'.""</p>

<p>I've tried passing FormGroup, FormBuilder, Validators into the test providers (since they are what is being used in the code that I am testing, I added them one at a time and all together), I also tried adding ReactiveFormsModule to it (with the other providers and without them) but continue to get the error. </p>

<p>Like I said I am new to this so be gentle.</p>

<p>Component: </p>

<pre><code>import { Component, OnInit, Input, OnChanges } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Benefit } from '../../models/benefit';
import { PolicyBase } from '../../models/policy-base';
import { DatePipe } from '@angular/common';
import { DataService } from '../../services/data-service/data-service';
import { Strings } from '../../models/strings';

@Component({
  selector: 'app-benefit-edit-modal',
  templateUrl: './benefit-edit-modal.component.html',
  styleUrls: ['./benefit-edit-modal.component.css']
})
export class BenefitEditModalComponent implements OnInit, OnChanges {

  @Input() policy: PolicyBase;
  @Input() mainForm: FormGroup;
  @Input() selectedBenefitToChange: Benefit;
  @Input() selectedBenefitToChangeIndex: number;

  headerText: string;
  private isAmountEditAvailable: boolean;

  constructor(private fb: FormBuilder,
      private dataService: DataService) { }

  ngOnInit() {
    this.mainForm.addControl('changeBenefitModalForm', this.fb.group({
      benefitType: [''],
      amount: [''],
      issueDate: [''],
      ceaseAge: ['']
    })) ;
  }
</code></pre>

<p>Component.Spec.ts</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import { FormGroup, FormBuilder, Validators, FormsModule, ReactiveFormsModule, FormControl } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { Ng4LoadingSpinnerModule } from 'ng4-loading-spinner';
import { AppRoutingModule } from 'src/app/app-routing.module';

import { BenefitMock } from '../../mock-components/mock-models.ts/benefit-mock';
import { Benefit } from '../../models/benefit';
import { PolicyBase } from '../../models/policy-base';
import { DataService } from '../../services/data-service/data-service';
import { Strings } from '../../models/strings';
import { BenefitEditModalComponent } from './benefit-edit-modal.component';
import { DataServiceHelper } from '../../services/data-service/data-service-helper';
import { AlertService } from '../../services/alert-service.service';
import {WindowRef} from '../../services/window-ref-service';
import { APP_BASE_HREF } from '@angular/common';

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ 
        BenefitEditModalComponent
      ],
      imports: [
        HttpClientModule, 
        RouterTestingModule,
        Ng4LoadingSpinnerModule,
      ],
      providers: [
        DataService, 
        DataServiceHelper, 
        AlertService,
        FormGroup,
        FormBuilder,
        Validators,
        {provide: APP_BASE_HREF, useValue: '/inforceillustrations/'}, WindowRef
      ],
    })
    .compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeDefined();
  });
});
</code></pre>

<p>In app.module.ts we import FormsModule and ReactiveFormsModule and export ReactiveFormsModule... if that makes a difference.</p>

<p>App works fine, this is isolated to the unit test.</p>
",https://stackoverflow.com/questions/55922353/cant-bind-to-formgroup-since-it-isnt-a-known-property-of-form,"['angular', 'unit-testing', 'jasmine']",563,True,1,1
How to collect all &quot;instances&quot; of a static class with genric type in C#?,"<p>I'm unit-testing my c# application synchron.
Inside my application i have some static classes and i want to reset them between test cases, without writing/using a new test framework or similar.</p>

<p>While i have decided to hardcode my static resets into TestCleanup, i wonder if i can collect statics automatically during runtime.</p>

<p>As the title says, i have a static class with a generic type, so during runtime i have multiple ""instances"" of that static class for each diffrent type.</p>

<p>is there any possibility to collect all statics on runtime in general?</p>

<p>if not, is there atleast some way to get all type ""versions/instances"" of a generic static class,
so i don't have to hardcode every possibly used type?</p>

<pre><code>    public static class DialogControlService&lt;DialogType&gt;
    {
        public static DialogResult DesiredDialogResult { get; set; }
        public static dynamic Attribute { get; set; }
    }       
</code></pre>
",https://stackoverflow.com/questions/58523045/how-to-collect-all-instances-of-a-static-class-with-genric-type-in-c,"['c#', 'unit-testing', 'generics', 'static']",43,True,1,2
how to call a unit test project by a windows application?,"<p>I am new to selenium and C sharp i somehow managed to write a code that does the unit testing of my application and creates a Extent Report with all my 7 test cases output Everything is working as expected The issue is i do not want every time to log into visual studio and run the selected test case Is there any way i can create a Windows application and make the test cases run with a click of a button </p>

<p>I have a total of 7 test cases and runs perfectly when running i select them all and run the selected tests, but i need not want to go there everytime , instead want to run it from some windows application. </p>
",https://stackoverflow.com/questions/58015236/how-to-call-a-unit-test-project-by-a-windows-application,"['c#', 'selenium-webdriver', 'selenium-extent-report']",523,True,0,2
Testing localStorage using mocks or spies in Angular 7 Applications using latest jest setup,"<p>I am trying to unit test my <strong>Angular 7</strong> application using <strong><em>jest</em></strong> and want to test if a method is called by setting localStorage. But I understand that setting the real localStorage is not ideal when testing, hence have to use <em>mocks</em> or <em>spies</em>. Since I'm new to unit-testing, I would like to know if there is a better method to test this and if my approach is correct.</p>

<p>I'm mainly asking this again here is because of <a href=""https://github.com/clarkbw/jest-localstorage-mock/issues/106"" rel=""nofollow noreferrer"">this</a> issue. It says jest now provides localStorage support out of the box. So, in the following methodology, is the localStorage mocked automatically or is my approach wrong?</p>

<h3>login.component.spec.ts</h3>

<pre class=""lang-js prettyprint-override""><code>    test('Call onSubmit() when localStorage is set', () =&gt; {
        const mockSubmit = jest.spyOn(component, 'onSubmit');
        localStorage.setItem('auth', 'abcd');
        component.ngOnInit();

        expect(mockSubmit).toBeCalled();
    });
</code></pre>

<hr>

<h3>login.component.ts</h3>

<pre class=""lang-js prettyprint-override""><code>    ngOnInit(): void {
        if (localStorage.getItem('auth') !== null) {

            this.onSubmit();
        }
    }
</code></pre>

<p>Mocking and Spying in <strong><em>jest</em></strong> is a bit confusing for me, so any advice or help is appreciated.</p>
",https://stackoverflow.com/questions/56359928/testing-localstorage-using-mocks-or-spies-in-angular-7-applications-using-latest,"['angular', 'unit-testing', 'jestjs']",230,False,0,1
iOS: UnitTesting: Cocoa Touch Framework: Pass App&#39;s info plist data in XCTest,"<p>We have developed cocoa touch framework for our Apps. We have integrated some third party libraries in it. One of the third party library needs the access key which the app should have it in the <code>Info.plist</code>. </p>

<p>While writing unit tests for our developed framework, I can't able to test my few logics which has the dependancy of the 3rd party framework which needs the access key for initialization. But the access key should be passed via App's <code>Info.plist</code>.</p>

<p>Kindly let me know how to pass the Accesskey for my unit testing.  </p>

<p>FYI, My cocoa touch framework has many third party libraries integrated via cocoa pods</p>

<p>Lets say</p>

<pre><code>class Sample{
  func someMethod() -&gt; Int{
     let someObj = ThridPartyClass() // The definition is inside the Pod
   return someObj.status
  }
}
</code></pre>

<p>Here ThridPartyClass will check access key and NSLocationWhenInUseUsageDescription in Info.plist, if it is not there it will throw an error.</p>
",https://stackoverflow.com/questions/56286183/ios-unittesting-cocoa-touch-framework-pass-apps-info-plist-data-in-xctest,"['ios', 'cocoa-touch', 'xctest', 'xctestcase']",46,False,0,0
Mocking a FileStream constructor within a Web API,"<p>I have the following piece of code within the POST method of my REST API:</p>

<pre><code>using (FileStream outputFile = new FileStream(Path.Combine(fileLocation, fileName), FileMode.OpenOrCreate))
</code></pre>

<p>The problem now is that I want to mock the FileStream object but I have no clue how because I cannot inject the object through my constructor. When I do that I get the following error:
System.InvalidOperationException: Unable to resolve service for type 'System.IO.FileStream' while attempting to activate 'webservice.Controllers.DataController'.</p>

<p>I also cannot add a layer of abstraction for the constructor of the FileStream object.</p>

<p>Does any of you have some experience with this and if yes, could you help me? Because the 2 ways above are all I can find on google sadly and I rather not write files to my file system while unit testing for obvious reasons.</p>
",https://stackoverflow.com/questions/59395249/mocking-a-filestream-constructor-within-a-web-api,"['c#', 'rest', 'mocking', 'moq', 'mstest']",123,True,0,1
Newbie in Unit Testing - How would you test this code using Jest Testing?,"<p>I'm a newbie in Unit Testing.
I want to learn how to test correctly using Jest and after articles, demos, and a course on Udemy, I'm still pretty confused (especially using Jest mocking).
I should mention that all our code is outside react so it seems to confuse me even more.</p>

<p>I've written an AB test for my company and already recognized it should be easy to test but I don't think I'm doing it right. It seems like I'm just copying my original code over to test and although I feel the function is validated, it seems wrong to me.</p>

<p>Here's my code in question and the test. How would you guys who have more experience do this ""right""?</p>

<p>Thanks!</p>

<p>JS:</p>

<pre><code>let ABTestValue = 30;
ABTest();

export function ABTest() {
  const roll = Math.floor(Math.random() * 100);

  if (debugMode) {
    console.log('TimedRefresh - AB Test Issue-831 (90 and above get their refresh time changed) randomized value = ', roll);
  }

  const ABTestMappings = [
    {
      roll: 90,
      ABTestValue: 40
    },
    {
      roll: 91,
      ABTestValue: 40
    },
    {
      roll: 92,
      ABTestValue: 50
    },
    {
      roll: 93,
      ABTestValue: 50
    },
    {
      roll: 94,
      ABTestValue: 60
    },
    {
      roll: 95,
      ABTestValue: 60
    },
    {
      roll: 96,
      ABTestValue: 70
    },
    {
      roll: 97,
      ABTestValue: 70
    },
    {
      roll: 98,
      ABTestValue: 80
    },
    {
      roll: 99,
      ABTestValue: 80
    }
  ];

  if (roll &gt; 89 &amp;&amp; roll &lt; 100) {
    ABTestValue = ABTestMappings.filter((a) =&gt; a.roll === roll)[0].ABTestValue;
  }

  window.rg_version = `time${ABTestValue}`;

  if (debugMode) {
    console.log('TimedRefresh - ABTestValue - change in refresh time in seconds (30 is default) - ', ABTestValue);
  }
}
</code></pre>

<p>test.js:</p>

<pre><code>import { ABTest } from './index';

describe('ABTEST test', () =&gt; {
  it('ABTest function', () =&gt; {
    expect(ABTest).toBeDefined();
  })

  describe('test different rolls', () =&gt; {
    const ABTestMappings = [
      {
        roll: 90,
        ABTestValue: 40
      },
      {
        roll: 91,
        ABTestValue: 40
      },
      {
        roll: 92,
        ABTestValue: 50
      },
      {
        roll: 93,
        ABTestValue: 50
      },
      {
        roll: 94,
        ABTestValue: 60
      },
      {
        roll: 95,
        ABTestValue: 60
      },
      {
        roll: 96,
        ABTestValue: 70
      },
      {
        roll: 97,
        ABTestValue: 70
      },
      {
        roll: 98,
        ABTestValue: 80
      },
      {
        roll: 99,
        ABTestValue: 80
      }
    ];

    const roll = 92;
    const roll2 = 95;
    const roll3 = 99;
    const roll4 = 80;
    let ABTestValue = 30;
    let ABTestValue2 = 30;
    let ABTestValue3 = 30;
    let ABTestValue4 = 30;

    if (roll &gt; 89 &amp;&amp; roll &lt; 100) {
      ABTestValue = ABTestMappings.filter((a) =&gt; a.roll === roll)[0].ABTestValue;
    }

    if (roll2 &gt; 89 &amp;&amp; roll2 &lt; 100) {
      ABTestValue2 = ABTestMappings.filter((a) =&gt; a.roll === roll2)[0].ABTestValue;
    }

    if (roll3 &gt; 89 &amp;&amp; roll3 &lt; 100) {
      ABTestValue3 = ABTestMappings.filter((a) =&gt; a.roll === roll3)[0].ABTestValue;
    }

    if (roll4 &gt; 89 &amp;&amp; roll4 &lt; 100) {
      ABTestValue4 = ABTestMappings.filter((a) =&gt; a.roll === roll4)[0].ABTestValue;
    }

    it('if roll is 92', () =&gt; {
      if (roll) {
        expect(ABTestValue).toEqual(50);
      }
    })

    it('if roll is 95', () =&gt; {
      if (roll2) {
        expect(ABTestValue2).toEqual(60);
      }
    })

    it('if roll is 99', () =&gt; {
      if (roll3) {
        expect(ABTestValue3).toEqual(80);
      }
    })

    it('if roll is less than 90', () =&gt; {
      if (roll4) {
        expect(ABTestValue4).toEqual(30);
      }
    })
  })
})
</code></pre>
",https://stackoverflow.com/questions/58258206/newbie-in-unit-testing-how-would-you-test-this-code-using-jest-testing,"['javascript', 'unit-testing', 'mocking', 'jestjs']",574,False,0,1
React.createElement: type is invalid -- expected a string warning in unit testing with enzyme,"<p>I am unit testing my react-native app. I have a login page which consist of a component and has following props passed from container component.</p>

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

<p>I am doing snapshot testing with jest and enzyme. I passed these props to Login Component like this</p>

<pre><code>import Login from ""../index"";
import React from 'react';
import { shallow } from 'enzyme';
import globalStyles from '../../../../../global/styles';

let theme = 'DefaultTheme', wrapper;

const createTestProps = (props) =&gt; ({
    navigation: {
        navigate: jest.fn()
    },
    theme: theme,
    globalStyles: globalStyles(theme),
    session: {},
    changeScene: jest.fn(),
    changeTheme: jest.fn(),
    setUser: jest.fn(),
    logout: jest.fn(),
    ...props
});
beforeEach(() =&gt; {
    const props = createTestProps({});
    console.log(JSON.stringify(props));
    wrapper = shallow(&lt;Login {...props} /&gt;);
});
test('should render login component correctly', () =&gt; {
    expect(wrapper).toMatchSnapshot();
});
</code></pre>

<p>Test passed and snapshot is created however this warning is shown in console. </p>

<blockquote>
  <p>Warning: React.createElement: type is invalid -- expected a string
  (for built-in components) or a class/function (for composite
  components) but got: object.</p>
</blockquote>

<p>I check the export type it is default one.</p>

<pre><code>export default Login
</code></pre>

<p>The global style object is a nested style object mainly consist of styles for button, text etc and it passed as a prop in every component of my app. Need help what I'm doing wrong.</p>
",https://stackoverflow.com/questions/57082779/react-createelement-type-is-invalid-expected-a-string-warning-in-unit-testin,"['reactjs', 'react-native', 'jestjs', 'enzyme']",423,False,0,0
Jest Module Mocking in React,"<p>Getting into functional components + hooks and React Unit testing, I'm trying to do the following:</p>

<p>In one compnent, I use a function from a utility API file. On mount, Im making an async function call to my api.
In that utility API file, I want to mock the function various ways so when I render my component in the test, it will see different responses in the hooks. It will return a Promise that will resolve to different values based on what I'm testing.</p>

<p>So I'm not mocking third party modules, Im mocking my own modules.</p>

<pre class=""lang-js prettyprint-override""><code>/**
 * App.js
 */
import React, { useState, useEffect } from 'react'
import { getData } from './api'

export default function App() {
  const [data, setData] = useState()

  // get data from api on mount
  useEffect(() =&gt; {
    loadData()
  }, [])

  // get the data and set the ""data"" state variable
  const loadData = async () =&gt; {
    try {
      let d = await getData()  // &lt;---- this is what i want to mock with different values per test
      setData(d)
    } catch (err) {
      setErr('Error occurred')
    }
  }

  render (
    &lt;div&gt;
      data is: {JSON.stringify(data)}
    &lt;/div&gt;
  )
}
</code></pre>

<p>Just looking for a way to define the mock in my test file per test, so when my component is rendered it will resolve/reject to different values</p>
",https://stackoverflow.com/questions/57579333/jest-module-mocking-in-react,"['reactjs', 'mocking', 'jestjs', 'react-hooks']",2035,True,0,2
IEnumerable extension methods called on IQueryable causing performance issues,"<p>Whenever I call an extension method that accepts an IEnumerable on an IQueryable, the remainder of the process where that list/entity is being used in is incredibly slow.</p>

<p>POR QUEEEEE?!</p>

<p>The problem doesn't seem to be related to the actual structure of the code, as it's otherwise optimal, and when I spin up a new database for unit testing it, the problem doesn't seem to appear.</p>

<p>This is the extension method:</p>

<pre><code>        public static Bill FirstById(this IEnumerable&lt;Bill&gt; query, int billId)
        {
            return query.FirstOrDefault(r =&gt; r.Id == billId);
        }
</code></pre>

<p>This is how it's being used:</p>

<pre><code>        public Bill GetDeposit(int depositId)
        {
            var deposit = _depositRepository
                .AndSalesOrder()
                .AndSalesOrderCustomerContact()
                .AndDepositApplications()
                .FirstById(depositId);

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

<p>And this is how the actual entity is being used:</p>

<pre><code>        public bool ConvertDeposit(List&lt;ConvertDepositSubmitModel&gt; conversions)
        {
            if (conversions.Any())
            {
                var depositId = conversions.Select(c =&gt; c.DepositId)
                .Distinct()
                .Single();

                var billPaymentIds = conversions.Select(c =&gt; c.BillPaymentId);

                var deposit = _dataProvider.GetDeposit(depositId);

                var billPayments = _dataProvider.GetBillPayments(billPaymentIds);

                var totalConversionAmount = conversions.Sum(c =&gt; c.Amount);

                var unappliedDepositAmount = (deposit.BillStatusId == BillStatus.Credited ? 0 : deposit.TotalSell - deposit.Balance) - deposit.DepositApplications.Select(a =&gt; a.Amount).DefaultIfEmpty(0).Sum();

                if (unappliedDepositAmount != totalConversionAmount)
                {
                    throw new Exception(""The provided conversion amount would not fully convert the Deposit."");
                }

                _unitOfWork.TryTransactionAndCommit(() =&gt;
                {

                    foreach (var conversion in conversions)
                    {
                        var billPayment = billPayments.FirstByBillPaymentId(conversion.BillPaymentId);


                        this.CreateBillPaymentBill(deposit, conversion);

                        this.CreateMoneyOnAccountTransaction(deposit, conversion);

                        this.UpdateBillPayment(conversion, billPayment);
                    }

                    this.UpdateNetProceeds(billPayments);

                    this.ApplyCreditCardFees(billPaymentIds);

                    var customerCredit = this.CreateCustomerCredit(deposit, totalConversionAmount);

                    this.CreateCustomerCreditBill(deposit, customerCredit);

                    this.UpdateDeposit(deposit, totalConversionAmount);
                });
            }
            else
            {
                throw new Exception(""The provided set of bill payments was empty."");
            }

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

<p>We're seeing that each method, which has been tested rigorously, is producing the following diagnostic results: </p>

<pre><code>PV2ANZAC                
GetDeposit: 33434ms
GetBillPayments: 54ms
CreateBillPaymentBill1: 17775ms
CreateMoneyOnAccountTransaction1: 10774ms
UpdateBillPayment1: 10810ms
UpdateNetProceeds: 18130ms
ApplyCreditCardFees: 17206ms
Insert CustomerCredit: 10795ms
CustomerCredit SaveChanges: 16276ms
CreateCustomerCredit: 27075ms
CreateCustomerCreditBill: 10688ms
</code></pre>

<p>And we are definitely expecting everything to be at least an order of magnitude less than what it is.</p>
",https://stackoverflow.com/questions/55942401/ienumerable-extension-methods-called-on-iqueryable-causing-performance-issues,"['c#', 'sql', 'entity-framework', 'extension-methods']",222,False,0,2
Void return in an API request,"<p>The client and a generic method for the API requests are created here:</p>

<pre><code>public class Client : IDisposable
{
    private HttpClient _client;

    private void CreateClient()
    {
        _client = new HttpClient(); 
        _client.DefaultRequestHeaders.Accept.Clear();
        _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/json""));
        _client.DefaultRequestHeaders.Add(""KEY"", token);
    }


    public void Dispose() =&gt; _client?.Dispose();

    public enum Method { GET, POST, PUT, DELETE }

    public HttpResponseMessage Request(string url, Method method, object data, HttpContent request)
    {
        if (data != null)
            request = new StringContent(Serialize(data), Encoding.UTF8, ""application/json"");

        switch (method)
        {
            case Method.POST: return _client.PostAsync(url, request).Result;
            case Method.PUT: return _client.PutAsync(url, request).Result;
            case Method.DELETE: return _client.DeleteAsync(url).Result;
            default: return _client.GetAsync(url).Result;
        }
    }

    public Task&lt;HttpResponseMessage&gt; RequestAsync(string url, Method method, object data, HttpContent request)
    {
        if (data != null)
            request = new StringContent(Serialize(data), Encoding.UTF8, ""application/json"");

        switch (method)
        {
            case Method.GET: return _client.GetAsync(url);
            case Method.POST: return _client.PostAsync(url, request);
            case Method.PUT: return _client.PutAsync(url, request);
            case Method.DELETE: return _client.DeleteAsync(url);
            default: return _client.GetAsync(url);
        }
    }

    public string Post(string url, object data) =&gt;
        Request(url, Method.POST, data, null).Content.ReadAsStringAsync().Result;

    public Task&lt;HttpResponseMessage&gt; PostAsync(string url, object data) =&gt;
        RequestAsync(url, Method.POST, data, null);

    //UTILS

    private static string Serialize(object data) =&gt;
        data == null
            ? string.Empty
            : JsonConvert.SerializeObject(data, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
}
</code></pre>

<p>I'm trying to call these methods to specific classes, to simplify the usage of it for the customer. For example, to create a new checkout for a transaction in a credit card:</p>

<pre><code>public class Checkout : SDK
{
    private static Client client;

    public Checkout() =&gt; client = new Client();

    public static async Task Credit(object data) =&gt; 
        await client.PostAsync(url, data);
}
</code></pre>

<p>The request needs to be mounted based on a few models, that can have this structure and I'm trying to generate it in a simple way, like this:</p>

<pre><code>    public async Task Test()
    {
        var transaction = new Transaction
        {
            PaymentMethod = new PaymentMethod { Code = ""1"" },
            Application = ""Test"",
            Vendor = ""Name"",
            Customer = new Customer
            {
                //Customer details...
            },
            Products = new List&lt;TransactionProduct&gt;
            {
                //Products...
            }
        };

        var teste = Checkout.Credit(transaction);
        Console.WriteLine(teste);
    }
</code></pre>

<p>And all I get as return is:</p>

<pre><code>System.Threading.Tasks.Task`1[System.Threading.Tasks.VoidTaskResult]
Id = 1, Status = WaitingForActivation, Method = ""{null}"", Result = ""{Not yet computed}""
</code></pre>

<p>I've tried to add <code>await</code> for the <code>Checkout.Credit</code> call, but I get:</p>

<pre><code>CS0815  Test C# Cannot assign void to an implicitly-typed variable
</code></pre>

<p>Unit testing this with a simple HttpClient requests works like a charm, but I'm not being able to identify the problem on my project structure, so any help will be very much appreciated. </p>
",https://stackoverflow.com/questions/56468755/void-return-in-an-api-request,"['c#', 'dotnet-httpclient']",1327,True,0,1
Net Testing Framework and Repetition,"<p>What is the proper test protocol in writing test cases for data warehouses?</p>

<p><strong>Background:</strong></p>

<p>We are copying multiple SQL tables from Source A to Source B, with a special procedure which applies dynamic SQL. The procedure finds the columns in Table A with information_schema. columns, validate if they exist in Table B, then copy.</p>

<p>What is the proper unit testing framework? We have over 1000 tables, do we need to individually test this procedure for 1000 tables validating counts and values? and write 1000 Nunit/Xunit tests in VS Test Explorer?</p>

<p>Eg; Copying SQL table  (Customers, Payments, Inventory).</p>

<p>Customer A ---> Customer B</p>

<p>Inventory ---> Inventory B</p>

<p>Payments B ---> Payments B</p>

<p>Example: run test cases validating count, and copy results into data test table, into, using for/while loop</p>

<pre><code>insert into dbo.TestResultTable(TestFlag)
utilize for loop   -- make sure counts are equal for every copy
set @TestFlag = (select count(*) from CustomerA = select count(*) from CustomerB)
set @TestFlag = (select count(*) from InventoryA = select count(*) from InventoryB)
set @TestFlag = (select count(*) from PaymentsA = select count(*) from PaymentsB)
</code></pre>
",https://stackoverflow.com/questions/55036732/net-testing-framework-and-repetition,"['c#', 'unit-testing', '.net-core', 'nunit', 'xunit']",50,True,0,1
EntityFrameworkCore.InMemory 3.0 exception with Eager Loading,"<p>I am using EntityFrameworkCore and EntityFrameworkCore.InMemory 3.0.0-preview8.x for ASP.NET Core 3.0. When using Eager Loading, including navigation properties is working fine. But when it comes to unit testing with the EntiyFrameworkCore.InMemory database, the Include-Method throws an exception. </p>

<p>Code:</p>

<pre><code> public async Task&lt;ModuleBinding&gt; GetAsync(int id)
    {
        try
        {
            using (AppContext context = this.factory.Create())
            {
                // Return the ModuleBinding
                return await context.ModuleBinding
                           .Include(x =&gt; x.PostModule)
                           .Include(x =&gt; x.PreModule)
                           .SingleOrDefaultAsync(x =&gt; x.Id == id)
                           .ConfigureAwait(false);
            }
        }
        catch (Exception e)
        {
            Log.Error($""Failed to get entity {nameof(ModuleBinding)} with id {id}."", e);
            throw;
        }
    }
</code></pre>

<p>So this works fine when using it in my application.</p>

<p>Test:</p>

<pre><code>    [SetUp]
    public void Setup()
    {
        // Setup the in-memory database context
        DbContextOptions&lt;AppContext&gt; options = new DbContextOptionsBuilder&lt;AppContext&gt;().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;
        this.context = new AppContext(options);

        // Setup the factory to create an in-memory database
        var factory = A.Fake&lt;IAppContextFactory&gt;();
        A.CallTo(() =&gt; factory.Create()).Returns(this.context);

        // Create repository with in-memory database.
        this.repository = new ModuleBindingRepository(factory);
    }

    [Test]
    public async Task GetShouldReturnEntity()
    {
        // Arrange
        int id = this.binding1.Id;

        // Act
        ModuleBinding result = await this.repository.GetAsync(id).ConfigureAwait(false);

        // Assert
        Assert.IsNotNull(result);
        Assert.AreEqual(result, this.binding1);
    }
</code></pre>

<p>The test works also fine, as long as I remove the Includes in my GetAsync-Method. But with them, the test throws the following exception:</p>

<blockquote>
  <p>System.InvalidOperationException : Operation is not valid due to the
  current state of the object.</p>
</blockquote>

<p>Do you know if this is a bug in the preview version of the EntityFrameworkCore. InMemory NuGet-Package and if there are any open threads, yet? Or did I probably do something wrong?</p>
",https://stackoverflow.com/questions/57953905/entityframeworkcore-inmemory-3-0-exception-with-eager-loading,"['unit-testing', 'asp.net-core', 'entity-framework-core', 'in-memory-database']",180,False,0,0
MassTransit - Unit Testing a Large Payload Consumer,"<p>Using the InMemoryTestHarness, I am working on unit testing a Consumer that handles a command with a MessageData property.  Using the InMemoryMessageDataRepository to populate the MessageData property works fine however, when the consumer attempts to load the payload (message.Body.Value) I am receiving the following exception: ""The message data was not loaded: urn:msgdata:xxxxxxxxxxxxxxxxxxxxxxxxxx""}.  What is the proper way to unit test a consumer that handles commands with a MessageData property?</p>

<p>I was going to use the In-memory transport, but it doesn't seem like the right approach since the unit test(s) will not receive immediate feedback from the consumer.  Ultimately the end goal is for my unit tests to be able assert that specific exceptions are thrown or that the consumer completed successfully without errors.</p>

<pre><code>using System;
using System.Linq;
using System.Threading.Tasks;
using MassTransit;
using MassTransit.MessageData;
using MassTransit.Testing;
using Newtonsoft.Json;
using Xunit;

namespace Test
{
    public class LargePayloadConsumerTest
    {
        [Fact]
        public async Task Consumer_Should_Deserialize_Message()
        {
            var harness = new InMemoryTestHarness();
            var consumer = harness.Consumer&lt;BigMessageConsumer&gt;();
            var command = new BigMessageCommand();
            var dataRepo = new InMemoryMessageDataRepository();

            var largePayload = new BigMessagePayload()
            {
                Id = 1,
                FirstName = ""TestFirstName"",
                MiddleName = ""TestMiddleName"",
                LastName = ""TestLastName""
            };


            var json = JsonConvert.SerializeObject(largePayload);
            command.Body = await dataRepo.PutString(json);

            var thisWorks = await command.Body.Value;
            await harness.Start();
            await harness.InputQueueSendEndpoint.Send(command);

            Assert.True(harness.Consumed.Select&lt;BigMessageCommand&gt;().Any());
        }

        public class BigMessageConsumer : IConsumer&lt;BigMessageCommand&gt;
        {
            public async Task Consume(ConsumeContext&lt;BigMessageCommand&gt; context)
            {
                try
                {
                    var json = await context.Message.Body.Value;
                    var deserialized = JsonConvert.DeserializeObject&lt;BigMessagePayload&gt;(json);
                    Console.WriteLine($""{deserialized.Id}: {deserialized.FirstName} {deserialized.MiddleName} {deserialized.LastName}"");
                }
                catch (Exception e)
                {
                    //throws {""The message data was not loaded: urn:msgdata:xxxxxxxxxxxxxxxxxxxxxxxxxx""}
                    Console.WriteLine(e);
                    throw;
                }
            }
        }

        public class BigMessageCommand
        {
            public MessageData&lt;string&gt; Body { get; set; }
        }

        public class BigMessagePayload
        {
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string MiddleName { get; set; }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/56193041/masstransit-unit-testing-a-large-payload-consumer,"['c#', 'masstransit']",835,True,0,1
Why is this Mockito.mock object being called instead of being mocked?,"<p>I'm unit testing my class and encountered this situation: I mock an object using Mockito and call a method on that object. When I do that, I expect the real method not to be called, and program flow to continue. What is happening is that the real method is being called and I got a NullPointerException, because that is what would happen if I called the method with this parameter.</p>

<p>Shouldn't the Mockito.mock prevent this behavior?</p>

<p>The <a href=""https://static.javadoc.io/org.mockito/mockito-core/1.10.19/org/mockito/Mockito.html#2"" rel=""nofollow noreferrer"">Mockito documentation</a> says <code>By default, for all methods that return value, mock returns null, an empty collection or appropriate primitive/primitive wrapper value (e.g: 0, false, ... for int/Integer, boolean/Boolean, ...).</code> and <a href=""https://stackoverflow.com/a/15976157/2272160"">this answer</a> confirms my expected behavior of <code>In a mock all methods are stubbed and return ""smart return types"". This means that calling any method on a mocked class will do nothing unless you specify behaviour.</code></p>

<p>The code:</p>

<pre class=""lang-java prettyprint-override""><code>public class BrokenTest {
    @Test
    public void shouldPassBecauseItIsMocked() throws IOException {
        Object anyObject = Mockito.mock(Object.class);
        ObjectOutputStream objectOutputStream = Mockito.mock(ObjectOutputStream.class);
        objectOutputStream.writeObject(anyObject);
    }
}
</code></pre>

<p>I expected this test to pass, but i get a NullPointerException:</p>

<pre><code>java.lang.NullPointerException
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1108)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    at packageName.BrokenTest.shouldPassBecauseItIsMocked(BrokenTest.java:14)
    ...
</code></pre>

<p>(<code>BrokenTest.java:14</code> is the <code>objectOutputStream.writeObject(anyObject);</code> line actually)</p>

<p>P.S.: I am not really trying to test <code>ObjectOutputStream</code> but a class of mine that uses <code>ObjectOutputStream.writeObject(Object object)</code>. The problem really arose when I did <code>myObjectWithMockedObjectOutputStream.methodThatCallsWriteObject()</code></p>
",https://stackoverflow.com/questions/55943150/why-is-this-mockito-mock-object-being-called-instead-of-being-mocked,"['java', 'unit-testing', 'mocking', 'mockito']",1568,True,0,2
Thymeleaf: Do not render during unit test?,"<p>As I haven't gotten an answer for my other question <a href=""https://stackoverflow.com/questions/54712564/webmvctest-does-not-find-buildproperties"">here</a>, I am looking for another approach. Is there a way to no not execute or include a fragment during unit testing?</p>

<p>I want to display the version and build number in the footer of my templates, thus I have the following line:</p>

<pre><code>&lt;div class=""versionInfo""&gt;Version &lt;span th:text=""${@buildProperties.getVersion()}""&gt;&lt;/span&gt;&lt;/div&gt;
</code></pre>

<p>This works well when running the application, but during unit test I get the exception:</p>

<blockquote>
  <p>No bean named 'buildProperties' available</p>
</blockquote>

<p>In the other question I am looking for a way to get this bean during unit test, as an alternative I am now looking for a way to exclude this template during unit tests. Something like this:</p>

<pre><code>&lt;div class=""versionInfo"" th:if=""${!isUnitTest}""&gt;Version &lt;span th:text=""${@buildProperties.getVersion()}""&gt;&lt;/span&gt;&lt;/div&gt;
</code></pre>

<p>I am using the following annotations on my test class:</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(SimpleController.class)
</code></pre>
",https://stackoverflow.com/questions/54821905/thymeleaf-do-not-render-during-unit-test,"['unit-testing', 'spring-boot', 'thymeleaf']",900,True,0,2
How to test business logic layer which involves data update in database,"<p>I know my question looks like I am searching for some shortcut but actually I have searched a lot and couldn't find a resource to learn unit testing specially for business layer which involves data update in database.</p>

<p>I did get resources to learn writing unit test cases in nunit but they all were testing static data. I don't want to learn unit test writing as a beginner, I have the idea of writing unit tests in nunit, <strong>my main question is how do we test methods which involves data insert/update/delete in database? Do we actually insert data while testing? Do mocking play a role in it?</strong></p>

<p>Please help me with any resource that covers specially this case.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/56153052/how-to-test-business-logic-layer-which-involves-data-update-in-database,"['c#', 'unit-testing', 'nunit']",203,True,0,1
Testing a function based on third party service,"<p>I'm trying to figure out how to create unit tests for a function, which behavior is based on a third party service.</p>

<p>Suppose a function like this:</p>

<pre><code>def sync_check():
    delta_secs = 90
    now = datetime.datetime.now().utcnow()
    res = requests.get('&lt;url&gt;')
    alert = SlackAlert()
    last_value = res[-1]['date'] # Last element of the array is the most recent
    secs = (now - last_value).seconds

    if secs &gt;= delta_secs:
        alert.notify(""out of sync. Delay: {} seconds"".format(secs))
    else:
        alert.notify('in sync')
</code></pre>

<p>What's best practice to write unit test for this function? I need to test both if and else branches, but this depends on the third party service.</p>

<p>The first thing that come to my mind is to create a fake webserver and point to that one (changing url) but this way the codebase would include testing logic, like:</p>

<pre><code>if test:
    url = &lt;mock_web_server_url&gt;
else:
    url = &lt;third_party_service_url&gt;
</code></pre>

<p>Moreover, unit testing would trigger slack alerts, which doesn't have to happen.</p>

<p>So there I shoulde change again the codebase like:</p>

<pre><code>if secs &gt;= delta_secs:
    if test:
        logging.debug(""out of sync alert sent - testing mode"")
    else:
        alert.notify(""out of sync. Delay: {} seconds"".format(secs))
else:
    if test:
        logging.debug(""in sync alert sent - testing mode"")
    else:
        alert.notify('in sync')
</code></pre>

<p>Which I don't really like.</p>

<p>Am I missing any design to solve this problem?</p>
",https://stackoverflow.com/questions/55262146/testing-a-function-based-on-third-party-service,"['python', 'unit-testing', 'web-services', 'testing']",48,False,0,1
Could not create EventTestRunnerAdaptor when running Arquillian-test,"<p>I want to use Arquillian for unit testing my EJB's. 
When I run the test, I get the following exception: </p>

<p><code>java.lang.RuntimeException: Could not create new instance of class org.jboss.arquillian.test.impl.EventTestRunnerAdaptor</code></p>

<p>This is for a homework assignment in a course about enterprise programming. I do have the solution from the lecturer, but that fails with the same exception. 
I have tried: </p>

<ul>
<li>double checking persistence.xml and arquillian.xml for errors </li>
<li>changing JUnit-version, as suggested <a href=""https://stackoverflow.com/questions/23134354/arquillian-running-tests-not-working"">here</a> </li>
<li>ensuring the arquillian configuration is what we are told to use: 
""Wildfly Managed"" with Working Directory = $MODULE_DIR$. I have tried $MODULE_WORKING_DIR$ as well, since that was suggested by IDE (intellij). </li>
</ul>

<p><strong>Persistence.xml</strong>: </p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;

&lt;persistence xmlns=""http://xmlns.jcp.org/xml/ns/persistence""
             xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
             xsi:schemaLocation=""http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd""
             version=""2.1""&gt;


    &lt;persistence-unit name=""JTA"" transaction-type=""JTA""&gt;
        &lt;provider&gt;org.hibernate.jpa.HibernatePersistenceProvider&lt;/provider&gt;
        &lt;properties&gt;
            &lt;property name=""wildfly.jpa.default-unit"" value=""true""/&gt;
            &lt;property name=""connection.driver_class"" value=""org.h2.Driver""/&gt;
            &lt;property name=""hibernate.connection.url"" value=""jdbc:h2:./target/db""/&gt;
            &lt;property name=""hibernate.dialect"" value=""org.hibernate.dialect.H2Dialect""/&gt;
            &lt;property name=""hibernate.hbm2ddl.auto"" value=""create-drop""/&gt;
            &lt;property name=""hibernate.show_sql"" value=""false""/&gt;
        &lt;/properties&gt;
    &lt;/persistence-unit&gt;


    &lt;persistence-unit name=""DB"" transaction-type=""RESOURCE_LOCAL""&gt;

        &lt;provider&gt;org.hibernate.jpa.HibernatePersistenceProvider&lt;/provider&gt;

        &lt;properties&gt;
            &lt;property name=""connection.driver_class"" value=""org.h2.Driver""/&gt;
            &lt;property name=""hibernate.connection.url"" value=""jdbc:h2:./target/db""/&gt;
            &lt;property name=""hibernate.dialect"" value=""org.hibernate.dialect.H2Dialect""/&gt;
            &lt;property name=""hibernate.hbm2ddl.auto"" value=""create-drop""/&gt;
            &lt;property name=""hibernate.show_sql"" value=""true""/&gt;
        &lt;/properties&gt;
    &lt;/persistence-unit&gt;
&lt;/persistence&gt;

</code></pre>

<p><strong>Arquillian.xml</strong>: </p>

<pre><code>&lt;arquillian xmlns=""http://jboss.org/schema/arquillian""
            xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
            xsi:schemaLocation=""
        http://jboss.org/schema/arquillian
        http://jboss.org/schema/arquillian/arquillian_1_0.xsd""&gt;


    &lt;container qualifier=""wildfly"" default=""true""&gt;
        &lt;configuration&gt;
            &lt;property name=""jbossHome""&gt;target/downloaded_Wildfly/wildfly&lt;/property&gt;
            &lt;property name=""outputToConsole""&gt;true&lt;/property&gt;
        &lt;/configuration&gt;
    &lt;/container&gt;

&lt;/arquillian&gt;
</code></pre>

<p><strong>Part of test class I am trying to run:</strong> </p>

<pre><code>@RunWith(Arquillian.class)
public class CategoryEjbTest {

    @Deployment
    public static JavaArchive createDeployment() {
        return ShrinkWrap.create(JavaArchive.class)
                .addClasses(Category.class, Quiz.class, SubCategory.class, CategoryEjb.class, ResetEjb.class)
                .addAsResource(""META-INF/persistence.xml"");
    }

</code></pre>

<p><strong>Relevant dependencies:</strong></p>

<pre><code>&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;
&lt;!-- JEE_container for tests --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.wildfly&lt;/groupId&gt;
    &lt;artifactId&gt;wildfly-arquillian-container-managed&lt;/artifactId&gt;
    &lt;version&gt;8.2.1.Final&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;

</code></pre>

<p>I want the test to run. Instead, I get the following stacktrace and the test are ignored.  </p>

<pre><code>java.lang.RuntimeException: Could not create new instance of class org.jboss.arquillian.test.impl.EventTestRunnerAdaptor

    at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:146)
    at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:89)
    at org.jboss.arquillian.test.spi.TestRunnerAdaptorBuilder.build(TestRunnerAdaptorBuilder.java:49)
    at org.jboss.arquillian.junit.AdaptorManager.initializeAdaptor(AdaptorManager.java:21)
    at org.jboss.arquillian.junit.AdaptorManagerWithNotifier.initializeAdaptor(AdaptorManagerWithNotifier.java:19)
    at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:109)
    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.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:144)
    ... 10 more
Caused by: java.lang.RuntimeException: Could not create new instance of class org.jboss.arquillian.core.impl.ManagerImpl
    at org.jboss.arquillian.core.spi.SecurityActions.newInstance(SecurityActions.java:160)
    at org.jboss.arquillian.core.spi.SecurityActions.newInstance(SecurityActions.java:111)
    at org.jboss.arquillian.core.spi.SecurityActions.newInstance(SecurityActions.java:97)
    at org.jboss.arquillian.core.spi.ManagerBuilder.create(ManagerBuilder.java:77)
    at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.&lt;init&gt;(EventTestRunnerAdaptor.java:60)
    ... 15 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.jboss.arquillian.core.spi.SecurityActions.newInstance(SecurityActions.java:156)
    ... 19 more
Caused by: java.lang.NoSuchMethodError: org.jboss.arquillian.core.spi.ExtensionLoader.loadVetoed()Ljava/util/Map;
    at org.jboss.arquillian.core.impl.loadable.LoadableExtensionLoader.load(LoadableExtensionLoader.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:86)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:103)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:90)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:133)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:105)
    at org.jboss.arquillian.core.impl.ManagerImpl.fireProcessing(ManagerImpl.java:295)
    at org.jboss.arquillian.core.impl.ManagerImpl.&lt;init&gt;(ManagerImpl.java:92)
    ... 24 more
</code></pre>
",https://stackoverflow.com/questions/54462818/could-not-create-eventtestrunneradaptor-when-running-arquillian-test,"['maven', 'jpa', 'junit', 'jboss', 'jboss-arquillian']",1372,False,0,0
How to declare a variable that conforms to a protocol with a specific associated type?,"<p>I have a protocol for diffing two models:</p>

<pre><code>protocol Differ {
    associatedtype Model
    func diff(oldModel: Model, newModel: Model)
}
</code></pre>

<p>and a concrete class that implements the protocol:</p>

<pre><code>class CabinModelDiffer: Differ {
    func diff(oldModel: CabinModel, newModel: CabinModel) { }
}
</code></pre>

<p>where the model is just a class with some properties:</p>

<pre><code>class CabinModel { //some properties... }
</code></pre>

<p>Finally, I have a higher-level class which contains a differ:</p>

<pre><code>class CabinManager {
    var differ: CabinModelDiffer?
}
</code></pre>

<p>which I can create and assign a differ to:</p>

<pre><code>let manager = CabinManager()
manager.differ = CabinModelDiffer()
</code></pre>

<p>My problem is, I would like to be able to assign a mock differ to the manager for unit testing, like this:</p>

<pre><code>manager.differ = MockCabinModelDiffer() //Error: Cannot assign value of type
</code></pre>

<p>where my mock differ implements the protocol and uses the same associated type as the actual differ:</p>

<pre><code>class MockCabinModelDiffer: Differ {
    func diff(oldModel: CabinModel, newModel: CabinModel) { }
}
</code></pre>

<p>I cannot figure out how, or if it's even possible, to declare the differ variable in my manager so that it will accept any type that conforms to the <code>Differ</code> protocol and uses <code>CabinModel</code> as its associated type.</p>

<pre><code>class CabinManager {
    var differ: ??? //what type to declare this as?
}
</code></pre>
",https://stackoverflow.com/questions/55293833/how-to-declare-a-variable-that-conforms-to-a-protocol-with-a-specific-associated,"['ios', 'swift']",47,True,0,1
How to replace singleton design pattern,"<p>I have my own simple <code>Timer</code> implementation, when a timer is created it register itself at a <code>TimerHandler</code>,</p>

<pre><code>Timer::Timer()
: tick_counter_(0),
  target_tick_(0),
  increment_(false),
  started_(false),
  elapsed_(false) {
  handlers::TimerHandler::RegisterTimer(*this);
}
</code></pre>

<p>The function <code>RegisterTimer()</code> is static as you can see and <code>TimerHandler</code> is implemented as a singleton.</p>

<p>As you all known this creates problems at unit testing! Testing the <code>Timer</code> class and the <code>TimerHandler</code> class can be ok and not really hard. But when testing other classes which uses <code>Timer</code> it sometimes become tricky.</p>

<p>I want to get some ideas of how to solve this problem using another kind of design.</p>

<p>My only solution I have come up with currently is to use simple dependency injection by simply passing <code>TimerHandler</code>as an argument everywhere I want to use a <code>Timer</code>. But this will clutter my code badly so I hope to be able to avoid this!</p>
",https://stackoverflow.com/questions/58626742/how-to-replace-singleton-design-pattern,"['c++', 'design-patterns', 'singleton']",141,False,0,1
Adding a mock object to a Mockito spy List&lt;&gt;,"<p>Cant a Mockito <code>Spy</code> List object contains other Mock objects added to it? Any alternatives other than creating actual objects?  </p>

<p>I have a Spy List Object</p>

<pre><code>Class TestableClassTest {
@InjectMocks
TestableClass myClassUnderTest;

@Mock
MyService myService
@Spy
List&lt;MyBusinessClass&gt; myBusinessClasses;
@Mock 
MyBusinessClass myBusinessClass1;
@Mock
MyBusinessClass myBusinessClass2;

ResponseEntity result;

@Rule
MockitoRule rule = MockitoJunit.rule();

@Before
public void setup()
{
  myBusinessClasses.add(myBusinessClass1);
  myBusinessClasses.add(myBusinessClass2);
  when(myService.get()).thenReturn(myBusinessClasses);
  result = myClassUnderTest.testThisMethod();
}
 @Test
  public void resultIsReceivedWithNoException()
  { Assert.assertNotNull(result);}
}
</code></pre>

<p>But this returns nullpointer exception when doing this</p>

<pre><code>List&lt;MyBusinessClass&gt; list = someService.get(); MyBusinessClass 
myBusinessClass = list.get(0);// this is null
</code></pre>

<p>It works only if I create real Object <code>myBusinessClass1</code> and <code>myBusinessClass2</code> from <code>MyBusinessClass</code> and then add it to the <code>spy()</code> list. What I mean by this is I dont get null any more if I create the objects with <code>MyBusinessClass myBusinessClass1 = new MyBusinessClass()</code> and then add it to the list.</p>

<p><strong>Edit:</strong> 
So my questions when Unit testing a class where we return a list from a mocked Class' <code>get()</code> method. How can I put in some real concrete data into that List so that my <code>Class Method which I am testing</code> can work on that data and then I can test that my method works correctly on the data.</p>
",https://stackoverflow.com/questions/55713665/adding-a-mock-object-to-a-mockito-spy-list,"['java', 'unit-testing', 'junit', 'mockito']",3100,True,0,3
syntax error when assigning to command result to variable,"<p>I'm doing some basic unit testing with the shunit2 unit test framework. 
I'm getting the error "" syntax error near unexpected token `nodeError=$( node ""node_fake_returns/return_error.js"" )"" on the first line of my function. the function is as follows:</p>

<pre><code>function testHandleNodeReturnError{
    nodeError=$( node ""./node_fake_returns/return_error.js"" )    
    if [ grep -i ""Error"" &lt;&lt;&lt; ""$nodeError""  ]; then
        assertTrue ""true""
    fi
}
</code></pre>

<p>It is suppose to run a node script that returns an error message to stdout, then assign that output to a variable. Only this first line in the function is important. </p>

<p>I'm quite new to bash and I've messed with the formatting of this line, mostly just adding spaces in different places, but I can't seem to find what's causing the syntax error. This is probably pretty simple but if somebody could show me what might be wrong I would be greatful.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/55680241/syntax-error-when-assigning-to-command-result-to-variable,"['bash', 'testing']",43,True,0,1
CommonJS modules in,"<p>Using Nx for my Angular workspace, and noticed something, which raised my question. What's the purpose to use CommonJS modules in all <strong>tsconfig.spec.json</strong> files for libs? Checking <a href=""https://github.com/nrwl/nx-examples"" rel=""nofollow noreferrer"">Nx examples</a> all libs don't have it, only apps have included <code>""modules: ""commonjs""</code>. Is it at all still needed, if in my case I'm working with modules purely on front-end side? Can't we rely on ES2015 (ES6) already in Angular/TypeScript projects for development? After all target is ES5 obviously, like so <code>""target"": ""es5""</code>.</p>

<p>Especially, if CommonJS modules are specific only for <strong>tsconfig.spec.json</strong> files, i.e. for unit testing (Jest in my case). Removing <code>""modules: ""commonjs""</code> from my <strong>tsconfig.spec.json</strong> still makes all my unit tests passed, builded bundle is working fine, as well whilst checking during serving my application without any single error/warning.</p>
",https://stackoverflow.com/questions/54999435/commonjs-modules-in,"['angular', 'typescript', 'jestjs', 'commonjs', 'nrwl']",367,True,0,1
git wants to change LF to CRLF on windows - how do I fix this?,"<p>In <a href=""https://stackoverflow.com/questions/1967370/git-replacing-lf-with-crlf/20653073#20653073"">this answer</a>, I found the following chart:</p>

<blockquote>
  <p><strong>How <code>autocrlf</code> works</strong>:</p>

<pre><code>core.autocrlf=true:      core.autocrlf=input:     core.autocrlf=false:

        repo                     repo                     repo
      ^      V                 ^      V                 ^      V
     /        \               /        \               /        \
crlf-&gt;lf    lf-&gt;crl      crlf-&gt;lf       \             /          \      
   /            \           /            \           /            \
</code></pre>
</blockquote>

<p>I do most of the development and unit testing locally on a windows box, but the main git repository is on a unix machine, and the code is used on multiple unix machines.</p>

<p>I don't really care how the line endings appear in my windows, but I want very much to <strong>not</strong> have any CRLF in the repository.</p>

<p>I'm using PyCharm, if that makes any difference.</p>

<p>Here's my git settings:</p>

<pre><code># ~/.gitconfig :
[user]
    name = ***
    email = ***
[core]
    autocrlf = true
    eol = lf
</code></pre>

<p>and</p>

<pre><code># &lt;path-to-my-project&gt;/.git/config :
[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
    autocrlf = true
[remote ""origin""]
    url = git+ssh://***
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch ""master""]
    remote = origin
    merge = refs/heads/master
</code></pre>

<p>I'd think I have the correct setup, and yet I get the <code>warning: LF will be replaced by CRLF in</code></p>

<p>My current workaround is to <code>sftp</code> the files to a unix box and commit/push my changes from there, which is really annoying.</p>

<p>How do I fix this?</p>
",https://stackoverflow.com/questions/55542861/git-wants-to-change-lf-to-crlf-on-windows-how-do-i-fix-this,"['git', 'core.autocrlf']",1202,False,0,2
Unit testing a public method that calls multiple private methods,"<p>I want to test a public method that calls multiple private methods. What I read from all the answers to previously asked questions are varying. Some say if one encounters such situation, then probably the structure is wrong, or methods that call other methods without any logic should not be tested, etc. </p>

<p>What is not clear for me is that, should I mock these private methods (using PowerMock or any reflection based library) and unit test just this method, or should I provide different types of inputs, so that all the cases will be tested, but private methods will be invoked as well. In the latter case, is it gonna be unit testing still, since I will call other methods, as well.</p>

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

    public void publicMethod (Argument argument) {
        try {
            privateMethod1();

            privateMethod2(argument);

            privateMethod3();
        } catch (Exception ex) {
            privateMethod4();
        }
    }

}
</code></pre>
",https://stackoverflow.com/questions/56660602/unit-testing-a-public-method-that-calls-multiple-private-methods,"['java', 'unit-testing', 'junit']",1151,True,0,1
Why are @expo/vector-icons undefined when mocking expo with jest.mock?,"<p>For unit testing test w/ jest i had mocked the expo directory with the following:</p>

<pre><code>jest.mock('expo', () =&gt; {
  const { View } = require('react-native');
  const constantsMock = { // the camera class has constants defined on it
    Type: {
      back: 'BACK',
      front: 'FRONT',
    },
  };
  const cameraMock = Object.assign({}, View, { Constants: constantsMock }); // assign so we can modify a copy, not the orig View - since its passed by reference

  return {
    Permissions: {
      askAsync: jest.fn(),
    },
    Camera: cameraMock,
    CameraObject: View,
  };
});
</code></pre>

<p>which worked - but lead to the following error being logged by react:</p>

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

    Check the render method of `InKeyboardCamera`.
        in InKeyboardCamera
</code></pre>

<p>Through process of elimination (i.e., taking out parts of the rendered component and checking when it was being thrown and when it was not) i tracked down that the component which produced this error was the following: </p>

<pre><code>(&lt;SimpleLineIcons name=""refresh"" size={19} color=""white"" /&gt;)
</code></pre>

<p>which was imported with this statement:</p>

<pre><code>import { SimpleLineIcons } from '@expo/vector-icons';
</code></pre>

<p>That was strange, because i had not mocked the <code>@expo/vector-icons</code> module and it was working live but not in the test environment. But sure enough, logging out <code>console.log(SimpleLineIcons)</code> in that file resulted in <code>undefined</code>.</p>

<p>I was able to eliminate the error with this:</p>

<pre><code>jest.mock('@expo/vector-icons', () =&gt; {
  const { View } = require('react-native');
  return {
    SimpleLineIcons: View,
    Ionicons: View,
  };
});

</code></pre>

<p>but it leaves the question: why would mocking the <code>expo</code> package affect the <code>@expo/vector-icons</code> package?</p>
",https://stackoverflow.com/questions/57443897/why-are-expo-vector-icons-undefined-when-mocking-expo-with-jest-mock,"['unit-testing', 'react-native', 'jestjs', 'expo']",1627,True,0,1
Why am I getting &quot;No tests discovered&quot; with Python tests in VS Code?,"<p>This is my first few lines of code but I've coded for 20 years so I quickly wanted to get unit testing running.</p>

<p>I am using</p>

<ul>
<li>Windows 10</li>
<li>VS Code 1.30.2 from 7th January, 2019.</li>
<li>Python 3.7.2</li>
<li>Python Extension ms-python.python 2018.12.1</li>
</ul>

<p>Here's the contents of the folder I'm in.</p>

<pre><code>    Directory: C:\DATA\Git\Py\my_first_code


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       19/01/2019     21:42                __pycache__
-a----       19/01/2019     21:35            289 messing.py
-a----       19/01/2019     21:42            204 test_messing.py
-a----       19/01/2019     22:07              0 __init__.py
</code></pre>

<p>I am not in a ""venv"", as far as I know.</p>

<p>This is the contents of <code>test_messing.py</code>.</p>

<pre><code>import unittest

class Test_Math(unittest.TestCase):
    def math_multiply__when__2_times_2__then__equals_4(self):
        self.assertEqual(2 * 2, 4)

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

<p>The <code>__init__.py</code> is empty, I added it to see if it helps, and <code>messing.py</code> contains like a 8 lines of some code from a book.</p>

<p>When I try to discover the tests in VS Code I get.</p>

<blockquote>
  <p>No tests discovered, please check the configuration settings for the tests. Source: Python (Extension)</p>
</blockquote>

<p>More interestingly, running test discovery via the Python command line looks like this.</p>

<pre><code>PS C:\DATA\Git\Py\my_first_code&gt; python -m unittest discover -v -s . -p test_*.py

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK
</code></pre>
",https://stackoverflow.com/questions/54271900/why-am-i-getting-no-tests-discovered-with-python-tests-in-vs-code,"['python', 'python-unittest']",3589,True,4,1
Ember concurrency timeout hanging in qunit,"<p>In Ember I have a component that starts a never-ending poll to keep some data up to date. Like so:</p>

<pre class=""lang-js prettyprint-override""><code>export default Component.extend({
  pollTask: task(function * () {
    while(true) {
      yield timeout(this.get('pollRate'));
      this.fetchSomeData();
    }
  }).on('init')
})
</code></pre>

<p>This causes a preexisting acceptance test to get stuck in this task and run forever, even though it should be run asynchronously. The test looks like this:</p>

<pre class=""lang-js prettyprint-override""><code>test('my test', async function(assert) {
  mockFindRecord(make('fetched-model'));

  await visit('/mypage'); // gets stuck here
  await typeIn('input', 'abc123');

  assert.ok(somethingAboutThePage);
});
</code></pre>

<p>I thought at first that I had mocked the request wrong and that the test was just timing out, but it was in fact correctly polling data. Removing this task makes the acceptance test finish normally.</p>

<p>Testing this manually seems to work fine, and nothing gets stuck. Why is this happening and what is the right way to address this?</p>

<p>Saw <a href=""https://stackoverflow.com/questions/58452244/unit-testing-ember-concurrency-tasks-and-yields"">Unit testing ember-concurrency tasks and yields</a> but it doesn't really help since it only deals with unit tests.</p>
",https://stackoverflow.com/questions/58513617/ember-concurrency-timeout-hanging-in-qunit,"['ember.js', 'concurrency', 'qunit', 'ember-qunit', 'ember-concurrency']",772,True,4,1
"[phantomjs.launcher]: Fatal Windows exception, code 0xc0000005","<p>Firstly, this could be a duplicated issue from <a href=""https://stackoverflow.com/questions/42857010/phantomjs-has-crashed-fatal-windows-exception-code-0xc0000005"">PhantomJS has crashed - Fatal Windows exception, code 0xc0000005</a>. I tried the solution which was given there but it is still not working for me</p>

<p>I set up a <code>webpack 4 (4.16.5)</code> project with <code>karma 4.0.0</code> (before I used <code>karma 1.x.x</code> but the error was still the same). It starts happening since I added more unit testing to the project (although not too much test cases).</p>

<p>So here's what I get when I run the test (not all the time, for example if I run it 10 times, it usually work 2-3 times)</p>

<pre><code>PhantomJS 2.1.1 (Windows 8.0.0): Executed 0 of 37 SUCCESS (0 secs / 0 secs)
12 02 2019 14:01:09.798:ERROR [phantomjs.launcher]: Fatal Windows exception, code 0xc0000005.
PhantomJS has crashed. Please read the bug reporting guide at
&lt;http://phantomjs.org/bug-reporting.html&gt; and file a bug report.

12 02 2019 14:01:09.910:ERROR [launcher]: PhantomJS crashed.
        Fatal Windows exception, code 0xc0000005.
PhantomJS has crashed. Please read the bug reporting guide at
&lt;http://phantomjs.org/bug-reporting.html&gt; and file a bug report.

12 02 2019 14:01:09.910:ERROR [launcher]: PhantomJS stdout:

12 02 2019 14:01:09.911:ERROR [launcher]: PhantomJS stderr: Fatal Windows exception, code 0xc0000005.
PhantomJS has crashed. Please read the bug reporting guide at
&lt;http://phantomjs.org/bug-reporting.html&gt; and file a bug report.

12 02 2019 14:01:09.915:INFO [launcher]: Trying to start PhantomJS again (1/2).
PhantomJS 2.1.1 (Windows 8.0.0) ERROR
  Disconnectedreconnect failed before timeout of 2000ms (transport error)
PhantomJS 2.1.1 (Windows 8.0.0): Executed 0 of 37 DISCONNECTED (5.91 secs / 0 secs)
</code></pre>

<p>I follow the link <a href=""http://phantomjs.org/bug-reporting.html"" rel=""nofollow noreferrer"">http://phantomjs.org/bug-reporting.html</a> but can't find any valuable information.</p>

<p>Here's the content of my <code>karma.conf.ts</code></p>

<pre><code>module.exports = function karmaConfig(config) {
    config.set({

        singleRun: true,

        frameworks: [
            'jasmine'
        ],

        files: [
            'sdk/**/*.spec.ts'
        ],

        preprocessors: {
            'sdk/**/*.spec.ts': ['webpack', 'sourcemap'],
            'sdk/**/!(*.spec).ts': ['coverage']
        },

        browsers: [
            'PhantomJS'
        ],

        reporters: [
            'progress',
            'coverage',
            'junit'
        ],

        coverageReporter: {
            dir: 'coverage/',
            reporters: [
                { type: 'text-summary' },
                { type: 'html' },
                {
                    type: 'lcov',
                    dir: 'reports',
                    subdir: 'coverage'
                }
            ]
        },

        junitReporter: {
            outputFile: 'reports/junit/TEST-karma.xml',
            useBrowserName: false
        },

        transports: ['polling'],

        webpack: require('./webpack.config'),

        webpackMiddleware: {
            stats: 'errors-only'
        },

        logLevel: config.LOG_INFO,

    });
};

</code></pre>

<p>Really appreciate for any suggestion on how to solve this issue, it is really annoying</p>
",https://stackoverflow.com/questions/54651012/phantomjs-launcher-fatal-windows-exception-code-0xc0000005,"['javascript', 'typescript', 'unit-testing', 'karma-jasmine', 'karma-runner']",614,False,3,0
How can I return an object (ie. List&lt;string&gt;) from an object mocked with NSubstitute?,"<p>I am using NSubstitute to mock one of my classes/interfaces. One of the functions implemented by my class should return an object of type List. </p>

<p>But when I try to use _mockedObject.MyFunction().Returns(myList), it gives me an error saying I cannot convert between my List and an object of type Func. </p>

<p>I figured I could pass my list as a string using some ToString() function and convert it back? But that doesn't seem particularly clean as I'm expecting a list to come back from my function.</p>

<p>I saw from a video on Unit Testing with Dependency Injection that you can return objects from mocked objects with Moq (<a href=""https://www.youtube.com/watch?v=DwbYxP-etMY"" rel=""nofollow noreferrer"">https://www.youtube.com/watch?v=DwbYxP-etMY</a>). I am considering switching to that if I can't manage to return an object with NSubstitute.</p>
",https://stackoverflow.com/questions/57383809/how-can-i-return-an-object-ie-liststring-from-an-object-mocked-with-nsubsti,"['c#', 'unit-testing', 'testing', 'nsubstitute']",1019,True,2,1
How to properly write unit tests for router modules in NodeJS,"<p>I'm new to nodeJS and testing and I'd like to know how I can test my application routes properly. I've read some articles that uses <strong>supertest</strong> and <strong>chai-http</strong> to call the POST method but I believe this way would be more of an integration testing instead of unit testing my app.</p>

<p>I've read about Sinon but I'm having a hard time applying it on my code like I don't know what to stub, how I can manipulate the data from the request body so I can cover different branches of my conditional statements. I'm monitoring my code coverage with <strong>nyc</strong> so I'm also aiming to increase my unit test coverage.</p>

<p>I would appreciate it a lot if someone can guide me on this. Thanks in advance! </p>

<p><strong>server.js</strong></p>

<pre><code>const express = require('express');
const app = express();

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
    extended: true
}));

app.listen(8080, function () {
    logger.info('App is now running on port 8080');
});

app.use('/', require('./routes/generateURL.js'));

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

<p><strong>generateURL.js</strong></p>

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

router.post('/generate-url', (req, res) =&gt; {
    let result = {
        status: false
    };
    const acctId = req.body.accountId;
    const baseURL = 'http://somecompany.com/billing/';
    const dateToday = new Date();

    try {
        if (accountId) {
            result.status = true;
            result.bill = baseURL + acctId + '/' + dateToday;
        } else {
            throw 'Missing accountId';
        }
    } catch(err){
        console.log(err);
    }

    return res.send(result);
});

module.exports = router;
</code></pre>
",https://stackoverflow.com/questions/54804948/how-to-properly-write-unit-tests-for-router-modules-in-nodejs,"['node.js', 'unit-testing', 'express', 'mocha.js', 'sinon-chai']",107,False,2,0
How to simulate change of system date/time for testing purposes?,"<p>I use gitlab-ci to run my test suite, in one test I would like to simulate a
change of system date (like, going to the day after) in order to see if
everything works as expected, for example:</p>

<ul>
<li>redis keys are deleted (TTL)</li>
<li>some files are written with a new 'run number' since the date as changed</li>
<li>date and time calculation are ok</li>
<li>...</li>
</ul>

<p>How do I simulate change of system date/time for unit-testing purposes?</p>

<hr>

<p><strong>EDIT</strong>: since my code base is in Python, I found <a href=""https://github.com/spulec/freezegun"" rel=""nofollow noreferrer"">freezegun</a> and <a href=""https://github.com/simon-weber/python-libfaketime"" rel=""nofollow noreferrer"">python-libfatketime</a>; the former can probably do the trick for my  Python code, and the latter is more powerful since it is intercepting system calls so theoretically I can use it for testing redis TTL if I start redis after the patches are applied.</p>
",https://stackoverflow.com/questions/54949547/how-to-simulate-change-of-system-date-time-for-testing-purposes,"['linux', 'unit-testing', 'testing', 'automated-tests']",2095,False,2,3
How do you view profile information with MiniProfiler from unit tests,"<p>I am trying to profile various portions of a .Net Core 2.2 library. I decided to use unit testing since I have unit tests for many of the areas I want to profile. I am trying to use StackExchange's MiniProfiler but I don't see anything in the documentation about how to view the profiling results.</p>

<p>I created a property on my test fixture:
    public MiniProfiler Profiler
    {
        get;
        private set;
    }</p>

<p>and populated it in the constructor of the fixture:</p>

<pre><code>this.Profiler = MiniProfiler.StartNew(""CRMODataDataSource Profiler"");
</code></pre>

<p>Then call my code I want to profile:</p>

<pre><code>        using (Fixture.Profiler.Step(""TestDefaultWithDynamic""))
        {
            testValue =
                (testEntity.HasPrimaryKey() == true)
                &amp;&amp; testEntity.GetPrimaryKey().KeyValues.All(v =&gt;
                {
                    if (null != v.Value)
                    {
                        return !CrmEntityFixture.ValueIsDefault((dynamic)v.Value);
                    }
                    return false;
                }
                );
        }
        Assert.True(testValue);
</code></pre>

<p>I installed the nuget packages using:
    Install-Package MiniProfiler.AspNetCore -IncludePrerelease</p>

<p>The <a href=""https://miniprofiler.com/dotnet/"" rel=""nofollow noreferrer"">documentation</a> shows a UI and talks about it but never mentions how to start the UI. I have searched the output folders and didn't find any files that resemble profile data.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/56507623/how-do-you-view-profile-information-with-miniprofiler-from-unit-tests,"['unit-testing', 'mvc-mini-profiler']",334,True,2,1
How to integrate Qt&#39;s windeployqt as part of Visual Studio build workflow?,"<p>Every time a new Qt project is built for first time in Visual Studio, even with the VS Tools installed, I have to copy some Qt-related binary files (Qt5Core.dll, platform files...). Otherwise, when running from Visual Studio, <code>Qt5Core.dll</code> (or debug one) are correctly found but not the platform DLL:</p>

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

<p>Obviously, it would also fail when running done from outside the IDE, for example, during unit testing on automated builds.</p>

<p>Qt's has a tool to do so, called <a href=""https://doc.qt.io/Qt-5/windows-deployment.html"" rel=""nofollow noreferrer""><code>windeployqt</code></a>, which basically looks for dependencies (Qt) and copy them. For example:</p>

<pre><code>c:\Qt\Qt5.12.1\bin\windeployqt c:\projects\qt-project\Release --release
</code></pre>

<p>will analyze executables in <code>c:\projects\qt-project\Release</code> and copy required DLLs, plugins, translations and other related binaries to such location.</p>

<p>I'm interested in how to integrate <code>windeployqt</code> into the build workflow of Visual Studio so this process is automatic (even when checked out in different computers).</p>
",https://stackoverflow.com/questions/54788631/how-to-integrate-qts-windeployqt-as-part-of-visual-studio-build-workflow,"['visual-studio', 'qt', 'deployment', 'qt5', 'windeployqt']",1559,True,2,2
Video tag with controls attribute causing unit tests to fail,"<p>I am building a webapp with Angular 7.2.4. I am using the default unit testing library that the angular CLI (7.3.1) comes with. </p>

<p>I keep running into this error as a failure when the unit tests run: 
<code>An error was thrown in afterAll\nResizeObserver loop limit exceeded thrown</code></p>

<p>It seems that the <code>controls</code> attribute on one of the video inputs is causing this. If I remove the controls attribute all tests pass. I have no idea how to get around this as I need to use the video controls. </p>

<p>Can someone please point me in the right direction on how to resolve this without building a custom video player? </p>

<p>For reference here is the component (which is literally just a wrapper around the video player) </p>

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

<pre><code>&lt;video preload=""auto""
       controls
       #videoPlayer
       controlsList=""nodownload""
       (ended)=""videoEnded($event)""&gt;
  &lt;source [src]=""getVideoSource()"" type=""video/mp4""/&gt;
&lt;/video&gt;
</code></pre>

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

<pre><code>import {Component, ElementRef, Input, OnChanges, OnInit, ViewChild} from '@angular/core';

import {ConfigService} from '../config.service';

@Component({
  selector: 'app-video',
  templateUrl: './video.component.html',
  styleUrls: ['./video.component.scss']
})
export class VideoComponent implements OnInit, OnChanges {

  @ViewChild('videoPlayer') videoPlayer: ElementRef;
  @Input() src: string;
  @Input() ended: (event: Event) =&gt; void;

  constructor(private cs: ConfigService) {
  }

  ngOnInit() {
    this.videoPlayer.nativeElement.src = this.getVideoSource();
  }

  ngOnChanges() {
    this.videoPlayer.nativeElement.src = this.getVideoSource();
  }

  getVideoSource(): string {
    return this.cs.getConfig('videosUrl') + this.src;
  }

  videoEnded($event) {
    if (this.ended) {
      this.ended($event);
    }
  }

}
</code></pre>

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

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { VideoComponent } from './video.component';

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ VideoComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(VideoComponent);
    component = fixture.componentInstance;
    component.src = '';
    component.ended = () =&gt; {};
    fixture.detectChanges();
  });

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

  afterEach(() =&gt; {
    fixture.destroy();
  });

});
</code></pre>

<p><strong>UPDATE:</strong> It would appear that this is a Chrome issue. This does not happen in firefox or safari</p>
",https://stackoverflow.com/questions/55170154/video-tag-with-controls-attribute-causing-unit-tests-to-fail,"['javascript', 'angular', 'unit-testing', 'html5-video', 'karma-jasmine']",886,False,2,2
How to mock method inside tested function using codeception,"<p>I'm just trying to implement unit testing to my PHP application and really can't figure out how it works with mock/stub and Codeception</p>

<p>So I'm using Laravel and want to add testing to an API endpoint like this</p>

<pre><code>$I-&gt;sendGET('/user/inventory/&lt;user_id&gt;');
</code></pre>

<p>Then in the controller I have function to authenticate the user, something like</p>

<pre><code>public function getUserInventory($userId) {

    if ($this-&gt;authenticateUser($userId)) 
    {
        do some logic...
        if ($success) {
            return $good_data;
        } else {
            return $bad_data;
        }
    } 
    return false;
}
</code></pre>

<p><code>authenticateUser</code> function is not relevant to the test and I just want to mock the return to <code>true</code> or <code>false</code> so I can test the actual logic on whether it should return <code>$good_data</code> or <code>$bad_data</code>, is that possible?</p>

<p>I've tried to declare stub object before calling the <code>sendGET</code> function like this </p>

<pre><code>Stub::make(
    'App\Http\Controllers\Controller',
    ['authenticateUser' =&gt; true],
    $this
);

$I-&gt;sendGET('/user/inventory/&lt;user_id&gt;');
</code></pre>

<p>but it doesn't seem to use the stub object inside the <code>getUserInventory</code> function when I ran the test. </p>

<p>Is there any way to use stub/mock method inside the <code>$I-&gt;sendGET('/user/inventory/&lt;user_id&gt;');</code> test?</p>

<p>Hopefully my question make sense</p>
",https://stackoverflow.com/questions/57433914/how-to-mock-method-inside-tested-function-using-codeception,"['php', 'unit-testing', 'laravel-5', 'codeception']",2079,False,2,0
Unable to do unit testing of retry parameter of AmazonS3Client,"<p>I have build a nifi custom processor.to put a object in AWS s3 bucket.(used AmazonS3Client in AWS SDK)
In  the ClientConfig , i have chnaged the MaxErrorRetry to 4(default AWS gives 3).</p>

<p>testcase Scenario:
I want do a unit testing(using Junit, Mokito) , to test this chnaged retry parameter is working or not.</p>

<p>Means, If i am getting 5**(Errror from server side) error then it will again attemp to upload the file to s3 and it will continue to try 4 times as my configured paramater whihc is 4 times.</p>

<p>I also want another clarification , while uploading the file s3 bucket, if i am giving wrong bucketname(errror related to client side 4**), then it will rerty 4 times or not.</p>

<p>Thanks in advance for help</p>

<pre><code>@Test
    public void testRetryLogin() {
        final TestRunner runner = TestRunners.newTestRunner(new myprocessor);


// need the logiv`enter code here`
        runner.run();
       // will do assert

    }
</code></pre>
",https://stackoverflow.com/questions/58355847/unable-to-do-unit-testing-of-retry-parameter-of-amazons3client,"['java', 'amazon-web-services', 'amazon-s3', 'junit4', 'apache-nifi']",403,False,2,0
How to mock a derived class that calls its base class methods?,"<p>I am unit testing a derived class and want to <code>EXPECT_CALL</code> that a certain method belonging to its base class is called.</p>

<p>For example:</p>

<pre><code>class Base {
public:
    void move(int x, int y);
};

class Derived: public Base{
public:
    RESULT update();

private:
    int age;
};

HRESULT Derived::update(void) {
    int param1 = 5, param2 = 10;
    move(param1, param2);
    age++;

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

<p>I can't just create a mock for Derived and expect <code>move</code> since there is no dependency and the actual move() will be called.</p>

<p>How can I be able to mock <code>move()</code>?  My end goal is that I need to expect move() to be called with CORRECT parameter values (<code>param1 and param2</code> in this case).</p>

<p>Of course this isn't the actual code but just a representation</p>

<p>I know this is not good design as far as UT is concerned, but this is to test some legacy code I am not allowed to reformat (but need to make UT). So being able to mock and test move() is the best option I have really.</p>

<p>Help will be appreciated. Thanks!</p>
",https://stackoverflow.com/questions/56750603/how-to-mock-a-derived-class-that-calls-its-base-class-methods,"['c++', 'googletest', 'googlemock']",788,True,2,2
Cloning a hashmap using a reference to another hashmap,"<p>I have a reference to a hashmap (<code>data</code> in the code below) which I want to clone into a new, owned hashmap. Cloning the reference gives me a new reference, which is not what I need.</p>

<p>I also tried doing an iter + map over the <code>data</code> reference and cloning the key and value pairs individually followed by a collect, but that also does not work. Here is a minimal working example:</p>

<pre class=""lang-rust prettyprint-override""><code>use core::cell::Cell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::rc::Rc;

struct Dummy&lt;K, V&gt; {
    dirty: Rc&lt;Cell&lt;bool&gt;&gt;,
    data: Cell&lt;Option&lt;HashMap&lt;K, HashSet&lt;V&gt;&gt;&gt;&gt;,
}

impl&lt;K, V&gt; Dummy&lt;K, V&gt; {
    fn persist(&amp;self, prefix: &amp;str, data: &amp;HashMap&lt;K, HashSet&lt;V&gt;&gt;) {
        self.dirty.set(true);
        self.data.set(Some(data.clone()));
    }
}
</code></pre>

<p>which gives the following error:</p>

<pre><code>error[E0308]: mismatched types
  --&gt; src/lib.rs:14:28
   |
14 |         self.data.set(Some(data.clone()));
   |                            ^^^^^^^^^^^^ expected struct `std::collections::HashMap`, found reference
   |
   = note: expected type `std::collections::HashMap&lt;K, std::collections::HashSet&lt;V&gt;&gt;`
              found type `&amp;std::collections::HashMap&lt;K, std::collections::HashSet&lt;V&gt;&gt;`
</code></pre>

<p>(<a href=""https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=01f983a97475341f0525803dc687fc4b"" rel=""noreferrer"">Permalink to the playground</a>)</p>

<p>The purpose of this code is to observe the contents of the hashmap on through the <code>Dummy</code> struct, which is used for unit testing.</p>

<p>I guess this problem is because given the generic types there is no way to determine how to deeply clone the key and value objects? </p>

<p>Is there a way to create a new hashmap given a reference to an existing hashmap?</p>
",https://stackoverflow.com/questions/59373165/cloning-a-hashmap-using-a-reference-to-another-hashmap,"['rust', 'reference', 'hashmap']",8001,True,6,1
What additional test cases can be included in my Unit Testing?,"<p>Given the following function <code>RhymeOrNot</code> with contains three parameters: a file defined as a string, the first word defined as a string, and the second word defined as a string. This function will return a boolean indicating whether or not the words rhyme. A word rhyme with another word if the last vowel and every word after are the same. Both words need to be in the file containing a dictionary of the word and their pronunciation. If neither words or in the file, return false. </p>

<p>Sample File Looks Similar To This:</p>

<pre><code>PHOTOGRAPH  F OW1 T AH0 G R AE2 F
STAFF  S T AE1 F
</code></pre>

<p>Here is a Unit Test in Python to test the function</p>

<pre><code>class TestRhyme(object):
    def Test(self):
        assert RhymeOrNot(""dictionary.txt"", ""CAT"", ""HAT"") == True
        assert RhymeOrNot(""dictionary.txt"", ""PHOTOGRAPH"", ""STAFF"") == True
        assert RhymeOrNot(""dictionary.txt"", ""TRAIN"", ""SUSTAIN"") == True
        assert RhymeOrNot(""dictionary.txt"", ""GIRL"", ""BOY"") == False
        assert RhymeOrNot(""dictionary.txt"", ""START"", ""HEART"") == True
        assert RhymeOrNot(""dictionary.txt"", ""BERRY"", ""BUILD"") == False
        assert RhymeOrNot(""dictionary.txt"", ""CLASS"", ""PASS"") == True
</code></pre>

<p>Updated:</p>

<pre><code>class TestRhyme(object):
    def Test(self):
        assert RhymeOrNot(""dictionary.txt"", ""CAT"", ""HAT"") == True
        assert RhymeOrNot(""dictionary.txt"", ""PHOTOGRAPH"", ""STAFF"") == True
        assert RhymeOrNot(""dictionary.txt"", ""TRAIN"", ""SUSTAIN"") == True
        assert RhymeOrNot(""dictionary.txt"", ""GIRL"", ""BOY"") == False
        assert RhymeOrNot(""dictionary.txt"", ""START"", ""HEART"") == True
        assert RhymeOrNot(""dictionary.txt"", ""BERRY"", ""BUILD"") == False
        assert RhymeOrNot(""dictionary.txt"", ""CLASS"", ""PASS"") == True
        assert RhymeOrNot(""dictionary.txt"", """", """") == False
        assert RhymeOrNot(""dictionary.txt"", """", ""HAPPY"") == False
        assert RhymeOrNot(""dictionary.txt"", ""HARRYPOTTER"", ""BTW"") == False
        assert RhymeOrNot(""dictionary.txt"", ""AIRPLANE"", """") == False
        assert RhymeOrNot(""dictionary.txt"", ""ABCDE"", ""FGHJI"") == False
        assert RhymeOrNot(""dictionary.txt"", ""air"", """") == False
        assert RhymeOrNot(""dictionary.txt"", """", ""sofa"") == False
        assert RhymeOrNot(""dictionary.txt"", ""&amp;#116;&amp;#114;&amp;#97;&amp;#105;&amp;#110;"", ""&amp;#102;&amp;#108;&amp;#121;"") == False
        assert RhymeOrNot(""dictionary.txt"", ""chair"", ""declare"") == True
        assert RhymeOrNot(""dictionary.txt"", ""slam"", ""ham"") == True
        assert RhymeOrNot(""dictionary.txt"", ""StAiR"", ""PaIr"") == True
        assert RhymeOrNot(""dictionary.txt"", ""pen"", ""hen"") == True
        assert RhymeOrNot("""", ""pen"", ""hen"") == FileNotFoundError
        assert RhymeOrNot(""def"", ""pen"", ""hen"") == FileNotFoundError
</code></pre>

<p>What other additional test cases can I incorporate in my Unit Testing? I want to test every possible test cases out there that follows the function <code>RhymeOrNot</code>.</p>
",https://stackoverflow.com/questions/54717945/what-additional-test-cases-can-be-included-in-my-unit-testing,"['python', 'file', 'unit-testing']",47,True,1,1
What is the correct way to inject dependency in Angular parameter,"<p>i just started learning angular last year, and i stumbled upon angular dependency injection. The case is i need to inject dependency that require some parameter to instantiate. Currently i'm doing it like this:</p>

<p>some-dependency.service.ts</p>

<pre><code>import { Injectable } from '@angular/core';
import { ConfigService } from 'app/services/config.service';
import { Client } from 'some-dependency';

@Injectable({
    providedIn: 'root',
    useFactory: (config:ConfigService) =&gt; new Client({
        host:config.clientURL, maxRetries: config.maxRetry
    }),
    deps: [ConfigService]
})

export class SomeDependencyService extends Client {

}
</code></pre>

<p>another-service.service.ts</p>

<pre><code>import { Injectable } from '@angular/core';
import { SomeDependencyService } from 'app/services/some-dependency.service';

@Injectable({
  providedIn: 'root'
})

export class SomeService {

    constructor( private deps: SomeDependencyService ) {}

    getSomething() {
        return this.deps.get('something');
    }
} 
</code></pre>

<p>The code works fine, and i can get <code>Client</code> instance without instantiate it inside <code>another-service.ts</code> with no problem plus i can easily mock it for unit testing, but i'm not sure if this is the correct way to do DI with parameter in Angular, and i'm also not sure if this code will generate any unexpected behaviour.</p>

<p>While i can just import the dependency inside the services that need it, and instantiate the dependency locally, but that would be very annoying if i have a lot services (and components) that require the dependency.</p>

<p>thanks</p>
",https://stackoverflow.com/questions/59207663/what-is-the-correct-way-to-inject-dependency-in-angular-parameter,"['angular', 'typescript', 'dependency-injection']",35,False,1,0
Is there a way to test for console.log entires,"<p>I'am currently trying to implement end to end unit testing for an App my team has. The app takes embedded video content on a website and records events that happen on the player.</p>

<p>Example: When our trackscript server is running we can go to <a href=""https://www.thrillist.com/"" rel=""nofollow noreferrer"">https://www.thrillist.com/</a> and when a video is playing we can monitor the events that take place on the player such as mute, fastforward, pause, ect... and log them to the console.</p>

<p>We are trying to implement unit tests to check that the data being logged on these events is happening. </p>

<p>We are currently looking into BrowserStack to check cross browser compatibility and perhaps use a framework such as nightwatch.js for writing the unit tests. </p>

<p>My question is, can you write nightwatch tests that check for logs made to the console? </p>
",https://stackoverflow.com/questions/57792428/is-there-a-way-to-test-for-console-log-entires,"['javascript', 'nightwatch.js', 'browserstack']",128,False,1,1
Relationship between Unit Testing &amp; End-to-End (Integration per se) while following BDD,"<p>My question is also related to who does what in typical BDD. My understanding, Product owner comes up with User Story (may or may not in Gherkin), QA writes Scenarios for End-to-End testing(in feature files), Dev writes his code (how and where, does he follow BDD as well?). At this point if the Dev writes the automated Unit Testing, whether this can be leveraged by the QA for End-to-End or they can be absolutely different? </p>

<p>My question is how the Dev and QA leverage each other's work in terms of coding while following BDD. I am not sure how to connect the dots.</p>

<p>Lets take the example of a JAVA based application and QA is already using Cucumber with Selenium Webdriver for automated testing. </p>
",https://stackoverflow.com/questions/54913972/relationship-between-unit-testing-end-to-end-integration-per-se-while-follow,"['java', 'unit-testing', 'cucumber', 'bdd', 'gherkin']",498,True,1,3
How to check test cases if no verification possible,"<p>I'm learning about unit testing and I came across the problem to create a final check on wether a test case is correct or not. Usually I try to create a verification, like through an <code>assertEquals()</code>. But what is recommended to do when it's not possible to test it like this?</p>

<p>I have a class like this:</p>

<pre><code>public class Landlord {

    private Map&lt;String, ChannelHandlerContext&gt; currentOccupier;
    private static Landlord instance;

    public Landlord() {
        currentOccupier = new HashMap&lt;&gt;();
    }

    public static Landlord getInstance {
        //return instance
    }

    public void add(Occupier occupier){
        currentOccupier.put(""test"", occupier.getChannelHandlerContext());    
    }
}
</code></pre>

<p>And now I try to test the method like this:</p>

<pre><code>public class LandlordTest {

    private Landlord landlord;
    @Mock
    private Occupier occupier;
    @Mock
    private ChannelHandlerContext channelHandlerContext;


    @BeforeEach
    void setUp() {
        occupier = mock(Occupier.class);
        channelHandlerContext = mock(ChannelHandlerContext.class);

        landlord = Landlord.getInstance();

        when(occupier.getChannelHandlerContext()).thenReturn(channelHandlerContext);
    }

    public void add(Occupier occupier){
        addedOccupier.put(occupier.getChannelHandlerContext()); 
        //adding succeded
    }

}
</code></pre>

<p>Maybe in this short example it wouldn't be needed to test it, but is there a way to verify that the add method was successful? Normally in these kind of cases, I'd try something like: <code>assertEquals(currentOccupier.size(), 1)</code>, but here I can't access the hashMap of the instance to do it like this. Is there another way to verify the correct behaviour of adding it? </p>
",https://stackoverflow.com/questions/56153735/how-to-check-test-cases-if-no-verification-possible,"['java', 'testing', 'junit', 'mockito']",45,True,1,1
How to configure a maven project for unit testing Spring Cloud functions,"<p>What's the right way to set up the Spring Cloud project with the functions and unit testing?</p>

<p>I want to create a standalone web application with Spring Cloud Function and have a possibility to cover it by the unit tests. I've set it up according to the <a href=""https://cloud.spring.io/spring-cloud-function/reference/html/spring-cloud-function.html"" rel=""nofollow noreferrer"">reference guide</a>:</p>

<ol>
<li>I created the maven project with the <code>spring-boot-starter-parent</code>.</li>
<li>Added <code>spring-cloud-dependencies</code> to a dependencyManagement.</li>
<li>Added <code>spring-cloud-starter-function-web</code> starter.</li>
<li>Added testing dependencies:

<ul>
<li>Added <code>junit-bom</code> for the 5th version to a dependencyManagement.</li>
<li>Added <code>spring-boot-starter-test</code> starter and excluded <code>junit</code> from it.</li>
<li>Added <code>junit-jupiter</code> and <code>mockito-junit-jupiter</code> dependencies.</li>
</ul></li>
</ol>

<p>My <code>FunctionapApplication</code> contains the bean <code>uppercase</code> as function, the exmaple from docs. I'm trying to make a test for it.</p>

<pre class=""lang-java prettyprint-override""><code>@ExtendWith(SpringExtension.class)
@FunctionalSpringBootTest
@AutoConfigureWebTestClient
class FunctionsApplicationTest {

  @Autowired
  WebTestClient client;

  @BeforeEach
  void setUp() {
    // set up
  }

  @Test
  void shouldCallFunctionViaWeb() {
    client.post().uri(""/"").body(""foo"", String.class).exchange()
      .expectStatus().isOk().expectBody(String.class).isEqualTo(""FOO"");
  }

}
</code></pre>

<p>But it fails to start a context and finds <code>WebTestClient</code>:</p>

<pre><code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.example.file.FunctionsApplicationTest': Unsatisfied dependency expressed through field 'client'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.test.web.reactive.server.WebTestClient' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:98)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassBasedTestDescriptor.java:337)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:342)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:337)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:313)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:743)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:742)
    at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:647)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:336)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:259)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:252)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$3(ClassBasedTestDescriptor.java:251)
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:29)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:106)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:105)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:69)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:107)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:107)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:75)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    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:1257)
    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:128)
    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)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.test.web.reactive.server.WebTestClient' 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:1695)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
    ... 67 more

</code></pre>

<p>and a small piece from a conditions evaluation report:</p>

<pre><code>Unconditional classes:
----------------------

    org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration

    org.springframework.cloud.client.ReactiveCommonsClientAutoConfiguration

    org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClientAutoConfiguration

    org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration

    org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration

    org.springframework.cloud.client.serviceregistry.ServiceRegistryAutoConfiguration

    org.springframework.cloud.autoconfigure.LifecycleMvcEndpointAutoConfiguration

    org.springframework.cloud.client.CommonsClientAutoConfiguration

    org.springframework.cloud.commons.httpclient.HttpClientConfiguration

    org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
</code></pre>

<p>What am I doing wrong?</p>

<p><strong>UPDATE</strong><br>
I guess the issue with <code>@AutoConfigureWebTestClient</code> and injecting <code>WebTestClient</code>.</p>
",https://stackoverflow.com/questions/59388822/how-to-configure-a-maven-project-for-unit-testing-spring-cloud-functions,"['java', 'spring', 'maven', 'spring-cloud', 'spring-cloud-function']",1308,True,1,1
"Basic concept of jasmine, protractor and mocha","<p>I am new to e2e testing. I'm using protractor for angular 4 testing. I am much confused about jasmine, mocha and protractor. My understanding with jasmine and protractor is that jasmine is a testing framework. <strong>It can not be used stand alone without any test runner</strong> i.e. protractor(e2e testing) or karma(unit testing).
<strong>Protractor is a test runner</strong> that uses jasmine framework. It interacts with browser, without protractor (or any other test runner), jasmine can't interact with browser in e2e testing.</p>

<p>On the other hand, mocha is also a testing framework that has its own test runner i.e. mocha-CLI. It doesn't need any test runner and can be used stand alone for testing.
Can any one help me in getting the right concept?</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/59450830/basic-concept-of-jasmine-protractor-and-mocha,"['angular', 'jasmine', 'protractor', 'mocha.js', 'e2e-testing']",741,True,1,1
Flink - Integration testing with multiple sources,"<p>I have a Flink job, which I am integration testing using the approach described here: <a href=""https://ci.apache.org/projects/flink/flink-docs-stable/dev/stream/testing.html#integration-testing"" rel=""noreferrer"">https://ci.apache.org/projects/flink/flink-docs-stable/dev/stream/testing.html#integration-testing</a></p>

<p>The job takes its input from two sources, which are combined in a <code>CoFlatMapFuntion</code>.  In the test environment, I'm currently using two simple SourceFunctions to emit the values, however this doesn't provide any control over the order in which the events are emitted.  This is necessary in order to properly test the functionality of the job.</p>

<p>How can I modify my test to ensure one source function emits all of its data before the second?</p>

<p>I've seen the approach suggested in <a href=""https://stackoverflow.com/questions/52153863/integration-test-for-complex-topology-multiple-inputs-in-flink"">Integration test for complex topology (multiple inputs) in Flink</a>, this is fine for unit testing but I'm looking for a solution which allows me to integration test the entire job.</p>
",https://stackoverflow.com/questions/54908476/flink-integration-testing-with-multiple-sources,"['java', 'apache-flink', 'flink-streaming']",1803,True,5,1
Simple Mock Function of Passport using Jest,"<p>I am currently unit testing all my routes, including some that are using a custom passport authentication function. I am trying to mock the passport function to test error handling, but I keep getting the error:</p>

<pre><code>TypeError: _passport.default.authenticate(...) is not a function
</code></pre>

<p>Here is the actual code that runs in <code>/controllers/users.js</code>:</p>

<pre><code>export const persistentLogin = (req, res, next) =&gt; {
  // Authenicate the cookie sent on the req object.
  passport.authenticate('jwt', { session: false }, async (authErr, user) =&gt; {
    // If there is an system error, send 500 error
    if (authErr) return res.sendStatus(500);

    // If no user is returned, send response showing failure.
    if (!user) {
      return res.status(200).json({
        success: 'false',
      });
    }
  })(req, res, next);
};
</code></pre>

<p>Here is the testing code in <code>/tests/controllers/users.js</code>:</p>

<pre><code>import passport from 'passport';
import { persistentLogin } from '../../controllers/users';

beforeEach(() =&gt; {
  mockResponse = () =&gt; {
    const response = {};
    response.status = jest.fn().mockReturnValue(response);
    response.json = jest.fn().mockReturnValue(response);
    response.sendStatus = jest.fn().mockReturnValue(response);
    response.clearCookie = jest.fn().mockReturnValue(response);
    response.cookie = jest.fn().mockReturnValue(response);
    return response;
  };
});

/**
 * persistentLogin Tests
 */
describe('Persistent Login Controller', () =&gt; {
  beforeEach(() =&gt; {
    req = {};

    res = mockResponse();

    validateLoginForm.mockClear();
    bcrypt.compare.mockClear();
  });

  // Passport authenication error
  test('Should show passport authenication error', async () =&gt; {
    passport.authenticate = jest.fn((authType, options, callback) =&gt; callback('This is an error', null));

    await persistentLogin(req, res);

    expect(passport.authenticate).toHaveBeenCalledTimes(1);

    expect(res.sendStatus).toHaveBeenCalledWith(500);
  });
});
</code></pre>

<p>If I had to guess, I would say it has something to do with how the (req, res, next) objects are passed into the live function after the fact. But since we are just mocking the function, I am not sure if it actually needs access to those objects.</p>

<p><strong>EDIT #1:</strong></p>

<p>Per the comment from @jakemingolla, I am now thinking it may be because Jest is not running my app.js file which defines my custom JWT strategy.</p>

<p>Here is the code from the <code>/app.js</code> file:</p>

<pre><code>import passport from 'passport';
import passportJWTStrategy from './utils/auth/passport';

app.use(passport.initialize());
passportJWTStrategy(passport);
</code></pre>

<p>And the code from the <code>/utils/auth/passport.js</code> file:</p>

<pre><code>import { Strategy } from 'passport-jwt';

/**
 * Verifies JWT payload
 *
 * @param passport The instance of passport module.
 */
export default (passport) =&gt; {
  const JWTStrategy = Strategy;

  // Setup Options Object
  const opts = {};
  opts.jwtFromRequest = req =&gt; req.cookies.jwt;
  opts.secretOrKey = process.env.PASSPORT_SECRET;

  passport.use(
    new JWTStrategy(opts, (jwtPayload, done) =&gt; {
      if (Date.now() &gt; jwtPayload.expire_date) {
        return done('jwt expired');
      }

      return done(null, jwtPayload);
    }),
  );
};
</code></pre>
",https://stackoverflow.com/questions/55123936/simple-mock-function-of-passport-using-jest,"['node.js', 'express', 'jestjs', 'passport.js']",9459,True,5,2
How to fix creation of table with reserved keywork (key)?,"<p>I use liquibase to initilize my h2 database for unit testing, but there is a problem with one table using ""key"" as name of column.</p>

<p>I tried ""_key"" as name, it works but the database (which I cannot change its schema) use ""key"" as a column name, so i have to put @Column(""\""key\"""") in my domain class. This works for SQL Server (production database) but doesn't for h2 (in memory db for testing)</p>

<p>In Liquibase xml:( for unit test)</p>

<pre><code>   &lt;column name='_key' type=""varchar(100)""&gt;
      &lt;constraints nullable=""true"" /&gt;
   &lt;/column&gt;
</code></pre>

<p>My domain:</p>

<pre><code>    @Column(name = ""_key"", length = 100)
    //@Column(name = ""\""key\"""", length = 100)
    private String key;
</code></pre>

<p>So I have to uncomment the first option and comment the second to make the unit test works and do the opposite to make the application work.</p>

<p>Using the </p>

<p><code>@Column(name = ""\""key\"""", length = 100)</code> 
with
<code>&lt;column name=""key"" type=""varchar(100)""&gt;</code> or 
<code>&lt;column name=""\""key\"""" type=""varchar(100)""&gt;</code> or
<code>&lt;column name='""key""' type=""varchar(100)""&gt;</code></p>

<p>returns an error:</p>

<blockquote>
  <p>Schema-validation: missing column [key] in table [displaymessages]</p>
</blockquote>

<p>and the query that creates the table is:</p>

<pre><code>CREATE TABLE PUBLIC.displaymessages (
  id BIGINT AUTO_INCREMENT NOT NULL,
  ""'key'"" VARCHAR(100),
  value VARCHAR(1000),
  type INT NOT NULL,
  createdon date NOT NULL,
  modifiedon date,
  isdeleted INT NOT NULL,
  CONSTRAINT PK_DISPLAYMESSAGES PRIMARY KEY (id)
)
</code></pre>
",https://stackoverflow.com/questions/58429210/how-to-fix-creation-of-table-with-reserved-keywork-key,"['sql-server', 'spring-boot', 'unit-testing', 'h2', 'liquibase']",1811,True,0,1
this.app.database is not a function when using firebase-server for unit testing,"<p>I'm trying to use firebase-server (<a href=""https://github.com/urish/firebase-server"" rel=""nofollow noreferrer"">https://github.com/urish/firebase-server</a>) for unit testing an express app that uses firebase. However, I'm starting out by just running the firebase-server on my own machine.</p>

<p>I've installed the library locally: <code>npm install --save-dev firebase-server</code></p>

<p>Then using the documentation for firebase-server, it says</p>

<blockquote>
  <p>If installed locally, use the following path to start the server: ./node_modules/.bin/firebase-server</p>
  
  <p>The following command will start a firebase server on port 5555:</p>
  
  <p><code>firebase-server -p 5555</code></p>
</blockquote>

<p>From the root of my project, I run <code>./node_modules/.bin/firebase-server -p 5555</code></p>

<p>The result is:</p>

<pre><code>/Users/user/Work/myproject/node_modules/firebase-server/dist/index.js:78
        this.app.database().goOffline();
                 ^

TypeError: this.app.database is not a function
    at new FirebaseServer (/Users/user/Work/myproject/node_modules/firebase-server/dist/index.js:78:18)
    at Object.&lt;anonymous&gt; (/Users/user/Work/myproject/node_modules/firebase-server/bin/firebase-server.js:85:17)
    at Object.cli.main (/Users/user/Work/myproject/node_modules/cli/cli.js:957:14)
    at Object.&lt;anonymous&gt; (/Users/user/Work/myproject/node_modules/firebase-server/bin/firebase-server.js:30:5)
    at Module._compile (module.js:649:30)
    at Object.Module._extensions..js (module.js:660:10)
    at Module.load (module.js:561:32)
    at tryModuleLoad (module.js:501:12)
    at Function.Module._load (module.js:493:3)
    at Function.Module.runMain (module.js:690:10)
</code></pre>

<p>Do I need to do some other configuration to get firebase-server to work via the cli?</p>

<p>Extra info:
I was able to get the server running if I install firebase-server globally, but still can't run it from my repo directory in <code>node_modules</code></p>

<p>package.json</p>

<pre><code>{
""name"": ""endpoints"",
""description"": ""my description"",
""version"": ""0.0.1"",
""private"": true,
""license"": ""Apache-2.0"",
""author"": ""JL"",
""repository"": {
    ""type"": ""git"",
    ""url"": ""https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git""
},
""engines"": {
    ""node"": ""&gt;=8.0.0""
},
""scripts"": {
    ""start"": ""node app.js"",
    ""test"": ""repo-tools test run --cmd ava -- -T 20s --verbose test/*.test.js""
},
""dependencies"": {
    ""@google-cloud/logging"": ""^4.2.0"",
    ""body-parser"": ""1.18.3"",
    ""express"": ""4.16.4"",
    ""firebase-admin"": ""~4.2.1"",
    ""safe-buffer"": ""5.1.2"",
    ""firebase"": ""5.8.3"",
    ""@firebase/app"": ""0.3.8"",
    ""@firebase/auth"": ""0.9.2"",
    ""@firebase/database"": ""0.3.12"",
    ""request-promise"": ""4.2.2""
},
""devDependencies"": {
    ""@google-cloud/nodejs-repo-tools"": ""^3.0.0"",
    ""ava"": ""0.25.0"",
    ""firebase-server"": ""^1.0.1"",
    ""husky"": ""^1.3.1"",
    ""proxyquire"": ""2.1.0"",
    ""sinon"": ""7.2.2"",
    ""supertest"": ""3.3.0""
},
""husky"": {
    ""hooks"": {
        ""pre-push"": ""npm test""
    }
}
}
</code></pre>
",https://stackoverflow.com/questions/54717381/this-app-database-is-not-a-function-when-using-firebase-server-for-unit-testing,"['firebase', 'unit-testing', 'firebase-realtime-database']",120,True,0,1
How to test a routing handler calling via mock from express,"<p>I'm unit-testing some code of mine in nodejs that works with express.
While it seems obvious, I want to test that my routes are calling the right handler functions.</p>

<p>I'm using jest to create a mock function for the handler function.
While I successfully tried to test that a function is called inside another function, I cannot seem to test that a function (handler) is called from express get of post.
Let's see an examplee:</p>

<p>fruits.js</p>

<pre class=""lang-js prettyprint-override""><code>function orange (req,res,next) {res.status(200)} ;
module.exports = {orange}
</code></pre>

<p>app.js</p>

<pre class=""lang-js prettyprint-override""><code>const fruits = require('./fruits')
const express = require('express');
const app = express();

app.get('/fruits', fruits.orange);

module.exports = { app };
</code></pre>

<p>When I'm trying to test (with jest) that GET request (with the help of axios module) to /fruits is calling orange(), altough actually orange() works, it won't be saved as a calling with a mock function cover of spy cover.</p>

<p>How can I test that orange() has been called from the GET request ?</p>
",https://stackoverflow.com/questions/56350877/how-to-test-a-routing-handler-calling-via-mock-from-express,"['node.js', 'express', 'testing', 'jestjs']",1007,False,0,1
NodeJs - Mongoose query in API failing in Mocha Chai test only,"<p>I am new to unit testing in Mocha/Chai and stuck on this issue. I have an POST for registering a new user. In that post, I check to see if the user is already in the database. </p>

<pre><code>if(error) return res.status(400).send(error.details[0].message);
console.log('check this ' +  req.body.email);
//console.log(`Connected to ${db}...`)
console.log(`Connected to ${User.db.mongoose}...`)
let user = await User.findOne({ email: req.body.email});
console.log(user);
if(user) return res.status(400).send('User already registered');
</code></pre>

<p>What I discovered the first test will register the user (inserting the information in the DB). What I found is that the second test fails.</p>

<pre><code>it('Should reject duplicate new user', async() =&gt; {
        const res = await request(server)
            .post('/api/users/')
            .send({firstname: sFirstName, lastname: sLastName, email: sEmail, password: sPassword});

        expect(res.status).to.be.equal(400);
        expect(res.error).to.be.equal('User already registered');

    });
</code></pre>

<p>The reason for the failure is that the connection string that the Query fails, thus not returning any records. So, I tested the query in Postman and the POST API is working as expected. I am curious if anyone knows why the mongoose query will not work when I run the test in Mocha but work when I connect via postman. Any thoughts would be appreciated. </p>

<pre><code>const {User, validate} = require('../models/user');


module.exports = function() {
    //Database connection 
    const db = config.get('db');
    mongoose.connect(db,{ useNewUrlParser: true })
        .then(() =&gt; console.log(`Connected to ${db}...`))
        .catch(err =&gt; console.error(`Could not connect to ${db}...`, err));
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/58533060/nodejs-mongoose-query-in-api-failing-in-mocha-chai-test-only,"['node.js', 'mongodb', 'mongoose', 'mocha.js', 'chai']",708,True,0,2
How to mock a class which contain a variable that can throw NPE,"<p>I have a login presenter which I want to test. I am new to unit testing and I have written a basic test to test a small functionality.</p>

<pre><code>class LoginPresenter @Inject constructor(
    private val view: LoginView,
    private val strategy: CancelStrategy,
    private val navigator: AuthenticationNavigator,
    private val tokenRepository: TokenRepository,
    private val localRepository: LocalRepository,
    private val settingsInteractor: GetSettingsInteractor,
    private val analyticsManager: AnalyticsManager,
    private val saveCurrentServer: SaveCurrentServerInteractor,
    private val saveAccountInteractor: SaveAccountInteractor,
    private val factory: RocketChatClientFactory,
    val serverInteractor: GetConnectingServerInteractor
) {
    // TODO - we should validate the current server when opening the app, and have a nonnull get()
    private var currentServer = serverInteractor.get()!!
    private val token = tokenRepository.get(currentServer)
    private lateinit var client: RocketChatClient
    private lateinit var settings: PublicSettings

    fun setupView() {
        setupConnectionInfo(currentServer)
        setupForgotPasswordView()
    }

    private fun setupConnectionInfo(serverUrl: String) {
        currentServer = serverUrl
        client = factory.get(currentServer)
        settings = settingsInteractor.get(currentServer)
    }

    private fun setupForgotPasswordView() {
        if (settings.isPasswordResetEnabled()) {
            view.showForgotPasswordView()
        }
    }

    fun authenticateWithUserAndPassword(usernameOrEmail: String, password: String) {
        launchUI(strategy) {
            view.showLoading()
            try {
                val token = retryIO(""login"") {
                    when {
                        settings.isLdapAuthenticationEnabled() -&gt;
                            client.loginWithLdap(usernameOrEmail, password)
                        usernameOrEmail.isEmail() -&gt;
                            client.loginWithEmail(usernameOrEmail, password)
                        else -&gt;
                            client.login(usernameOrEmail, password)
                    }
                }
                val myself = retryIO(""me()"") { client.me() }
                myself.username?.let { username -&gt;
                    val user = User(
                        id = myself.id,
                        roles = myself.roles,
                        status = myself.status,
                        name = myself.name,
                        emails = myself.emails?.map { Email(it.address ?: """", it.verified) },
                        username = username,
                        utcOffset = myself.utcOffset
                    )
                    localRepository.saveCurrentUser(currentServer, user)
                    saveCurrentServer.save(currentServer)
                    localRepository.save(LocalRepository.CURRENT_USERNAME_KEY, username)
                    saveAccount(username)
                    saveToken(token)
                    analyticsManager.logLogin(
                        AuthenticationEvent.AuthenticationWithUserAndPassword,
                        true
                    )
                    view.saveSmartLockCredentials(usernameOrEmail, password)
                    navigator.toChatList()
                }
            } catch (exception: RocketChatException) {
                when (exception) {
                    is RocketChatTwoFactorException -&gt; {
                        navigator.toTwoFA(usernameOrEmail, password)
                    }
                    else -&gt; {
                        analyticsManager.logLogin(
                            AuthenticationEvent.AuthenticationWithUserAndPassword,
                            false
                        )
                        exception.message?.let {
                            view.showMessage(it)
                        }.ifNull {
                            view.showGenericErrorMessage()
                        }
                    }
                }
            } finally {
                view.hideLoading()
            }
        }

    }

    fun forgotPassword() = navigator.toForgotPassword()

    private fun saveAccount(username: String) {
        val icon = settings.favicon()?.let {
            currentServer.serverLogoUrl(it)
        }
        val logo = settings.wideTile()?.let {
            currentServer.serverLogoUrl(it)
        }
        val thumb = currentServer.avatarUrl(username, token?.userId, token?.authToken)
        val account = Account(
            settings.siteName() ?: currentServer,
            currentServer,
            icon,
            logo,
            username,
            thumb
        )
        saveAccountInteractor.save(account)
    }

    private fun saveToken(token: Token) = tokenRepository.save(currentServer, token)
}
</code></pre>

<p>LoginPresenterTest</p>

<pre><code>class LoginPresenterTest {

    lateinit var loginPresenter: LoginPresenter

    private val view = mock(LoginView::class.java)
    private val strategy = mock(CancelStrategy::class.java)
    private val navigator = mock(AuthenticationNavigator::class.java)
    private val tokenRepository = mock(TokenRepository::class.java)
    private val localRepository = mock(LocalRepository::class.java)
    private val settingsInteractor = mock(GetSettingsInteractor::class.java)
    private val analyticsManager = mock(AnalyticsManager::class.java)
    private val saveCurrentServer = mock(SaveCurrentServerInteractor::class.java)
    private val saveAccountInteractor = mock(SaveAccountInteractor::class.java)
    private val factory = mock(RocketChatClientFactory::class.java)
    private val serverInteractor = mock(GetConnectingServerInteractor::class.java)
    private val token = mock(Token::class.java)
    private lateinit var settings: PublicSettings

    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
        loginPresenter = LoginPresenter(
            view, strategy, navigator, tokenRepository, localRepository, settingsInteractor,
            analyticsManager, saveCurrentServer, saveAccountInteractor, factory, serverInteractor
        )
    }

    @Test
    fun testAttach() {
        loginPresenter.setupView()
        assertNotNull(view)
    }
}
</code></pre>

<p>But on running the test I am getting KotlinNullPointerException as the variable current server is becoming null because there is no url saved in it. Is there any way I can avoid it from being null during running test. I have tried using elvis operator and modify LoginPresenter but I want to know is there anything other way which can work. I just want to initialise the value of current server with any url string to avoid NPE during running tests.</p>

<pre><code>private var currentServer = serverInteractor.get()?: ""https://example.com""
</code></pre>

<p>I also have SaveConnectingServerInteractor and GetConnectingServerInteractor  which is used to store the server url at the time of authentication. </p>

<pre><code>class SaveConnectingServerInteractor @Inject constructor(
    @ForAuthentication private val repository: CurrentServerRepository
) {
    fun save(url: String) = repository.save(url)
}

class GetConnectingServerInteractor @Inject constructor(
    @ForAuthentication private val repository: CurrentServerRepository
) {
    fun get(): String? = repository.get()

    fun clear() {
        repository.clear()
    }
}
</code></pre>
",https://stackoverflow.com/questions/56467566/how-to-mock-a-class-which-contain-a-variable-that-can-throw-npe,"['java', 'android', 'kotlin', 'mockito']",1355,True,0,2
My DbSet&lt;Entity&gt; won&#39;t update when trying from Unit Testing (MSTest) code,"<p>I am unit testing my MVC application. One of the tests is validating if my controller is correctly returning data for provided id.</p>

<p>To Unit test it, I want to add data from my [TestMethod] to the Context.DBSet and then call my Controller method and validate its output.</p>

<p>However, my added record isn't reflected inside the Context.DBSet object.</p>

<p>Below is the code that I currently have.</p>

<pre><code>    ///for purpose of unit testing, there is no underlying database
    public class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser&gt;
    {
        public ApplicationDbContext()
        {
            Database.SetInitializer(new ApplicationDbContextInitializer());
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
        public DbSet&lt;Book&gt; Books { get; set; }
        public DbSet&lt;Customer&gt; Customers { get; set; }
    }
</code></pre>

<pre><code>    public class ApplicationDbContextInitializer : CreateDatabaseIfNotExists&lt;ApplicationDbContext&gt;
    {
        protected override void Seed(ApplicationDbContext context)
        {
            InitializeBooks(context);
            InitializeCustomers(context);
            base.Seed(context);
        }
    }
    //for brevity, i haven't posted the InitializeBooks &amp; InitializeCustomers()
    //these methods create Book and Customer objects
    //and do context.Book.Add(objBook) and context.Customer.Add(objCustomer)

</code></pre>

<p>My Controller class has DbContext object which I use in my MS Test</p>

<pre><code>    public class CustomersController : Controller
    {
        public ApplicationDbContext db = new ApplicationDbContext();

        ///other methods exist too
    }
</code></pre>

<p>Finally my MSTest</p>

<pre><code>[TestMethod]
public void TestCustomerIDReplacedCorrectly()
{
    var objCtrl = new CustomersController();
    Customer objCust = new Customer()
    {
        Name = ""Foo Bar"",
        Address = ""Hello World"",
    };

    Console.WriteLine(objCtrl.db.Customers.Count()) //returns 4 correctly
    objCtrl.db.Customers.Add(objCust);
    Console.WriteLine(objCtrl.db.Customers.Count()) //still returns 4!? it should return 5

    ///calls are given to controller method
    ///to fetch ViewResult and ViewBag
    ///to validate if it is processing the
    ///instance put inside the objCtrl.db.Customers
}
</code></pre>

<p>I see that the added customer is not reflected inside by Customer's DbContext object, thus even my actual controller method which I'm supposed to validate, doesn't reflect my desired behavior either. How do I ensure that my <code>objCust</code> is added to <code>objCtrl.db.Customers.Add</code></p>

<p>Here is the InitializeCustomers() code which is called for seeding</p>

<pre><code>        private void InitializeCustomers(ApplicationDbContext context)
        {
            Customer cust1 = new Customer()
            {
                Name = ""James Butt"",
                Address = ""6649 N Blue Gum St"",
                Contact = ""50-621 8927"",
                NationalID = ""12312312312""
            };

            Customer cust2 = new Customer()
            {
                Name = ""Josephine Darakjy"",
                Address = ""Chanay, Jeffrey A Esq"",
                Contact = ""81-292 9840"",
                NationalID = ""123123124""
            };

            Customer cust3 = new Customer()
            {
                Name = ""Art Venere"",
                Address = ""Chemel, James L Cpa"",
                Contact = ""85-636 8749"",
                NationalID = ""123123456""
            };


            Customer cust4 = new Customer()
            {
                Name = ""Lenna Paprocki"",
                Address = ""Feltz Printing Service"",
                Contact = ""90-385 4412"",
                NationalID = ""32165498712""
            };

            context.Customers.Add(cust1);
            context.Customers.Add(cust2);
            context.Customers.Add(cust3);
            context.Customers.Add(cust4);

        }
</code></pre>
",https://stackoverflow.com/questions/58957405/my-dbsetentity-wont-update-when-trying-from-unit-testing-mstest-code,"['c#', 'asp.net-mvc', 'entity-framework', 'mstest', 'dbcontext']",681,True,-1,1
PHPUnit - Class &#39;/path/to/my/class.php&#39; could not be found in &#39;&#39;,"<p>I have set up PHPUnit on Windows to do unit testing within my Moodle application. My php version is 7.2.10 and the version of PHPUnit is 7.5.</p>

<p>I was able to successfully install composer and then PEAR and PHPUnit.</p>

<p>I was then able to initialise the Moodle PHPUnit test environment by running:</p>

<pre><code>php ../phpunit/cli/init.php
</code></pre>

<p>This successfully set up the test environment and ran all of the unit tests in the application.</p>

<p>The problem I have is when I attempt to run a single test, using e.g.</p>

<pre><code>vendor\bin\phpunit /mod/quiz/tests/event_test.php
</code></pre>

<p>This gives me the following error:</p>

<pre><code>Class '/mod/quiz/tests/event_test.php' could not be found in ''.
</code></pre>

<p>The solution to a similar looking problem, <a href=""https://stackoverflow.com/questions/5996734/phpunit-error-class-could-not-be-found"">PHPUnit error - Class could not be found</a>, does not solve the issue. I had to modify the solution since the <code>StandardTestSuiteLoader</code> class has changed - I tried making all comparisons to <code>realpath($suiteClassFile)</code> case insensitive but this has not worked.</p>
",https://stackoverflow.com/questions/54545163/phpunit-class-path-to-my-class-php-could-not-be-found-in,"['php', 'php-7.2', 'phpunit']",542,True,0,1
Asp.Net Core Unit Testing Delete Method in controller,"<p>I'm unit testing controller logic in a asp.net core project with xUnit and Moq, and I'm having trouble with testing the delete method. I have tried to put together some ideas from different tutorials etc. but still struggling. </p>

<p>I have managed to test that the method returns NoContentResult, and the NotFoundResponse. What I am missing here is the test to see that the delete method actually has deleted an item from the Bygg Repository.</p>

<p>What I am trying to do here in this case is to retreive the list of Bygg, delete an item, and then use assert to check if the list now only contains 2 items. </p>

<p>fyi: bygg = building.</p>

<p>The project follows a repository pattern with generic and userspecific repositories. </p>

<p>This is the delete method in the controller:</p>

<pre><code>[HttpDelete(""{id}"")]
public async Task&lt;IActionResult&gt; DeleteBygg(int id)
{
    try
    {
        var bygg = await _byggRepository.GetByggByIdAsync(id);
        if (bygg == null)
        {
            return NotFound();
        }

        await _byggRepository.DeleteByggAsync(bygg);

        return NoContent();
    }
    catch (Exception ex)
    {
        return StatusCode(500, ""Internal Server Error"");
    }
}
</code></pre>

<p>This is the test method:</p>

<pre><code>[Fact]
public async Task DeleteBygg_ExistingIdPassed_RemovesOneItem()
{
    // Arrange
    _mockRepo.Setup(repo =&gt; repo.DeleteByggAsync(It.IsAny&lt;Bygg&gt;()));
    _mockRepo.Setup(repo =&gt; repo.GetAllByggAsync())
        .ReturnsAsync(GetTestBygg());

    // Act
    var actual = await _controller.GetAllBygg();
    var actual2 = actual as OkObjectResult;
    var noContentResponse = await _controller.DeleteBygg(1);


    // Assert
    var items = Assert.IsType&lt;List&lt;Bygg&gt;&gt;(actual2.Value);
    Assert.Equal(2, items.Count);
}
</code></pre>
",https://stackoverflow.com/questions/55223684/asp-net-core-unit-testing-delete-method-in-controller,"['c#', 'unit-testing', 'asynchronous', 'asp.net-core', 'moq']",3241,True,0,1
Mockito how to unit test a static method which has many objects to be mocked inside,"<p>I have to unit test a static method which looks like this:</p>

<pre><code>public static boolean someProcess(List&lt;String&gt; arg1, Properties props, String[] arg3, String arg4, String arg5) throws Exception {
    boolean success = false;
    Job1 job1 = new Job1(arg3, props.getProperty(""prop1""), props.getProperty(""prop2""), arg1.get(0), arg4, ""asdf"", arg5);

    if(doJobAndCheckStatus(arg1, job1)) {
        String someId = job1.someId;
        Job2 job2 = new Job2(arg3, someId, arg4, arg5);

        if(doJobAndCheckStatus(arg1, job2)) {
            Job3 job3 = new Job3(arg3, someId, arg4, arg5);

            if(doJobAndCheckStatus(arg1, job3)) {
                String id2 = job3.id2;
                Job4 job4 = new Job4(arg3, id2, props.getProperty(""prop3""), arg4, arg5);

                if(doJobAndCheckStatus(arg1, job4)) {
                    String id3 = job4.id3;
                    Job5 job5 = new job5(arg3, id3, arg4, arg5, props.getProperty(""prop4""));

                    if(doJobAndCheckStatus(arg1, job5)) {
                        success = jobCompletedSuccessfully(arg1);
                    }
                }
            }
        }
    }
    return success;
}

public static boolean doJobAndCheckStatus(List&lt;String&gt; arg1, JobParent job) {
    job.processJob();
    ....
}
</code></pre>

<p>As shown above, in this static method, there are 5 JobX classes to initialize. All these Job classes are complex objects which will connect to external systems.  </p>

<p>My idea of unit testing this method is:</p>

<ol>
<li>Mock all the JobX classes which are used in the someProcess method.</li>
<li>Configure all the mocked classes to return the status of ""success"" when their processJob methods are called.</li>
<li>This someProcess method should return true if every job is completed successfully</li>
</ol>

<p>My questions are:</p>

<ol>
<li>Does my idea make sense at all? What's there to test for this
particular method at all?</li>
<li>Best way to test this method? How to get all the mocked JobX classes into effect?</li>
</ol>

<p>Any enlightenment will be highly appreciated!  </p>
",https://stackoverflow.com/questions/54221906/mockito-how-to-unit-test-a-static-method-which-has-many-objects-to-be-mocked-ins,"['java', 'unit-testing', 'mockito', 'junit5']",56,False,0,0
Using Tesng to test the service layer of the spring project encountered some unsolvable problems,"<p>In the process of unit testing the service layer of the spring project, I encountered the problem that the Repository cannot be called. In the unit test, I want to call the Repository to directly manipulate the contents of the database. When I use <code>@SpyMock</code> to simulate the Repository, an error is reported. as follows:</p>

<pre><code>
Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
    at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextPrepareTestInstance(AbstractTestNGSpringContextTests.java:145)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
    at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:62)
    at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:340)
    at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:294)
    at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:176)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:122)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.testng.TestRunner.privateRun(TestRunner.java:770)
    at org.testng.TestRunner.run(TestRunner.java:591)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:402)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:396)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:355)
    at org.testng.SuiteRunner.run(SuiteRunner.java:304)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
    at org.testng.TestNG.runSuites(TestNG.java:1032)
    at org.testng.TestNG.run(TestNG.java:1000)
    at org.gradle.api.internal.tasks.testing.testng.TestNGTestClassProcessor.runTests(TestNGTestClassProcessor.java:139)
    at org.gradle.api.internal.tasks.testing.testng.TestNGTestClassProcessor.stop(TestNGTestClassProcessor.java:89)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy1.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:123)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:155)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:137)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'scanResultConfigureService': Unsatisfied dependency expressed through field 'scanResultConfigureRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'app.dnatask.domain.repository.ScanResultConfigureRepository#0': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [app.dnatask.domain.repository.ScanResultConfigureRepository]: Specified class is an interface
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:398)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:330)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:139)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
    ... 56 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'app.dnatask.domain.repository.ScanResultConfigureRepository#0': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [app.dnatask.domain.repository.ScanResultConfigureRepository]: Specified class is an interface
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1229)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1128)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583)
    ... 74 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [app.dnatask.domain.repository.ScanResultConfigureRepository]: Specified class is an interface
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:70)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1221)
    ... 85 more
</code></pre>

<p>The service I need to test is as follows::</p>

<pre><code>package app.dnatask.service;

import ...

@Slf4j
@Service
public class ScanResultConfigureService {
    @Autowired
    private ScanResultConfigureRepository scanResultConfigureRepository;

    public Boolean pushResultList(String externalname) {
        ExternalNamePO po = scanResultConfigureRepository.findLabelType(externalname);
        if(po!=null){
            return true;
        }else{
            return false;
        }
    }
}

</code></pre>

<p>The relevant Repository is as follows::</p>

<pre><code>package app.dnatask.domain.repository;

import ...

public interface ScanResultConfigureRepository extends BaseRepository&lt;ScanResultConfigurePO, String&gt; {
    @Query(value = ""select a from dna_external_name a where a.id = ?1 "")
    ExternalNamePO findLabelType(String externalname);
}
</code></pre>

<p>The relevant test classes are as follows::</p>

<pre><code>package appTest.dnatask.service;

import ...

@SpringBootTest
@ContextConfiguration(classes = {ScanResultConfigureService.class})

public class ScanResultConfigureServiceTest extends AbstractTestNGSpringContextTests {
    @Autowired
    private ScanResultConfigureService scanResultConfigureService;

    @SpyBean
    private ScanResultConfigureRepository scanResultConfigureRepository;

    @Test
    public void testPushResultList() {
        CheckResult cr=new CheckResult();
        Boolean flag = scanResultConfigureService.pushResultList(""abc"");
//        .....
    }
}
</code></pre>

<blockquote>
  <p>I checked the information and found that many people suggested using the spring configuration file. At the time, I was not good at writing configuration files. I was more inclined to use annotations to solve this problem. I want to directly access the real database, but I encountered difficulties in the process</p>
</blockquote>
",https://stackoverflow.com/questions/59495869/using-tesng-to-test-the-service-layer-of-the-spring-project-encountered-some-uns,"['database', 'spring', 'unit-testing', 'service']",152,True,0,1
Accessing property on DisplayClass object at runtime,"<p><strong>Environment:</strong> VS2017, C# 7.0 targeting .NET Core 2.1.</p>

<p>I'm trying to write a fake/mock class to use for unit testing, and I'm having difficulties accessing a property on a <code>DisplayClass</code> object, which I understand  is <a href=""https://stackoverflow.com/q/16401860/606576"">a closure class from an anonymous function</a>.</p>

<p>My code looks like this:</p>

<pre class=""lang-cs prettyprint-override""><code>namespace MyCompany.Application.Web.Test.Fakes
{
    public class FakeElasticClient : IElasticClient
    {
        public FakeElasticClient() { }

        public Task&lt;ISearchResponse&lt;T&gt;&gt; SearchAsync&lt;T&gt;(Func&lt;SearchDescriptor&lt;T&gt;, ISearchRequest&gt; selector = null, CancellationToken cancellationToken = default(CancellationToken)) where T : class
        {
            var methodName = selector.Method.Name;
            dynamic tgt = selector.Target;
            object id = tgt?.GetType().GetProperty(""id"")?.GetValue(tgt, null);
            int? total;
            if (methodName.Contains(""Quux""))
            {
                total = CountSomething((Guid)id);
            }
            else
            {
                total = CountSomethingElse((Guid)id);
            }

            return Task.Run(() =&gt; new FakeSearchResponse&lt;T&gt;(total ?? 0) as ISearchResponse&lt;T&gt;);
        }

        // … below here follows a couple thousand other methods
</code></pre>

<p>Casting <code>id</code> to <code>Guid</code> throws a <code>NullReferenceException</code>, even though the Visual Studio debugger shows the <code>tgt</code> object has an <code>id</code> property:</p>

<p><a href=""https://i.stack.imgur.com/D7uZL.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/D7uZL.png"" alt=""Visual Studio debugger""></a></p>

<p>Comments:</p>

<ul>
<li>I have stolen the <code>object id = …</code> line from <a href=""https://stackoverflow.com/a/1203538/606576"">this answer</a>.</li>
<li><code>tgt.GetType()</code> returns <code>MyCompany.Application.Domain.Repository.Implementations.BusinessEntityRepository.&lt;&gt;c__DisplayClass8_0</code></li>
<li><code>tgt.GetType().GetProperties()</code> returns an empty <code>PropertyInfo</code> array.</li>
<li>Inspired by <a href=""https://juristr.com/blog/2013/08/object-does-not-contain-definition/"" rel=""nofollow noreferrer"">this blog post</a> I added an <code>[assembly: InternalsVisibleTo(""MyCompany.Application.Web.Test"")]</code> attribute to both the <code>MyCompany.Application.Domain.Repository.Implementations.BusinessEntityRepository</code> and the <code>MyCompany.Application.Web.Controllers</code> class, which as far as I can tell are the only two classes involved in the call chain. Didn't make any difference.</li>
<li>I tried futzing around with <code>IgnoresAccessChecksTo</code> <a href=""https://www.strathweb.com/2018/10/no-internalvisibleto-no-problem-bypassing-c-visibility-rules-with-roslyn/"" rel=""nofollow noreferrer"">as described here</a>, but couldn't make anything compile.</li>
</ul>

<p>How do I retrieve the value for <code>id</code>?</p>
",https://stackoverflow.com/questions/55143602/accessing-property-on-displayclass-object-at-runtime,"['c#', 'dynamic', 'reflection', 'anonymous-function', 'anonymous-types']",616,True,0,1
"jasmine unit testing a component which has data in a services, where that service fetches data from other service in angular 2+","<p>I have tried to write unit testing of a httpmock one of a service which uses a method (function) to get http get call, but failed to write. </p>

<p><strong>saveservice.service.ts -- file</strong></p>

<pre><code>const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
const envURL = sessionStorage.getItem('apiBaseURL');
 httpGet&lt;T&gt;(url) {
    const URL = envURL + url;
    return this.http.get&lt;T&gt;(URL, httpOptions);
  }
</code></pre>

<p>this saveservice.service file have httpGET() one, which is used by work.service.ts one</p>

<p><strong>work.service.ts</strong></p>

<pre><code>import {SaveserviceService } from '../../.././my-service.service';

getworklist(employeeID){

    return this.saveservice.httpGet('work/v1/works?employeeid=' + employeeID);
  }
</code></pre>

<p>this is how workservice and save service are connected.Now I want to write unit test case for work.component.ts file,but Iam unable to write the httpmock calls there .</p>

<p>For info, apiUrl is present in a different file named env.ts file--
<strong>env.ts</strong></p>

<pre><code>export const apivalue= {

    apiBaseUrl:""https://example.co/"",
  };
</code></pre>

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

<pre><code>ngOnit(){
this.employeeID:this.id;
   this.workservice.getworkList(this.employeeID).subscribe(
      (data) =&gt; {
        this.workList = data;
       console.log("" ggghfghfgh"", this.worklist);
      }, (error) =&gt; {
        console.log(error);}
</code></pre>

<p>Above one is work.component.ts file for which i should write unit test cases.Please help me to complete it.</p>

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

<pre><code> let httpMock: HttpTestingController;
 let injector: Injector;
  let workservice: WorksService;
let saveservice123: SaveService;

 providers: [
        Injector,
        HttpClient,
        HttpClientTestingModule,
        saveService,
        worksService
      ],

  httpMock = TestBed.get(HttpTestingController);
    workservice = TestBed.get(WorksService);
    saveservice123 = TestBed.get(SaveService)

  fit('getting work detsails indivually', async(() =&gt; {

    fixture = TestBed.createComponent(worksComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    workservice.getworkList(123).subscribe(() =&gt;{});

    const request = httpMock.expectOne(""work/v1/works?employeeid="")
    // expect(request.request.method).toBe('httpGet');
    // request.flush(xxxxx);

</code></pre>

<p>its throwing error </p>

<pre><code>Error: Expected one matching request for criteria ""Match URL: work/v1/works?employeeGuid="", found none.
</code></pre>

<p>Please help , how to know to write unit test cases for this type..
I also tried with  spy also,but unable to complete.</p>

<pre><code>const mockdata = { id:1, title: ""Hello world"",  paste: ""console.log('Hello world');""}
     const spyOnAdd = spyOn(service, ""getworkList"").and.returnValue(mockdata);

</code></pre>
",https://stackoverflow.com/questions/58254432/jasmine-unit-testing-a-component-which-has-data-in-a-services-where-that-servic,"['javascript', 'angular', 'typescript', 'unit-testing', 'jasmine']",288,False,0,1
Enzyme: &quot;Error: Method “text” is meant to be run on 1 node. 0 found instead.&quot;,"<p>I'm trying too add Unit Testing to a Project I've been working on, using Enzyme. I've been able to set up a basic test, however, when I try to run it, I get the following error ""Method “text” is meant to be run on 1 node. 0 found instead.""</p>

<p>I've been going through various online tutorials, as well as SO answers for similar questions, but I can't find anything that helps. I've also tried console.log-ing the wrapper, which returns:</p>

<pre><code>&lt;Connect(withRouter(WithStyles(SignIn))) &gt;
</code></pre>

<p>Code Being Tested;</p>

<pre><code>class SignIn extends Component {

//Removed unnecessary code for expediency

  render() {
    const { classes, loading } = this.props;
    const {
      values,
      touched,
      errors,
      isValid,
    } = this.state;

    const hasError = field =&gt; !!(touched[field] &amp;&amp; errors[field]);
    const { store } = configureStore();

    return (
      &lt;Provider store={store}&gt;
        &lt;div className={classes.root}&gt;
          &lt;Grid
            className={classes.grid}
            container
          &gt;
            &lt;Grid
              className={classes.quoteWrapper}
              item
              lg={5}
            &gt;
              &lt;div className={classes.quote}&gt;
                &lt;div className={classes.quoteInner}&gt;
                  &lt;Typography
                    className={classes.quoteText}
                    variant=""h1""
                  &gt;
                    We work with your business to provide a range of innovative
                    and bespoke software solutions.
                  &lt;/Typography&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/Grid&gt;
            &lt;Grid
              className={classes.content}
              item
              lg={7}
              xs={12}
            &gt;
              &lt;div className={classes.content}&gt;
                &lt;div className={classes.contentBody}&gt;
                  &lt;form className={classes.form}&gt;


                     &lt;p&gt;
                      &lt;Typography
                        className={classes.title}
                        variant=""h2""
                      &gt;
                        Sign in
                      &lt;/Typography&gt;
                    &lt;/p&gt;



                    &lt;div className={classes.fields}&gt;
                      &lt;TextField
                        className={classes.textField}
                        error={hasError('username')}
                        helperText={
                          hasError('username') ? errors.username[0] : null
                        }
                        label=""User name""
                        name=""username""
                        onChange={event =&gt;
                          this.handleFieldChange('username', event.target.value)
                        }
                        onKeyPress={this.handleKeyPress}
                        type=""text""
                        value={values.username}
                        variant=""outlined""
                      /&gt;
                      &lt;TextField
                        className={classes.textField}
                        error={hasError('password')}
                        helperText={
                          hasError('password') ? errors.password[0] : null
                        }
                        label=""Password""
                        name=""password""
                        onChange={event =&gt;
                          this.handleFieldChange('password', event.target.value)
                        }
                        onKeyPress={this.handleKeyPress}
                        type=""password""
                        value={values.password}
                        variant=""outlined""
                      /&gt;
                    &lt;/div&gt;
                    {loading ? (
                      &lt;CircularProgress className={classes.progress}/&gt;
                    ) : (
                      &lt;Button
                        className={classes.signInButton}
                        color=""primary""
                        disabled={!isValid}
                        onClick={this.handleSignIn}
                        size=""large""
                        variant=""contained""
                      &gt;
                        Sign in now
                      &lt;/Button&gt;
                    )}
                    &lt;Typography
                      className={classes.resetPassword}
                      variant=""body1""
                    &gt;
                      Have you forgotten your password?{' '}
                      &lt;Link
                        className={classes.resetPasswordURL}
                        to=""/reset-password""
                      &gt;
                        Reset it
                      &lt;/Link&gt;
                    &lt;/Typography&gt;
                  &lt;/form&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/Grid&gt;
          &lt;/Grid&gt;
        &lt;/div&gt;
      &lt;/Provider&gt;
    );
  }
}

SignIn.propTypes = {
  className: PropTypes.string,
  classes: PropTypes.object.isRequired,
  dispatch: PropTypes.func.isRequired,
  history: PropTypes.object.isRequired,
  loading: PropTypes.bool.isRequired,
  user: PropTypes.object.isRequired
};

const mapStateToProps = state =&gt; ({
  loading: state.authReducer.loadingKeys.includes(dataConstants.loading.main),
  user: state.authReducer.user
});

export default connect(mapStateToProps)(compose(
  withRouter,
  withStyles(styles)
)(SignIn));
</code></pre>

<p>And here is my test:</p>

<pre><code>describe('SignIn component', () =&gt; {
  it('starts with a count of 0', () =&gt; {
    const wrapper = shallow(
      &lt;Provider store={store}&gt;
        &lt;SignIn/&gt;;
      &lt;/Provider&gt;
    ).dive();
    let wrapperDebug = wrapper.debug();
    console.log(wrapperDebug);
    const text = wrapper.find('p').text();
    expect(text).toEqual('Sign in');

  });

});
</code></pre>

<p>The test should find the typography surrounded by p (I have left a few lines clear on either side in my code to highlight this area), and compare the text found within to the expected value. Thanks in advance for any help!</p>
",https://stackoverflow.com/questions/58234295/enzyme-error-method-text-is-meant-to-be-run-on-1-node-0-found-instead,"['reactjs', 'redux', 'jestjs', 'enzyme']",1503,False,0,1
Java/Mockito - A unit test for the thread to sleep exponentially before retry,"<p>I am trying to create a unit test class to test the class I created. This class tries to send a message and if it fails to send, it will wait exponentially (1s, 2s, 4s, 8s etc) before it retries to send the message. I want to test if this exponential wait behaviour works correctly. But I am new to unit testing and not really sure how to go about testing it using JUnit and Mockito. Any help would be greatly appreciated! </p>

<pre><code>@Slf4j
@Setter
@RequiredArgsConstructor
@AllArgsConstructor(access = AccessLevel.PACKAGE)
public class RetriableProcessorExponentialDecorator implements   
        AbsMessageProcessorDecorator {
    private final AbsMessageProcessor messageProcessor;
    @Autowired
    private AbsMessageActiveMQConfiguration configuration;

    @Override
    public void onMessage(AbsMessage message) throws Exception {
        int executionCounter = 0;
        long delay = 1000;
        final int maxRetries = this.configuration.getExceptionRetry() + 1;
        do {
            executionCounter++;
            try {
                this.messageProcessor.onMessage(message);
            } catch (RetriableException e) {
                log.info(""Failed to process message. Retry #{}"", executionCounter);
                delay = (long) (delay * (Math.pow(this.configuration.getMultiplier(), executionCounter)));
                Thread.sleep(delay);
            } catch (Exception e) {
                // We don't retry on this, only RetriableException.
                throw e;
            }
        } while (executionCounter &lt; maxRetries &amp;&amp; delay &lt; Long.MAX_VALUE);
    }
}
</code></pre>

<p>P.S Based on @Andy Turner's suggestion, I added a line <code>private final DefaultSleeper defaultSleeper;</code> in my <strong>RetriableProcessorExponentialDecorator</strong> class, and then replace <code>Thread.sleep(delay)</code> with <code>defaultSleeper.sleep(delay)</code>.</p>

<p>Then in my unit test class, I mocked <strong>DefaultSleeper</strong> by doing <code>@Mock
private DefaultSleeper sleeper;</code> and passed the mock object through the constructor of <strong>RetriableProcessorExponentialDecorator</strong> like the following: </p>

<pre><code>@Before
public void setUp() {
    this.decorator = new   
    RetriableProcessorExponentialDecorator(sleeper, processor,   
    configuration);
}
</code></pre>

<p>Am I on the right track?</p>
",https://stackoverflow.com/questions/54562426/java-mockito-a-unit-test-for-the-thread-to-sleep-exponentially-before-retry,"['java', 'spring', 'unit-testing', 'junit', 'mockito']",877,True,0,1
No provider for MockDialogRef,"<p>Here's the component constructor:</p>

<pre><code>constructor(
  public dialogRef: MatDialogRef&lt;TaskActionModalContainer&gt;,
  @Inject(MAT_DIALOG_DATA) data
) {}
</code></pre>

<p>Here's the testbed:</p>

<pre><code>TestBed.configureTestingModule({
  imports: [ MatDialogModule ],
  declarations: [ TaskActionModalContainer ],
  schemas: [
    CUSTOM_ELEMENTS_SCHEMA
  ],
  providers: [
    {
      provide: MatDialogRef,
      useValue: {},
    },
    {
      provide: MAT_DIALOG_DATA,
      useValue: {}
    }
  ]
})
.compileComponents();
</code></pre>

<p>Here's the error:</p>

<pre><code>StaticInjectorError(DynamicTestModule)[TaskActionModalContainer -&gt; MatDialogRef]: 
  StaticInjectorError(Platform: core)[TaskActionModalContainer -&gt; MatDialogRef]: 
    NullInjectorError: No provider for MatDialogRef!
</code></pre>

<p>I've searched high and low and see this NullInjector error everywhere, but I'm continuing to get it. I thought an angular guru could solve this quickly.</p>

<p>Help!</p>

<p>EDIT:</p>

<p>I've also used <code>useClass</code> with no success.</p>

<p>Of interest is that I also have this:</p>

<pre><code>  beforeEach(inject(
    [
      MatDialogRef,
      MAT_DIALOG_DATA
    ],
    (
      dialogRef,
      dialogData
    ) =&gt; {
    console.log(dialogRef);
    console.log(dialogData);
  }));
</code></pre>

<p>and I am seeing those console.log's when running the test....right before it shows me the error at <code>TestBed.createComponent</code></p>

<p>EDIT #2 - I feel like this is because this is an entryComponent, which I have no idea what that means, but this is one. I have a ModalContainer which pops up this one (so I guess it's a dynamically created one) - any help there?</p>

<p>Mistakenly closed this as a dupe, mine was about unit testing so the answer is a little more nuanced.</p>
",https://stackoverflow.com/questions/54638513/no-provider-for-mockdialogref,"['angular', 'angular-material', 'angular-test']",144,False,0,1
Need to check environment before maven runs unit tests,"<p>First - I'm a novice with maven, I can barely spell it.</p>

<p>We've tracked down a test problem to a missing file that should have been part of the dev's environment. We want to avoid this in the future by verifying this file, and perhaps others, exists prior to running the unit tests. We don't want the file to be a dependency since it is not required for building, just unit testing.</p>

<p>What is the best practice for this? A rather poor illustration of what I am looking for....</p>

<pre><code>   &lt;somephase&gt;
      &lt;required&gt;
         &lt;files&gt;
            &lt;file&gt;/some/path/to/some/needed/file&lt;/file&gt;
         &lt;/files&gt;
      &lt;/required&gt;
   &lt;/somephase&gt;
</code></pre>

<p>My searches have come up with nothing. Thanks in advance.</p>

<p>Update - Found this <a href=""https://maven.apache.org/enforcer/enforcer-rules/requireFilesExist.html"" rel=""nofollow noreferrer"">https://maven.apache.org/enforcer/enforcer-rules/requireFilesExist.html</a>, but I'm not sure when that actually executes. I would rather the check be performed only if unit tests are going to run.</p>
",https://stackoverflow.com/questions/56081523/need-to-check-environment-before-maven-runs-unit-tests,['maven'],29,False,0,1
JUnit to retrieve value from database to test criteria,"<p>How do I write JUnit with actual service/repository call to retrieve data from a database table instead of using a mock service/repository? </p>

<p>Here the below code returns an empty list of object, whereas I am expecting few hundred objects. <code>findAll()</code> is a simple method for which I am trying to write JUnit but later on I will be writing JUnit for a method which takes Map as JSON from request parameters and  forms a criteria API so in this case, I would like to test </p>

<blockquote>
  <ol>
  <li>Request </li>
  <li>Parsing of the request in Controller(what controller receives) </li>
  <li>And forming the SQL Criteria and returned object and that's the reason I don't want to mock service/repository. </li>
  </ol>
</blockquote>

<p>I am using Spring Boot Rest Controller and for Unit Testing, I am using Mocikito and JUnit.</p>

<pre><code>@ActiveProfiles(""test"")
@RunWith(SpringRunner.class)
@WebMvcTest(CaDetailController.class)
public class CaDetailControllerTest {

    private static ObjectMapper objectMapper = null;

    private List&lt;CaDetail&gt; caDetails;

    @Autowired
    private MockMvc controller;

    @MockBean
    CaDetailRepository repository;

    @BeforeClass
    public static void beforeClass() {
        objectMapper = new ObjectMapper();

    }

    @Before
    public void before() {
        caDetails = new ArrayList&lt;CaDetail&gt;();
    }

    @After
    public void after() {
        caDetails = new ArrayList&lt;CaDetail&gt;();
    }

    @AfterClass
    public static void afterClass() {
        objectMapper = null;
    }

    @Test
    public void getCorporateActions() throws Exception {
        MvcResult result = controller.perform(MockMvcRequestBuilders.get(""/api/ca"").accept(MediaType.APPLICATION_JSON)).andReturn();
        caDetails = objectMapper.readValue(result.getResponse().getContentAsByteArray(), new TypeReference&lt;List&lt;CaDetail&gt;&gt;() {
        });
        System.out.println(""&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; caDetails : "" + caDetails);
        assertNotNull(caDetails);
        assertTrue(caDetails.size() &gt; 0);
    }
</code></pre>
",https://stackoverflow.com/questions/54823492/junit-to-retrieve-value-from-database-to-test-criteria,['junit5'],2067,False,0,1
How extensive should negative unit test cases be?,"<p>I am pretty new to unit testing, and am aware that, for any non-primitive type parameter, a test should be written in which said parameter is provided as null. Should I also be including a negative test in which the parameter has a field which has a field whose being null could impact the method being tested, and so on?</p>

<p>For example, in the code provided the parameter of type Cart has a field which is a list of <code>CartLine</code>s. This <code>CartLine</code> class has a field of type Product, which, if provided as null in the one of the <code>CartLines</code> constituting the list of <code>CartLine</code>s that constitutes the field of the <code>Cart</code> being provided as a parameter, would produce a <code>NullPointerException</code> in the method being tested. Should I be providing a unit test for this possibility?</p>

<pre><code> public void updateProductQuantities(Cart cart){
    for (CartLine cartLine : cart.getCartLineList()) {
        Optional&lt;Product&gt; productOptional = productRepository.findById(cartLine.getProduct().getId());
        if (productOptional.isPresent()){
            Product product = productOptional.get();
            product.setQuantity(product.getQuantity() - cartLine.getQuantity());
            if (product.getQuantity()&lt;1){
                productRepository.delete(product);
            }else {
                productRepository.save(product);
            }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/58324095/how-extensive-should-negative-unit-test-cases-be,"['java', 'junit']",59,False,0,0
"good software design patterns, constructor overloading for unit testing","<p>I am developing a windows form application in c#. When instantiating the form, I initialize a few hardware classes within the constructor. <code>hardware1, Hardware2, Hardware3</code> represent the hardware classes that i instantiate in the software.</p>

<pre><code>public partial class Form1 {
    Hardware1 a;
    Hardware2 b;
    Hardware3 c;

    public Form1() {
        // initialize hardware1,2 and 3 using native dll calls of a,b and c
    }
</code></pre>

<p>I want to conduct unit testing for this method within my main form.</p>

<pre><code>public int MyMethod(int percent, ref double power) {
    for(int i =0; i&lt;3; i++)
        {
            if(a.isValid)
            {
                b.DoThing1(percent);
                b.DoThing2(true);
                c.DoSomething1();
                double val = C.DoSomething2();
                if (val != -500)
                {
                    power = val;
                    return 0;
                }
            }
            else
                return 1;

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

<p>The difficulty is that a.IsValid is set through some dll calls that i would have to mock. b.DoThing1 and C.DoThing2 also calls some dll function that I would have to mock as well. One possibility is to overload the form method constructor. Then i can mock each classes dll's </p>

<pre><code>Form1 (Hardware1 a, Hardware2 b, Hardware3 c) {
    this.a = a;
    this.b = b;
    this.c = c;
} 
</code></pre>

<p>or should i have interfaces for Hardware1 a, Hardware2 b and Hardware3 c ? I read that its generally better to have interfaces to substitute the concrete classes. </p>

<p>what is good software practice to unit test Form1 myMethod ?  </p>
",https://stackoverflow.com/questions/57040425/good-software-design-patterns-constructor-overloading-for-unit-testing,"['c#', 'visual-studio', 'unit-testing']",156,True,0,2
Unit tests for Project Using Z3,"<p>I have a project in c# which makes use of the Z3 library. The project runs and works perfectly fine on its own. But I try to add a second project to the main solution, and use the second project as a Unit testing project for the first and main project. In the second project I add reference to the first project and I also install NUnit from the ""Manage NuGet packages..."". But after I have built the whole solution and try to run the unit tests I get a error message saying: </p>

<p>System.BadImageFormatException : Could not load file or assembly 'Microsoft.Z3, Version=4.5.0.0, Culture=neutral, PublicKeyToken=9c8d792caae602a2' or one of its dependencies. An attempt was made to load a program with an incorrect format.</p>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/55034852/unit-tests-for-project-using-z3,"['c#', 'unit-testing', 'z3']",106,False,0,0
Can I downgrade from .net 2.1 to 2.0 for unit testing purposes,"<p>I am looking for some advice please. I have built a web app  in visual studio community edition which leverages on .NET 2.1. 
I want to start unit testing but when referencing the main project in the unit test project I get the error ""NET Framework 4.6.1 can not reference a project that targets 2.1. etc. etc."" 
I understand that .NET Framework will not support .NET Standard 2.1 or any other later version anymore. 
Would you have any advice on whether it would make sense to downgrade to .NET Standard 2.0 (assuming that is possible and I apologise if the question is stupid) or do I risk messing up the entire thing and therefore I should explore alternatives (for which I am happy to do my own research). 
Thanks in advance</p>
",https://stackoverflow.com/questions/55986778/can-i-downgrade-from-net-2-1-to-2-0-for-unit-testing-purposes,"['.net', 'unit-testing', 'asp.net-core-mvc']",183,True,0,1
Unit test a helper class around SharedPreference,"<p>I have a helper class to save user object to shared preferences. I have used a <code>serialize(): String</code> function and a <code>create(serializedString: String)</code> function in my <code>User</code> data model. They use GSon serializer and are working good as suggested by the unit tests on them. </p>

<p>Now my helper class is called <code>SharedPreferenceUserStore.kt</code> which takes a <code>Context</code> object. The code is:</p>

<pre><code>class SharedPreferenceUserStore(context: Context) {
    companion object {
        val TAG = SharedPreferenceUserStore::class.java.simpleName
    }

    var userLocalSharedPref: SharedPreferences =
        context.getSharedPreferences(USER_LOCAL_STORE_SHARED_PREF_NAME, Context.MODE_PRIVATE)

    /*
    Store the required data to shared preference
     */
    @SuppressLint(""ApplySharedPref"")
    fun storeUserData(user: User) {
        val userLocalDatabaseEditor = userLocalSharedPref.edit()
        val serializedData = user.serialize()

        userLocalDatabaseEditor.putString(
            USER_LOCAL_STORE_SHARED_PREF_SERIALIZED_DATA_KEY,
            serializedData
        )
        if (userLocalDatabaseEditor.commit()) {
            Log.d(TAG, "" Store Commit return true"")
        }
    }


    /*
    Clear all the locally stored data from the shared pref
     */
    @SuppressLint(""ApplySharedPref"")
    fun clearUserData() {
        val userLocalDatabaseEditor = userLocalSharedPref.edit()
        userLocalDatabaseEditor.clear()
        userLocalDatabaseEditor.commit()
    }

    fun getLoggedInUser(): User? {
        val stringUser = userLocalSharedPref.getString(
            USER_LOCAL_STORE_SHARED_PREF_SERIALIZED_DATA_KEY, """")

        return if (stringUser==null || stringUser == """"){
            null
        } else{
            User.create(stringUser)
        }
    }
</code></pre>

<p>And I have written some unit tests for this helper class as follows:</p>

<pre><code>@RunWith(JUnit4::class)
class SharedPreferenceUserStoreTest {

    lateinit var sharedPreferenceUserStore: SharedPreferenceUserStore
    lateinit var user: User

    //to be mocked
    lateinit var sharedPreferences: SharedPreferences
    lateinit var sharedPreferencesEditor: SharedPreferences.Editor
    lateinit var context: Context

    @Before
    fun setUp() {
        //mocking Context and SharedPreferences class
        context = mock(Context::class.java)
        sharedPreferences = mock(SharedPreferences::class.java)
        sharedPreferencesEditor = mock(SharedPreferences.Editor::class.java)

        //specifying that the context.getSharedPreferences() method call should return the mocked sharedpref
        `when`&lt;SharedPreferences&gt;(context.getSharedPreferences(anyString(), anyInt()))
            .thenReturn(sharedPreferences)
        //specifying that the sharedPreferences.edit() method call should return the mocked sharedpref editor
        `when`(sharedPreferences.edit()).thenReturn(sharedPreferencesEditor)
        //specifying that the sharedPreferencesEditor.putString() method call should return the mocked sharedpref Editor
        `when`(sharedPreferencesEditor.putString(anyString(), anyString())).thenReturn(
            sharedPreferencesEditor
        )
        `when`(sharedPreferences.getString(anyString(), anyString())).thenReturn("""")

        //instantiating  SharedPreferenceUserStore from the mocked context
        sharedPreferenceUserStore = SharedPreferenceUserStore(context)


        user = User(
            35,
            ""Prashanna Bhandary"",
            ""prashanna.bhandary@gmail.com"",
            ""dd58a617ea618010c2052cb54079ad67.jpeg"",
            ""98********"",
            ""test address 01"",
            1,
            ""yes"",
            ""2019-08-30 04:56:43"",
            ""2019-08-30 05:14:47"",
            0
        )
    }

    @After
    fun tearDown() {
    }

    @Test
    fun passUser_storeUserData() {
        sharedPreferenceUserStore.storeUserData(user)

        verify(sharedPreferencesEditor).putString(
            Constants.USER_LOCAL_STORE_SHARED_PREF_SERIALIZED_DATA_KEY,
            user.serialize()
        )
        verify(sharedPreferencesEditor).commit()
    }

    @Test
    fun testClearUserData() {
        sharedPreferenceUserStore.clearUserData()

        verify(sharedPreferencesEditor).clear()
    }


    @Test
    fun testGetLoggedInUser_storeNotCalled() {
        //calling getLoggedInUser() without calling storeUserData() should give null
        assertEquals(null, sharedPreferenceUserStore.getLoggedInUser())
        //verify that getString() was called on the shared preferences
        verify(sharedPreferences).getString(Constants.USER_LOCAL_STORE_SHARED_PREF_SERIALIZED_DATA_KEY, """")
    }

    @Test
    fun testGetLoggedInUser_storeCalled(){

        //call getLoggedInUser(), we are expecting null
        assertNull(sharedPreferenceUserStore.getLoggedInUser())

        //verify that getString() was called on the shared preferences
        verify(sharedPreferences).getString(Constants.USER_LOCAL_STORE_SHARED_PREF_SERIALIZED_DATA_KEY, """")
    }
}
</code></pre>

<p>As I am really new to Unit Testing and Mocking libraries like <code>Mockito</code>. Now my question is <strong>are my tests any good?</strong> and I wanted to test if the <code>getLoggedInUser()</code> funciton of my helper class is doing what it is supposed to do (ie. get logged in user if shared pref has it), how do I do that? </p>

<p>In addition do suggest me any improvements I can make to my test or the helper class itself. Thank you.</p>
",https://stackoverflow.com/questions/58485875/unit-test-a-helper-class-around-sharedpreference,"['android', 'unit-testing', 'kotlin', 'mockito', 'sharedpreferences']",2638,True,4,3
Karma-typescript cannot find module &quot;readable-stream/duplex.js&quot;,"<p>The closest thing I have found here is <a href=""https://stackoverflow.com/questions/43161453/karma-typescript-cannot-find-module"">karma-typescript cannot find module</a> but that one refers to an issue where karma-typescript cannot find a source file not a dependency. Its solution didn't work anyway.</p>

<p>I am trying to set up unit testing for a TypeScript project using Karma, Mocha, and Chai. I decided to use the karma-typescript package in npm to set up my tests so they didn't have to compile to Javascript first. When I run 'karma start karma.conf.js' it runs for a bit, then returns:</p>

<pre><code>02 03 2019 14:08:28.791:DEBUG [coverage.karma-typescript]: Initializing
02 03 2019 14:08:28.799:DEBUG [compiler.karma-typescript]: Setting up deferred project compilation
02 03 2019 14:08:28.800:DEBUG [coverage.karma-typescript]: Configuring coverage preprocessor
02 03 2019 14:08:28.805:ERROR [karma-server]: Server start failed on port 9876: Error: Cannot find module 'readable-stream/duplex.js'
npm ERR! Test failed.  See above for more details.
</code></pre>

<p>I have tried manually adding readable-stream, even though readable-stream is in karma-typescript's package.json, but it does not seem to do anything different. I have set up karma.conf.js as so:</p>

<pre><code>const puppeteer = require('puppeteer');
process.env.CHROME_BIN = puppeteer.executablePath();

module.exports = function(config) {
config.set({

basePath: '',

frameworks: ['mocha', 'chai', 'karma-typescript'],

karmaTypescriptConfig: {
  compilerOptions: {
    module: ""commonjs""
  },
  tsconfig: ""./src/ts/tsconfig.json""
},

files: [
  'src/**/*.ts'
],

exclude: [
],

preprocessors: {
  ""**/*.ts"": [""karma-typescript""]
},

reporters: ['progress', 'karma-typescript'],

port: 9876,

colors: true,

// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_DEBUG,

autoWatch: false,

browsers: ['ChromeHeadless'],

singleRun: true,

concurrency: Infinity
})
}
</code></pre>

<p>My tsconfig.json looks like this and is stored in the same folder as all the .ts source files (src/ts/):</p>

<pre><code>{
   ""compilerOptions"": {
   ""target"": ""es2018"",
   ""outDir"": ""../js"",
   ""rootDir"": ""./"",
   ""strict"": true,
   ""moduleResolution"": ""node"",
   ""esModuleInterop"": true
   }
}
</code></pre>
",https://stackoverflow.com/questions/54962129/karma-typescript-cannot-find-module-readable-stream-duplex-js,"['typescript', 'mocha.js', 'karma-runner', 'karma-mocha', 'karma-typescript']",608,False,4,0
Mocking a dependent class using Mockito in JAVA,"<p>I am quite new to Mockito. I apologise if my question sounds sill. I have a standalone JAVA application for which I have to write Unit test cases using JUnit and Mockito. The important thing is that I cannot change the code as it has been written by someone else and Integration testing has been completed. I have tried to search for similar questions, but couldnt find anything. Solutions suggested in somewhat similar questions, didnt work :(</p>

<p>I have attached the flow control diagram.I want to mock the dependent classes. For example when I am Unit testing 'Class 1 --> Method 1', I want to mock the output of 'Method 2 in Class 2' WITHOUT CALLING it. I have tried to use Mockito.when and Mockito.doReturn. Both call the dependent methods. </p>

<p>Can someone please suggest me some ideas to achieve this ?</p>

<p><a href=""https://i.stack.imgur.com/A201b.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/A201b.jpg"" alt=""Flow of Control""></a></p>

<pre class=""lang-java prettyprint-override""><code>//Pseudocode of Class 1
public class Class1 {
    public boolean method1() {
        Class2 c2 = new Class2();
        boolean b1 = c2.method2();
    }
}

//Pseudocode of Class 2
public class Class2 {
    public boolean method2() {
        Class3 c3 = new Class3();
        boolean b2 = c3.method3();
    }
}

... Likewise same for Class 3, 4 and 5
</code></pre>
",https://stackoverflow.com/questions/59190782/mocking-a-dependent-class-using-mockito-in-java,"['java', 'mockito', 'powermock', 'stub']",3656,True,3,2
How to Mock a class having no default construtor,"<p>I want to mock a class having no default constructor and call a method inside it. This method calls another method of the same class. I want to setup this second method to return a value ad execute rest of the part of first method to test some results.</p>

<pre><code>[Test]
public void TestFunction(){
    int d=0;
    var mockObject = new Mock&lt;Foo&gt;(){MockBehaviour.Default, p, q}; //p and q are parameters for Foo constructor
    mockObject.Setup(x=&gt;x.func2(a,b,c)).Returns(d);
    mockobject.Object.func1();
}


Class Foo{
    public Foo(int x,int y){}

    public virtual int func1(){
       DoSomething;
       func2();
    }

    public virtual int func2(){}
}
</code></pre>

<p>I am mocking Foo because I don't want func2() to be executed when I test func1(). Hence I setup the mockObject to return a value for func2() without executing it when func1() calls func2().</p>

<p>When I run this test case I get exception ""System.NotSupportedException : Parent does not have a default constructor. The default constructor must be explicitly defined.""</p>

<p>If I see the mockObject while debugging the test case, mockObject.Object is not getting initialized. 
I am new to unit testing and Mock. Can someone help me about where I am going wrong. </p>
",https://stackoverflow.com/questions/54555712/how-to-mock-a-class-having-no-default-construtor,"['c#', 'nunit', 'moq']",4014,True,3,2
How to test styled components conditionally and children elements?,"<p>I'm new to unit testing and I've spent some 20-30 hours in docs, articles and YT videos but still can't make sense of how to achieve this. Basically I want to test 3 things here:</p>

<ol>
<li>Make sure that this component renders 3  components</li>
<li>Test the conditional styling </li>
<li>Test the click event</li>
</ol>

<p>So far, for the 1st thing, if I try to do:</p>

<pre><code>import { shallow } from ""enzyme"";
import React from ""react"";
import ButtonsComponent, { SchedButton } from ""./ButtonsComponent"";

it(""renders three &lt;MyButton /&gt; components"", () =&gt; {
  const wrapper = shallow(&lt;ButtonsComponent /&gt;);
  expect(wrapper.find(MyButton)).to.have.lengthOf(3);
});
</code></pre>

<p>I get the following error:
TypeError: Enzyme::Selector expects a string, object, or Component Constructor</p>

<p>And I don't have any good idea how to test the other two things, I've seen some examples but I don't understand how to adapt them to my particular situation since they don't seem to be testing exactly what I'm trying to do.</p>

<p>This is a simplifed version of my component:</p>

<pre><code>import React from ""react"";
import styled from ""styled-components"";

const MyButton = styled.button`
  background: ${props =&gt;
    props.color ? theme.palette.secondary.dark : ""#e6e6e6""};
  color: ${props =&gt; (props.color ? ""white"" : ""#737373"")};
`;

const ButtonsComponent = ({ currentState, updateState }) =&gt; {
  const handleClick = event =&gt; {
    updateState(event.target.value);
  };

  return (
    &lt;div&gt;
      &lt;MyButton
        value=""Button 1""
        onClick={handleClick}
        color={currentState === ""Button 1"" ? ""#1fbd45"" : """"}
      &gt;
        Button 1
      &lt;/MyButton&gt;
      &lt;MyButton
        value=""Button 2""
        onClick={handleClick}
        color={currentState === ""Button 2"" ? ""#1fbd45"" : """"}
      &gt;
        Button 2
      &lt;/MyButton&gt;

      &lt;MyButton
        value=""Button 3""
        onClick={handleClick}
        color={!currentState || currentState === ""Button 3"" ? ""#1fbd45"" : """"}
      &gt;
        Button 3
      &lt;/MyButton&gt;
    &lt;/div&gt;
  );
};

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

<p>Any help is greatly appreciated, an ELI5 explanation would be so much more!</p>
",https://stackoverflow.com/questions/56333009/how-to-test-styled-components-conditionally-and-children-elements,"['reactjs', 'unit-testing', 'enzyme', 'styled-components']",3897,True,3,1
Testing Code with Third Party Object Instantiation,"<p>New to unit testing and trying to get my head around some simple tests for a piece of code which gets or creates a template if it doesn't exist (in Umbraco 8).</p>

<p>The method is quite simple, when Initialise is called, it gets the template and if it doesn't exist, creates it:</p>

<pre><code>using Umbraco.Core.Composing;
using Umbraco.Core.Models;
using Umbraco.Core.Services;

namespace Papermoon.Umbraco.Aldus.Core.Components
{
    public class TemplateComponent : IComponent
    {
        private readonly IFileService _fileService;

        public TemplateComponent(IFileService fileService)
        {
            _fileService = fileService;
        }

        public void Initialize()
        {
            ITemplate blogTemplate = _fileService.GetTemplate(""aldusBlog"");

            if (blogTemplate == null)
            {
                blogTemplate = new Template(""Aldus Blog"", ""aldusBlog"");

                _fileService.SaveTemplate(blogTemplate);
            }
        }

        public void Terminate() { }
    }
}
</code></pre>

<p>Works okay, no problem.</p>

<p>I'm trying to write a few tests, the first checks if <code>_fileService.GetTemplate</code> is called.</p>

<p>The second test should check that <code>_fileService.SaveTemplate()</code> is called if that returns null.</p>

<pre><code>using Moq;
using NUnit.Framework;
using Papermoon.Umbraco.Aldus.Core.Components;
using Umbraco.Core.Models;
using Umbraco.Core.Services;

namespace Papermoon.Umbraco.Aldus.Core.Tests.Components
{
    [TestFixture]
    public class TemplateComponentTests
    {
        private Mock&lt;IFileService&gt; _fileService;

        private TemplateComponent _component;

        [SetUp]
        public void SetUp()
        {
            _fileService = new Mock&lt;IFileService&gt;();

            _component = new TemplateComponent(_fileService.Object);
        }

        [Test]
        public void Initialise_WhenCalled_GetsBlogTemplate()
        {
            _component.Initialize();

            _fileService.Verify(s =&gt; s.GetTemplate(""aldusBlog""), Times.Once);
        }

        [Test]
        public void Initialise_BlogTemplateDoesNotExist_CreateTemplate()
        {
            _fileService
                .Setup(s =&gt; s.GetTemplate(""aldusBlog""))
                .Returns((ITemplate) null);

            _component.Initialize();

            _fileService.Verify(s =&gt; s.SaveTemplate(It.Is&lt;ITemplate&gt;(p =&gt; p.Alias == ""aldusBlog""), -1), Times.Once());
        }
    }
}
</code></pre>

<p>The trouble when I do this is that the <code>blogTemplate = new Template(""Aldus Blog"", ""aldusBlog"");</code> throws an error:</p>

<pre><code>Can not get Current.Config during composition. Use composition.Config.
</code></pre>

<p>I assume this is because I don't have any kind of context which leads me to think that the <code>ITemplate</code> needs to be mocked. However, because <code>new Template(""Aldus Blog"", ""aldusBlog"");</code> will always be called, it will always throw this error.</p>

<p>Obviously the code isn't bullet proof, so how do I refactor this to be testable?</p>
",https://stackoverflow.com/questions/57615120/testing-code-with-third-party-object-instantiation,"['c#', 'unit-testing', 'nunit', 'moq', 'umbraco']",54,True,3,1
Mocking Highcharts (w/ Exporting) for Jest Unit Testing,"<p>I am working on a React project that I am testing using Jest.
Our application uses Highcharts to render data visulaizations on our views, but I am having an issue when it comes to using one of Highcharts plugin modules ""exporting"" that is used for capturing the dataURL of the svg Highcharts has already rendered.</p>

<p>Everything unfortunately works beautifully when it comes to actually running the application and seeing everything work, but since unit testing is a big requirement  I am now stuck on this mocking aspect. </p>

<p>My component imports highcharts and it's module like</p>

<pre><code>import Highcharts, { Chart } from 'highcharts';
import addExporting from 'highcharts/js/modules/exporting.src.js'
addExporting(Highcharts);
</code></pre>

<p>I created a genMockFromModule in <strong>mocks</strong>/highcharts.ts</p>

<pre><code>const highcharts: any = jest.genMockFromModule(`highcharts`);
highcharts.getOptions = () =&gt; ({ plotOptions: {}, exporting: {} });
module.exports = highcharts;
</code></pre>

<p>I tried in my test file (<strong>tests</strong>/components/Chart.ts)</p>

<pre><code>jest.mock('highcharts', () =&gt; ({
  Chart: jest.fn(),
  setOptions: jest.fn(),
  seriesTypes: {},
}));
jest.mock('highcharts/js/modules/exporting.src.js', () =&gt; jest.fn() )
</code></pre>

<p>Seems whatever I try, I always get this issue: </p>

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

<pre><code>  16 |
&gt; 18 | addExporting(Highcharts);
     | ^
  19 |

  at node_modules/highcharts/js/modules/exporting.src.js:49:23
  at node_modules/highcharts/js/modules/exporting.src.js:1760:3
</code></pre>
</blockquote>

<p>Without addExporting module I can't figure out how to mock the other highcharts functionality such as </p>

<pre><code>if(this.chartRef) {
    this.chartRef.destroy()
}
</code></pre>
",https://stackoverflow.com/questions/56117785/mocking-highcharts-w-exporting-for-jest-unit-testing,"['reactjs', 'highcharts', 'jestjs', 'enzyme']",2365,False,3,0
Is it a good practice to unit test controller classes in Spring MVC,"<p>I used to unit test my controller classes just like any other normal Java class. I mean without using Spring's MockMvc. But then I realized that this way I won't be able to be sure that I've set up the MVC configuration correctly. So if I have controller like this:</p>

<pre><code>@Restcontroller
@RequestMapping(""/cars"")
public class CarController{
    private CarService carService;
    public CarController (CarService service){this.carService = service};
    @GetMapping
    public List&lt;Car&gt; getCar(@RequestParam(""filter"") String filter){
       if(filter!=null &amp;&amp; !filter.trim().equal("""")){
          //omitted for brevity
       }
    }
}
</code></pre>

<p>and if I unit test its <code>getCar</code> method directly, even if the test passes, that won't mean my controller is alright. So instead of unit testing, I started actually doing integration testing. Something like this:</p>

<pre><code>mockMvc.perform(get(""/v1/cars?filter = Honda""))....  bla bla bla
</code></pre>

<p>Recently a question arose if we should first unit test and the integration test rest controllers. At first glance, it seems to me that integration test does, in the end, check the correct behavior of the controller. But on the other hand, how good is that to rely on integration test only.</p>
",https://stackoverflow.com/questions/55649851/is-it-a-good-practice-to-unit-test-controller-classes-in-spring-mvc,"['spring', 'unit-testing', 'controller', 'integration-testing']",958,True,2,1
CUDA 10.1 compile error with SFINAE templates,"<p>CUDA 10.1<br>
g++ 7.3</p>

<p>For the purposes of a unit testing suite, I need large sets of repeatable data (more than can be hard-coded). I came up with this ""generator"" paradigm, with the idea that it could be used to fill arbitrary containers with data.</p>

<p>Now I need to extend the generator to populate multivalue containers (<code>float2</code>, <code>int2</code>, <code>thrust::complex</code>). My solution is to use SFINAE to conditionally define a function based on whether it can be constructed from a single value or requires a pair of values.</p>

<p>The below code compiles fine with GCC (<code>-std=c++1z</code>) but fails with nvcc (<code>-std=c++14</code>)</p>

<pre class=""lang-cpp prettyprint-override""><code>#include &lt;random&gt;
#include &lt;type_traits&gt;

template &lt;typename T&gt;
class RandomGenerator
{
public:
    RandomGenerator(T min, T max, unsigned seed = 42);

    // Generate the next element in the sequence. This requires keeping all the necessary state
    // to advance
    T operator()();

    // fill a container if it is scalar
    template&lt;typename Container&gt;
    typename std::enable_if_t&lt;std::is_constructible_v&lt;typename Container::value_type, T&gt;&gt;
    fill( Container&amp; c );

    // fill a container if it takes 2 values (e.g., complex)
    template&lt;typename Container&gt;
    typename std::enable_if_t&lt;std::is_constructible_v&lt;typename Container::value_type, T, T&gt;&gt;
    fill2( Container&amp; c );

protected:
private:
    std::uniform_real_distribution&lt; T &gt; dist;
    std::mt19937 rng;
};


// Constructor - define the domain of this generation
template &lt;typename T&gt;
RandomGenerator&lt;T&gt;::RandomGenerator(T min, T max, unsigned seed)
    : dist(min, max)
    , rng()
{
    rng.seed(seed);
}

// generate one random number
template &lt;typename T&gt;
T
RandomGenerator&lt;T&gt;::operator()()
{
    return dist(rng);
}

template &lt;typename T&gt;
template&lt;typename Container&gt;
typename std::enable_if_t&lt;std::is_constructible_v&lt;typename Container::value_type, T&gt;&gt;
RandomGenerator&lt;T&gt;::fill( Container&amp; c )
{
    std::generate(c.begin(), c.end(), *this);
}

template &lt;typename T&gt;
template&lt;typename Container&gt;
typename std::enable_if_t&lt;std::is_constructible_v&lt;typename Container::value_type, T, T&gt;&gt;
RandomGenerator&lt;T&gt;::fill2( Container&amp; c )
{
    std::generate(c.begin(), c.end(), [this]() { return typename Container::value_type( (*this)(), (*this)() ); });
}


</code></pre>

<p>The compiler error:</p>

<pre><code>/usr/local/cuda/bin/nvcc  -g -Xcompiler=-fPIE -gencode=arch=compute_60,code=sm_60 --std=c++14 --use_fast_math -Xcompiler -pthread -x cu -dc unittest.cu -o unittest.cu.o
RandomGenerator.hh(30): error: namespace ""std"" has no member ""is_constructible_v""

RandomGenerator.hh(30): error: type name is not allowed

RandomGenerator.hh(30): error: expected an identifier

RandomGenerator.hh(34): error: namespace ""std"" has no member ""is_constructible_v""

RandomGenerator.hh(34): error: type name is not allowed

RandomGenerator.hh(34): error: too many arguments for alias template ""std::enable_if_t""

RandomGenerator.hh(34): error: expected an identifier

RandomGenerator.hh(63): error: namespace ""std"" has no member ""is_constructible_v""

RandomGenerator.hh(63): error: type name is not allowed

RandomGenerator.hh(63): error: expected an identifier

RandomGenerator.hh(71): error: namespace ""std"" has no member ""is_constructible_v""

RandomGenerator.hh(71): error: type name is not allowed

RandomGenerator.hh(71): error: too many arguments for alias template ""std::enable_if_t""

RandomGenerator.hh(71): error: expected a "";""

</code></pre>

<p>Am I missing something? Is there a way to pass this to CUDA?</p>

<hr>

<p>UPDATE</p>

<p>It appears that the specific problem is with <code>std::enable_if_t</code>, <code>std::is_XXX_v</code>. If instead of these typdefs I use the more verbose form</p>

<pre class=""lang-cpp prettyprint-override""><code>typename std::enable_if&lt;std::is_constructible&lt;typename Container::value_type, T&gt;::value&gt;::type
</code></pre>

<p>then nvcc can handle it.</p>
",https://stackoverflow.com/questions/57403473/cuda-10-1-compile-error-with-sfinae-templates,"['c++11', 'cuda']",696,True,2,1
"Should I mount using beforeEach() and set props for each test or mount a specific component at the start of each test? (using Enzyme, Chai and Mocha)","<p>I've recently starting programming.  I'm on a team who is programming in React and is using Enzyme, Mocha and Chai for unit testing.  See package versions below.</p>

<p>When testing a component where there are several use cases that require different prop values, should I use beforeEach() and then setProps() in each test, or should I do an explicit mount() (or shallow()) at the start of each test?  Does it matter?</p>

<p>For example, I could use beforeEach() to mount without any props and then use setProps() in each test like this (using pseudocode):</p>

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

   beforeEach(... let component = mount(&lt;MyComponent /&gt;) ...)

   it('tests use case 1', () =&gt; {
      // set prop A = 123
      component.setProps({A: 123})
      // assert some stuff
   })

   it('tests use case 2, () =&gt; {
      // set prop A = 456 and B = 'foo'
      component.setProps({A: 456})
      component.setProps({B: 'foo'})
      // assert some stuff
   })

})
</code></pre>

<p>or I could do a use-case specific mount at the start of each test, passing in props in the mount, like this:</p>

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

   it('tests use case 1', () =&gt; {
      ...mount(&lt;MyComponent A=123 /&gt;)
      // assert some stuff
   })

   it('tests use case 2, () =&gt; {
      ...mount(&lt;MyComponent A=456 B='foo' /&gt;)
      // assert some stuff
   })

})
</code></pre>

<p>What are the pros and cons of each method?  Is there a best practice?</p>

<p><strong>Packages</strong></p>

<ul>
<li>""enzyme"": ""^3.3.0"",</li>
<li>""enzyme-adapter-react-16"": ""^1.1.1"",</li>
<li>""mocha"": ""^5.0.0"",</li>
<li>""chai"": ""3.5.0""</li>
</ul>
",https://stackoverflow.com/questions/57062372/should-i-mount-using-beforeeach-and-set-props-for-each-test-or-mount-a-specifi,"['reactjs', 'unit-testing', 'mocha.js', 'enzyme', 'chai']",1622,False,2,1
Unit testing Nativescript application logic on a browser,"<p>I am trying to set up unit testing for a Nativescript application, run by <code>ng test</code> on a browser. The problem is that whenever there is a <code>tns-core-modules</code> or another plugin import, the module cannot be resolved because of the platform specific files (e.g. ""tns-core-modules/application/application.android.js"") that never get compiled into the bundle, thus throwing an error like ""Module not found: Error: Can't resolve 'tns-core-modules/application'"".</p>

<p>I know there is a built-in unit test support in Nativescript. The problem I have with it is that it can't run on CI. I would like to be a ble to have lightweight tests for my business logic, mocking out all platform dependencies.
I have looked for a way to mock the module imports at runtime with no luck. I looked into <code>rewire</code> package but it only runs on node.</p>
",https://stackoverflow.com/questions/55458902/unit-testing-nativescript-application-logic-on-a-browser,"['unit-testing', 'angular-cli', 'nativescript', 'nativescript-angular']",268,True,2,2
How to mock UserManager&lt;IdentityUser&gt;,"<p>I am trying to work out how to add unit testing to my project.  I thought it was best to start with a blank project and work it out from the start rather than adding it to my main project.  Once I understand the process i figure i can start refactoring my project for adding testing.</p>

<h1>web application</h1>

<p>So i created a web application and added default user identity to it.  </p>

<p>This gave me a start up looking like this </p>

<pre><code>public void ConfigureServices(IServiceCollection services)
    {
        services.Configure&lt;CookiePolicyOptions&gt;(options =&gt;
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context =&gt; true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
            options.UseSqlServer(
                Configuration.GetConnectionString(""DefaultConnection"")));
        services.AddDefaultIdentity&lt;IdentityUser&gt;()
            .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }
</code></pre>

<p>Then i created a simple controller and passed the usermanager in the constructor.</p>

<pre><code>[Route(""api/[controller]"")]
[ApiController]
public class SweetController : ControllerBase
{
    private readonly UserManager&lt;IdentityUser&gt; _userManager;

    public SweetController(UserManager&lt;IdentityUser&gt; userManager)
    {
        _userManager = userManager;
    }
    public async Task&lt;int&gt; NumberOfGummyBearsForUser(string userId)
    {
        var user = await _userManager.FindByIdAsync(userId);
        var userHasASweetTooth = await _userManager.IsInRoleAsync(user, ""SweetTooth"");
        if (userHasASweetTooth)
        {
            return 100;
        }
        else
        {
            return 1;
        }
    }
}
</code></pre>

<h2>Unit Test</h2>

<p>The first thing i have been trying to do is mock this user manager but its not working.</p>

<pre><code>public void Test1()
    {
        // Arrange
        var mockUser = new Mock&lt;UserManager&lt;IdentityUser&gt;&gt;();
        var userManager = new UserManager(mockRepo.Object);  &lt;-- error here see image below

        var controller = new SweetController(userManager.Object);

        // Act
        var result = await controller.NumberOfGummyBearsForUser(""123"");

        // Assert
        Assert.Equal(100, result);
    }
</code></pre>

<p>The error looks like this</p>

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

<p>I think i need to pass more to create this usermanager object but i am not sure what all the tutorials i have found use ApplicationUser and not IdentityUser so i am at a loss as to how i can mock this object.</p>
",https://stackoverflow.com/questions/55412776/how-to-mock-usermanageridentityuser,"['c#', 'asp.net-core', 'asp.net-identity', 'moq', 'xunit']",8197,True,10,2
How can i patch out a parameter from a function that calls a method?,"<p>Hello I am pretty new to unit testing and therefore I got a big issue with unittest.mock.
My Project consists of different modules. 
My first module is General:</p>

<pre><code>general.py


def do_something(item, collection): 
    # some more code that i want to test
    try:
        collection.insert_one(item)
    except:
        print(""did not work"")

</code></pre>

<p>My second module ist my_module.py</p>

<pre><code>mymodule.py

import general
from pymongo import MongoClient

client = MongoClient(""localhost"", 27017)
db = client['db']
collection = db['col']

item = 
  {
    ""id"": 1
  }



def method:
    general.do_something(item, collection)
</code></pre>

<p>Now I want to test the do_something(item, collection) method from general.py, and therefore I want to mock the collection.insert_one(item). I did not find a possible solution for this.
I tried it with patch, but my Problem is, that the parameter collection (which is a pymongo Collection) is a parameter that calls a function. How can i now manage to mock collection.insert_one?</p>

<p>My target is to extract collection.insert_one and set a MagicMock into it. And this Magic Mock should have the possibility to crash to check if the except part works or to not crash to check if the try part workes.</p>

<pre><code>TestGeneral.py
import unnittest

class TestGeneral(unittest.TestCase):

    @patch()
    def test_general():





</code></pre>

<p>Thank you in advance! :)</p>
",https://stackoverflow.com/questions/58768755/how-can-i-patch-out-a-parameter-from-a-function-that-calls-a-method,"['python', 'mocking', 'decorator', 'patch']",500,True,1,2
Unit Testing In Network With Using Volley in Android,"<p>I am trying to test functions from my Presenter Class. In below, I can reach <code>getSomeThing()</code> function however, I cannot reach the <code>getData()</code> and <code>getError()</code> functions. </p>

<p>Volley functions are not working in unit tests. Further help would be highly appreciated as I am struggling with this for over a week. </p>

<p>Below is my Presenter Class, Presenter Listener and Test Function.</p>

<p>my Presenter Class:</p>

<pre><code>public abstract class SomePresenter implements BasePresenterListener {

    private static final String sTAG = SomePresenter.class.getSimpleName();

    private Context context;
    private Integer testInteger;

    protected SomePresenter(Context context, Integer testInteger) {
        this.context = context;
        this.testInteger = testInteger;
        onResponse();
    }

    @Override
    public void onResponse() {
        try {
            Thread.sleep(1000);
            getSomeThing();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        final GetRequest&lt;SomeResponse&gt; someResponseRequest =
                ApiRequests.getSomeResponse(
                        new Response.Listener&lt;SomeResponse&gt;() {
                            @Override
                            public void onResponse(SomeResponse response) {
                                getData(response);
                            }
                        }
                        ,
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                ErrorResponse errorResponse = new ErrorResponse();
                                errorResponse.setMessage(Constant.NETWORK_ERROR);
                                getError(errorResponse);
                            }
                        }
                );

        NetworkInstance.addRequest(context, poiResponseGetRequest, sTAG);
    }

    public static void cancelRequest(Context context) {
        NetworkInstance.cancelAllRequests(context, sTAG);
    }

    protected abstract void getSomeThing();

    protected abstract void getData(SomeResponse response);

    protected abstract void getError(ErrorResponse response);
}
</code></pre>

<p>my BasePresenter Class: </p>

<pre><code>public interface BasePresenterListener {
    void onResponse();
}

</code></pre>

<p>my Unit Test Function:</p>

<pre><code>    @Test
    public void test() throws InterruptedException {
        new SomePresenter(mockContext, 107){

            @Override
            protected void getData(PoiResponse response) {
                SomeLogger.debug(""getData works"");//this is not called.
            }

            @Override
            protected void getSomeThing() {
                SomeLogger.debug(""getSomeThing works!"");//this is called.
            }

            @Override
            protected void getError(ErrorResponse response) {
                SomeLogger.debug(""ErrorResponse works!""); //this is not called.
            }
        };
    }

</code></pre>

<p>I have looked below links none of them solved my problem.</p>

<p><a href=""https://stackoverflow.com/questions/37032558/unit-testing-a-network-response-works-when-debugging-not-when-actually-running"">Unit testing a network response. Works when debugging, not when actually running</a></p>

<p><a href=""https://stackoverflow.com/questions/24399423/android-unit-test-with-volley"">Android Unit test with Volley</a><a href=""https://stackoverflow.com/questions/24399423/android-unit-test-with-volley""></a></p>

<p>In my case is I can reach the <code>getSomething()</code> function from unit test  but I cannot reach the <code>getData()</code> nor <code>getError()</code> functions because Volley does not seem to work in unit tests. </p>

<p>All, <code>getSomething()</code>, <code>getData()</code>, <code>getError()</code> functions are callback functions, I can reach the <code>getSomeThing()</code> function but I cannot reach the <code>getData()</code> and <code>getError()</code> functions.</p>
",https://stackoverflow.com/questions/58389841/unit-testing-in-network-with-using-volley-in-android,"['java', 'android', 'unit-testing', 'junit', 'android-volley']",123,False,1,0
Jest Typescript: mock doesn&#39;t return expected shape,"<p>I have a TypeScript file that I'm trying to mock with Jest.  Here is the file:</p>
<pre><code>export class Logger {
  log(message) =&gt; {console.log(message); }
}
</code></pre>
<p>The class I am unit testing has <code>Logger</code> as a dependency so I'm trying to create a mock that will be reusable in other tests.  Here is my attempt at a mock:</p>
<pre><code>export const MockLogger = jest.fn&lt;Logger, any&gt;(() =&gt; {
  const mockedObject = {
    log: jest.fn()
  };

  return mockedObject;
});
</code></pre>
<p>In my test file I import the constant and try to use it.</p>
<pre><code>import {MyService} from './my-service';
import {MockLogger} from './mock-logger';

describe('...', () =&gt; {
  let service: MyService; // depends on Logger
  
  beforeEach(() =&gt; {
    jest.resetAllMocks();
    service = new MyService(MockLogger());
  });
});
</code></pre>
<p>But <code>MockLogger()</code> logs as <code>undefined</code>.  I've also tried injecting <code>new MockLogger()</code> and that appears to be a <code>mockConstructor {}</code>.  Don't know what that is; either way, neither has the <code>.log()</code> function that <code>MyService</code> wants to call.</p>
<p>Using <code>jest@^24.9</code> and <code>typescript@^3.6</code></p>
<h3>Additional Info</h3>
<p>It must have to do with the timing of execution. If i place the same exact mock at the beginning of the test itself, it works.</p>
<h3>Think I got it</h3>
<p>The <code>jest.resetAllMocks()</code> in my before each clears out the mock before it has a chance to be used.</p>
",https://stackoverflow.com/questions/59330479/jest-typescript-mock-doesnt-return-expected-shape,"['typescript', 'unit-testing', 'jestjs']",111,False,1,0
Validating if request body in HTTP POST request is null in Spring Boot controller,"<p>I am replacing manual validation of input to a POST request in a Spring Boot REST-controller. JSR-303 Spring Bean Validation is used for validating the instance variables in the request body and this is working as expected. What is the recommended method to validate that the object in the request body is not null?</p>

<p>I have tried: </p>

<ul>
<li><p>annotating the entire object such as this: @NotNull @Valid @RequestBody Foo foo</p></li>
<li><p>annotating the entire class with @NotNull </p></li>
</ul>

<p>I am replacing:</p>

<pre class=""lang-java prettyprint-override""><code>@PostMapping...
public ResponseEntity&lt;Map&lt;String, Object&gt;&gt; editFoo(
@RequestBody Foo foo, ...) {
   if(foo == null) {
      return (new ResponseEntity&lt;&gt;(headers, HttpStatus.BAD_REQUEST));
   }
}
</code></pre>

<p>with a Bean Validation equivalent:</p>

<pre class=""lang-java prettyprint-override""><code>@PostMapping...
public ResponseEntity&lt;Map&lt;String, Object&gt;&gt; editFoo(
@Valid @RequestBody Foo foo, ...) {
   ...
}
</code></pre>

<p>I tried unit testing the controller method by:</p>

<pre class=""lang-java prettyprint-override""><code>// Arrange
    Foo foo = null;
    String requestBody = objectMapper.writeValueAsString(foo);

    // Act + assert
    mockMvc
    .perform(
    post(""/end_point"")
    .contentType(""application/json"")
    .content(requestBody))
    .andExpect(status().isBadRequest());
</code></pre>

<p>I expected a MethodArgumentNotValidException which is handled by a @ControllerAdvice for this exception, but I get HttpMessageNotReadableException when executing the unit test.
My questions:</p>

<ol>
<li>is it necessary to test if the request body is null?</li>
<li>if 1. is true, how should this be done with Bean Validation?</li>
</ol>
",https://stackoverflow.com/questions/57038083/validating-if-request-body-in-http-post-request-is-null-in-spring-boot-controlle,"['spring', 'rest', 'spring-boot', 'controller', 'httprequest']",23623,True,1,1
Unit testing memory leaks using xUnit,"<p>I recently read <a href=""https://michaelscodingspot.com/find-fix-and-avoid-memory-leaks-in-c-net-8-best-practices/"" rel=""nofollow noreferrer"">this article</a> and it was all about finding, fixing and avoiding memory leaks. I had a feeling that my ASP.NET Core 3.1 app was leaking because it kept increasing the memory usage for the first few minutes but after I kept it opened for like 5 minutes, it sticked to 350 MB in the <em>Diagnostic Tools</em> in Visual Studio 2019. Everything is probably okay because I usually don't forget to dispose stuff (by <em>using</em> block) but I wanted to make sure because my web app is listening to web sockets event for lifetime unless a CancellationToken is requested by the user.</p>

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

<p>In that article, I saw that it's possible to test an object for memory leak.</p>

<pre><code>[Test]
void MemoryLeakTest()
{
  var weakRef = new WeakReference(leakyObject)
  // Ryn an operation with leakyObject
  GC.Collect();
  GC.WaitForPendingFinalizers();
  GC.Collect();
  Assert.IsFalse(weakRef.IsAlive);
}
</code></pre>

<p>Can the following code be tested for memory leaks in unit testing using xUnit? More specifically, <code>timer</code> and <code>_subscription</code>.</p>

<pre><code>using Binance.Entity;
using Binance.Extensions;
using Binance.Helpers;
using Binance.Interfaces;
using Binance.Models.Redis;
using Binance.Net;
using Binance.Net.Interfaces;
using Binance.Net.Objects;
using CryptoExchange.Net.Authentication;
using CryptoExchange.Net.Sockets;
using Hangfire;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Binance.Services
{
    public interface IBotService
    {
        void RunStart(Bot bot);
        Task StopAsync();
    }

    public class BotService : IBotService, IDisposable
    {
        private readonly ILogger _logger;
        private readonly IConfiguration _configuration;
        private readonly IBinanceClient _client;
        private readonly IBinanceSocketClient _socketClient;
        private readonly INotificationService _notificationService;

        public BotService(
            ILogger&lt;BotService&gt; logger,
            IConfiguration configuration,
            IBinanceClient client,
            IBinanceSocketClient socketClient,
            INotificationService notificationService)
        {
            _logger = logger;
            _configuration = configuration;
            _client = client;
            _socketClient = socketClient;
            _notificationService = notificationService;
        }

        private void ApplyCredentialsOnClient()
        {
            BinanceClient.SetDefaultOptions(new BinanceClientOptions()
            {
                ApiCredentials = new ApiCredentials(_configuration.GetValue&lt;string&gt;(""BinanceConfig:ApiKey""), _configuration.GetValue&lt;string&gt;(""BinanceConfig:SecretKey"")),
                AutoTimestamp = true,
                AutoTimestampRecalculationInterval = TimeSpan.FromMinutes(30)
            });

            BinanceSocketClient.SetDefaultOptions(new BinanceSocketClientOptions()
            {
                ApiCredentials = new ApiCredentials(_configuration.GetValue&lt;string&gt;(""BinanceConfig:ApiKey""), _configuration.GetValue&lt;string&gt;(""BinanceConfig:SecretKey"")),
                AutoReconnect = true,
                ReconnectInterval = TimeSpan.FromHours(24)
            });
        }

        private UpdateSubscription _subscription;

        public void RunStart(Bot bot)
        {
            BackgroundJob.Enqueue(() =&gt; Start(bot));
        }

        public void Start(Bot bot)
        {
            ApplyCredentialsOnClient();

            bool locked = false;
            Timer timer = null; 

            BinanceKline lastKnownKline = null;
            _subscription = _socketClient.SubscribeToKlineUpdates(bot.CryptoPair.Symbol, bot.TimeInterval.Interval, async data =&gt;
            {
                if (data.Data.Final)
                {
                    lastKnownKline = data.Data.ToKline();

                    // Static logic

                    // Clean up
                    if (locked)
                    {
                        locked = false;
                        timer?.Dispose();
                    }
                }
                // This block won't be executed before the static block is executed first
                else if (lastKnownKline != null &amp;&amp; lastKnownKline.Close != data.Data.Close)
                {
                    lastKnownKline = data.Data.ToKline();

                    if (!locked)
                    {
                        locked = true;

                        timer = new Timer(async state =&gt;
                        {
                            // Real time logic

                            bool condition = true;
                            if (condition)
                            {
                                timer?.Change(Timeout.Infinite, 0);
                            }
                        }, null, TimeSpan.Zero, TimeSpan.FromSeconds(scheduledTime));
                    }
                }
            }).Data;
        }

        public async Task StopAsync()
        {
            await _socketClient.Unsubscribe(_subscription);
        }

        private bool _disposed = false;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                _client.Dispose();
            }

            _disposed = true;
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/59375952/unit-testing-memory-leaks-using-xunit,"['unit-testing', 'asp.net-core', 'memory-leaks']",672,False,1,0
pytest fails with pyspark 2.3.2 but passes with 2.4.2,"<p>I'm struggling with unit testing some <code>pyspark</code> code. Assume I have the following minimal code:</p>

<pre class=""lang-py prettyprint-override""><code># foo.py
import pyspark.sql.functions as F


def my_func(df):
    return df.select(F.col(""myCol"")).collect()

</code></pre>

<p>In addition I have two <code>test_</code> files:</p>

<pre class=""lang-py prettyprint-override""><code># test_no_import.py
import pytest


@pytest.fixture
def sqlC():
    # For this to work I had to tweak:
    # $ export JAVA_HOME=""$(/usr/libexec/java_home --version 1.8)""
    import findspark

    findspark.init()

    from pyspark.sql import SparkSession
    from pyspark.sql import SQLContext

    spark = SparkSession.builder.master(""local[*]"").getOrCreate()
    sc = spark.sparkContext
    return SQLContext(sc)


def test_foo(sqlC):
    df = sqlC.createDataFrame([(""charly"", 15), (""nick"", 40)], [""name"", ""age""])
    assert True
</code></pre>

<p>and</p>

<pre class=""lang-py prettyprint-override""><code># test_with_import.py
import pytest
import foo


@pytest.fixture
def sqlC():
    # For this to work I had to tweak:
    # $ export JAVA_HOME=""$(/usr/libexec/java_home --version 1.8)""
    import findspark

    findspark.init()

    from pyspark.sql import SparkSession
    from pyspark.sql import SQLContext

    spark = SparkSession.builder.master(""local[*]"").getOrCreate()
    sc = spark.sparkContext
    return SQLContext(sc)


def test_foo(sqlC):
    df = sqlC.createDataFrame([(""charly"", 15), (""nick"", 40)], [""myCol"", ""age""])
    print(foo.my_func(df))
    assert True
</code></pre>

<p>Note that in the latter, I import <code>foo</code>.</p>

<p>Next, I create a <code>conda</code> environment: </p>

<pre class=""lang-sh prettyprint-override""><code>conda create -n foo python=3.7
</code></pre>

<p>and I install <code>pyspark</code> (using <code>conda install -c conda-forge pyspark=2.4.2</code>), <code>pytest</code> and <code>findspark</code> (using <code>pip install findspark</code>).</p>

<p>Finally, I run the tests using <code>pytest</code>. Both tests pass! Great. Now, I want to test the code with version 2.3.2 of <code>pyspark</code> so I downgrade:</p>

<pre class=""lang-sh prettyprint-override""><code>conda install -c conda-forge pyspark=2.3.2
</code></pre>

<p>and I run <code>pytest</code> again. Now, <em>both</em> tests fail. However, just running <code>pytest test_no_import.py</code> passes. Running <code>pytest test_with_import.py</code> on the other hand fails... In this case the error is:</p>

<pre><code>sqlC = &lt;pyspark.sql.context.SQLContext object at 0x118614990&gt;

    def test_foo(sqlC):
&gt;       df = sqlC.createDataFrame([(""charly"", 15), (""nick"", 40)], [""myCol"", ""age""])

test_with_import.py:23:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
../anaconda3/envs/foo/lib/python3.7/site-packages/pyspark/sql/context.py:302: in createDataFrame
    return self.sparkSession.createDataFrame(data, schema, samplingRatio, verifySchema)
../anaconda3/envs/foo/lib/python3.7/site-packages/pyspark/sql/session.py:692: in createDataFrame
    jrdd = self._jvm.SerDeUtil.toJavaArray(rdd._to_java_object_rdd())
../anaconda3/envs/foo/lib/python3.7/site-packages/pyspark/rdd.py:2296: in _to_java_object_rdd
    return self.ctx._jvm.SerDeUtil.pythonToJava(rdd._jrdd, True)
../anaconda3/envs/foo/lib/python3.7/site-packages/pyspark/rdd.py:2474: in _jrdd
    self.preservesPartitioning)
../anaconda3/envs/foo/lib/python3.7/site-packages/py4j/java_gateway.py:1525: in __call__
    answer, self._gateway_client, None, self._fqn)
../anaconda3/envs/foo/lib/python3.7/site-packages/pyspark/sql/utils.py:63: in deco
    return f(*a, **kw)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

answer = 'xspy4j.Py4JException: Constructor org.apache.spark.api.python.PythonRDD([class org.apache.spark.rdd.ParallelCollectio...java:69)\\n\tat py4j.GatewayConnection.run(GatewayConnection.java:238)\\n\tat java.lang.Thread.run(Thread.java:748)\\n'
gateway_client = &lt;py4j.java_gateway.GatewayClient object at 0x1185e59d0&gt;, target_id = None, name = 'org.apache.spark.api.python.PythonRDD'

    def get_return_value(answer, gateway_client, target_id=None, name=None):
        """"""Converts an answer received from the Java gateway into a Python object.

        For example, string representation of integers are converted to Python
        integer, string representation of objects are converted to JavaObject
        instances, etc.

        :param answer: the string returned by the Java gateway
        :param gateway_client: the gateway client used to communicate with the Java
            Gateway. Only necessary if the answer is a reference (e.g., object,
            list, map)
        :param target_id: the name of the object from which the answer comes from
            (e.g., *object1* in `object1.hello()`). Optional.
        :param name: the name of the member from which the answer comes from
            (e.g., *hello* in `object1.hello()`). Optional.
        """"""
        if is_error(answer)[0]:
            if len(answer) &gt; 1:
                type = answer[1]
                value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
                if answer[1] == REFERENCE_TYPE:
                    raise Py4JJavaError(
                        ""An error occurred while calling {0}{1}{2}.\n"".
                        format(target_id, ""."", name), value)
                else:
                    raise Py4JError(
                        ""An error occurred while calling {0}{1}{2}. Trace:\n{3}\n"".
&gt;                       format(target_id, ""."", name, value))
E                   py4j.protocol.Py4JError: An error occurred while calling None.org.apache.spark.api.python.PythonRDD. Trace:
E                   py4j.Py4JException: Constructor org.apache.spark.api.python.PythonRDD([class org.apache.spark.rdd.ParallelCollectionRDD, class org.apache.spark.api.python.PythonFunction, class java.lang.Boolean]) does not exist
E                       at py4j.reflection.ReflectionEngine.getConstructor(ReflectionEngine.java:179)
E                       at py4j.reflection.ReflectionEngine.getConstructor(ReflectionEngine.java:196)
E                       at py4j.Gateway.invoke(Gateway.java:237)
E                       at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
E                       at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
E                       at py4j.GatewayConnection.run(GatewayConnection.java:238)
E                       at java.lang.Thread.run(Thread.java:748)

../anaconda3/envs/foo/lib/python3.7/site-packages/py4j/protocol.py:332: Py4JError
</code></pre>

<ul>
<li>What's going on here?</li>
<li>How is it possible that when having version 2.3.2 a single test passes but the two of them together do not?</li>
</ul>

<p>BTW: I am trying to test with version 2.3.2 because I want to align with the version installed on the clusters I work with.</p>
",https://stackoverflow.com/questions/57710771/pytest-fails-with-pyspark-2-3-2-but-passes-with-2-4-2,"['python', 'pyspark', 'pytest', 'conda']",635,False,1,0
Can custom Material-UI components be tested with React Testing Library?,"<p>I'm evaluating widget toolkits for a new project, and I want to be sure that I can write unit tests for them first. So I've created a simple component using Material-UI based on react-autosuggest using axios to query a simple API. The component works just fine, but I can't seem to get it to work with React Testing Library.</p>

<p>The test is failing with this: ""Cannot read property 'px' of undefined""</p>

<p>It almost seems as though Material-UI isn't loading fully, so the component can't be tested until it is. I have no previous experience with unit testing React components, but shouldn't it load in all the dependencies at the top of my component when it renders?</p>

<p>Here's a demo of my failure in Code Sandbox: 
<a href=""https://codesandbox.io/s/testing-material-ui-problem-ndn9f"" rel=""nofollow noreferrer"">https://codesandbox.io/s/testing-material-ui-problem-ndn9f</a></p>
",https://stackoverflow.com/questions/56829213/can-custom-material-ui-components-be-tested-with-react-testing-library,"['reactjs', 'react-testing-library']",161,False,1,0
C# Mock a custom interface,"<p>I have this function that I am testing, which is called CreateMessageHistory, it has 2 dependencies, the IhttpClientFactory and another interface, I was able to mock the httpclient but I cant mock the interface</p>

<pre><code>public class MessageHistoryService : IMessageHistoryService
{
    private const string API_MESSAGING_DB = ""messages"";
    private const string API_GET_MESSAGE_HISTORY_DESIGN = ""_design/upn-timesent"";
    private const string API_GET_MESSAGE_HISTORY_DESIGN_VIEW = ""_view/upn-timesent-query"";
    private readonly ICouchDbClients couchDbClient;
    private readonly IHttpClientFactory clientFactory;


    public MessageHistoryService(
        IHttpClientFactory clientFactory,
        ICouchDbClients couchDbClient)
    {
        this.couchDbClient = couchDbClient ??
            throw new ArgumentNullException(nameof(couchDbClient));

        this.clientFactory = clientFactory ??
            throw new ArgumentNullException(nameof(clientFactory));
    }

    public async Task CreateMessageHistory(Message message)
    {
        var client = this.clientFactory.CreateClient(NamedHttpClients.COUCHDB);

        var formatter = new JsonMediaTypeFormatter();
        formatter.SerializerSettings = new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
            NullValueHandling = NullValueHandling.Ignore,
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };

        Guid id = Guid.NewGuid();

        var response = await this.couchDbClient.AuthenticatedQuery(async () =&gt; {
            return await client.PutAsync($""{API_MESSAGING_DB}/{id.ToString()}"", message, formatter);
        }, NamedHttpClients.COUCHDB, client);

        if (!response.IsSuccessStatusCode)
        {
            throw new HttpRequestException(await response.Content.ReadAsStringAsync());
        }
    }
}
</code></pre>

<p>I seem to be having a problem about this interface...</p>

<pre><code>public interface ICouchDbClients
{
    Task&lt;HttpResponseMessage&gt; AuthenticatedQuery(Func&lt;Task&lt;HttpResponseMessage&gt;&gt; query, string name, HttpClient client);
}
</code></pre>

<p>Here is the implementation of that interface:</p>

<pre><code>public class CouchDbClients : ICouchDbClients
{
    private readonly Dictionary&lt;string, string&gt; authSessions;
    private readonly Dictionary&lt;string, Credentials&gt; couchDbCredentials;
    private readonly IOptions&lt;Clients&gt; clients;
    private readonly string AuthCouchDbCookieKeyName = ""AuthSession"";

    public CouchDbClients(IOptions&lt;Clients&gt; clients)
    {
        this.clients = clients ??
            throw new ArgumentNullException(nameof(couchDbCredentials));

        this.couchDbCredentials = new Dictionary&lt;string, Credentials&gt;();
        this.couchDbCredentials.Add(NamedHttpClients.COUCHDB, this.clients.Value.Work);

        this.authSessions = new Dictionary&lt;string, string&gt;();
    }

    public async Task&lt;HttpResponseMessage&gt; AuthenticatedQuery(Func&lt;Task&lt;HttpResponseMessage&gt;&gt; query, string name, HttpClient client)
    {
        int counter = 0;
        var response = new HttpResponseMessage();

        do
        {
            Authenticate(name, client);
            response = await query();

            if (response.IsSuccessStatusCode)
            {
                break;
            }
            else if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                this.authSessions[name] = GenerateCookie(client, name);
            }
            else
            {
                throw new HttpRequestException(await response.Content.ReadAsStringAsync());
            }

            counter++;
        } while (counter &lt; 3);

        return response;
    }

    private void Authenticate(string name, HttpClient client)
    {
        CookieContainer container = new CookieContainer();
        var session = this.authSessions.ContainsKey(name);

        if (!session)
        {
            var newCookie = GenerateCookie(client, name);
            authSessions.Add(name, newCookie);
        }

        container.Add(
            client.BaseAddress,
            new Cookie(AuthCouchDbCookieKeyName, this.authSessions[name])
            );
    }

    private string GenerateCookie(HttpClient client, string name)
    {
        string authPayload = JsonConvert.SerializeObject(this.couchDbCredentials[name]);

        var authResult = client.PostAsync(
            ""_session"",
            new StringContent(authPayload, Encoding.UTF8, ""application/json"")
            ).Result;

        if (authResult.IsSuccessStatusCode)
        {
            var responseHeaders = authResult.Headers.ToList();
            string plainResponseLoad = authResult.Content.ReadAsStringAsync().Result;

            var authCookie = responseHeaders
                .Where(r =&gt; r.Key == ""Set-Cookie"")
                .Select(r =&gt; r.Value.ElementAt(0)).FirstOrDefault();

            if (authCookie != null)
            {
                int cookieValueStart = authCookie.IndexOf(""="") + 1;
                int cookieValueEnd = authCookie.IndexOf("";"");
                int cookieLength = cookieValueEnd - cookieValueStart;
                string authCookieValue = authCookie.Substring(cookieValueStart, cookieLength);
                return authCookieValue;
            }
            else
            {
                throw new Exception(""There is auth cookie header in the response from the CouchDB API"");
            }
        }
        else
        {
            throw new HttpRequestException(string.Concat(""Authentication failure: "", authResult.ReasonPhrase));
        }
    }
}
</code></pre>

<p>and here is my unit testing : </p>

<pre><code>[Fact]
    public async Task Should_NotThrowHttpRequestException_When_AMessageHistoryIsCreated()
        {
            var recipients = MockMessage.GetRecipients(279, 1, 2, 3);
            var message = MockMessage.GetMessage(recipients);

            mockStateFixture
                .MockMessageHistoryService
                .Setup(service =&gt; service.CreateMessageHistory(message));

            // ARRANGE
            var handlerMock = new Mock&lt;HttpMessageHandler&gt;(MockBehavior.Strict);

            handlerMock
               .Protected()
               .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;(
                  ""SendAsync"",
                  ItExpr.IsAny&lt;HttpRequestMessage&gt;(),
                  ItExpr.IsAny&lt;CancellationToken&gt;())
               .ReturnsAsync(new HttpResponseMessage()
               {
                   StatusCode = HttpStatusCode.Created
               })
               .Verifiable();

            // create the mock client
            // use real http client with mocked handler here
            var httpClient = new HttpClient(handlerMock.Object)
            {
                BaseAddress = new Uri(""http://10.179.236.207:5984/""),
            };

            mockStateFixture.MockIHttpClientFactory.Setup(x =&gt; x.CreateClient(NamedHttpClients.COUCHDB))
                                 .Returns(httpClient);

            //var httpResponseMessage = new Mock&lt;Task&lt;HttpResponseMessage&gt;&gt;();


            //httpResponseMessage.Setup


            var httpResponseMessage = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.Created
            };


            //httpResponseMessage.Setup(x =&gt; x.StatusCode = HttpStatusCode.Created);

            //mockStateFixture.MockCouchDbClient.Setup(x =&gt; x.AuthenticatedQuery(
            //    async () =&gt;
            //    {
            //        return await httpResponseMessage;
            //    },
            //    NamedHttpClients.COUCHDB,
            //    httpClient))
            //    .Returns(It.IsAny&lt;Task&lt;HttpResponseMessage&gt;&gt;);

            var messageHistoryService = new MessageHistoryService(
                mockStateFixture.MockIHttpClientFactory.Object, mockStateFixture.MockCouchDbClient.Object);

            var task = messageHistoryService.CreateMessageHistory(message);
            var type = task.GetType();
            Assert.True(type.GetGenericArguments()[0].Name == ""VoidTaskResult"");
            Assert.True(type.BaseType == typeof(Task));
            await task;
        }
</code></pre>

<p>How do I mock the ICouchDbClients, do I even have to?</p>

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

<p>Test Name:  </p>

<blockquote>
  <p>Data.Tests.MessageHistoryServiceTests+CreateMessageHistory.Should_NotThrowHttpRequestException_When_AMessageHistoryIsCreated
  Test
  FullName: Data.Tests.MessageHistoryServiceTests+CreateMessageHistory.Should_NotThrowHttpRequestException_When_AMessageHistoryIsCreated
  Test Source:  C:\Data.Tests\MessageHistoryServiceTests.cs : line 36
  Test Outcome: Failed Test Duration:   0:00:00.393</p>
</blockquote>

<p>Result StackTrace:  </p>

<blockquote>
  <p>at Data.API.MessageHistoryService.CreateMessageHistory(Message
  message) in C:\Data\API\MessageHistoryService.cs:line 51    at
  Data.Tests.MessageHistoryServiceTests.CreateMessageHistory.Should_NotThrowHttpRequestException_When_AMessageHistoryIsCreated()
  in C:\Data.Tests\MessageHistoryServiceTests.cs:line 100
  --- End of stack trace from previous location where exception was thrown --- Result Message:  System.NullReferenceException : Object
  reference not set to an instance of an object.</p>
</blockquote>
",https://stackoverflow.com/questions/55246122/c-mock-a-custom-interface,"['c#', 'asp.net-core', 'moq', 'xunit']",773,False,1,0
How do I mock away Ignition.start(),"<p>For various reasons my unit testing environment won't have access to the environment that's needed to start ignite.  I don't need ignite to start for the test and I'd like for the code to just ignore the call to Ignition.start().  How do I do that?</p>

<p>I've tried mocking away ignition but when I try to mock away the start() method it throws an error.</p>

<pre><code>when(ignitionMock.start())
</code></pre>

<p>This results in the following error: </p>

<p>org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);</p>

<p>Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods <em>cannot</em> be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.</p>
",https://stackoverflow.com/questions/56049153/how-do-i-mock-away-ignition-start,"['java', 'unit-testing', 'junit', 'mocking', 'mockito']",403,True,1,1
Kestrel not listening in xUnit test,"<p>I'm using this custom server for unit-testing where I initialize it with <code>MyStarup</code> that loads a single middleware that I need for testing.</p>

<p>This has worked before with net47 and it stopped after I switched the project to .net-core. It now gives me this very helpful exception:</p>

<blockquote>
  <p>System.Net.Sockets.SocketException
  No connection could be made because the target machine actively refused it 127.0.0.1:30001</p>
</blockquote>

<p>I create it from a <code>IClassFixture</code> with a factory method and call it with a <code>HttpClient</code> that I also create with a factory method and get it from the same fixture.</p>

<pre><code>public class MyServer : IDisposable
{
    private readonly IWebHost _host;        

    public MyServer(string url) // &lt;-- http://localhost:30001
    {
        _host =
            new WebHostBuilder()
                .UseKestrel()
                .UseUrls(url)                    
                .UseStartup&lt;MyStartup&gt;()
                .Build();

        Task = _host.StartAsync(); // &lt;-- tried RunAsync too, no difference
    }

    public Task Task { get; set; }

    public void Dispose()
    {
        _host.Dispose();
    }
}
</code></pre>

<p>So my question is, how can I make it work again?</p>

<p>I read this <a href=""https://stackoverflow.com/questions/49895258/why-kestrel-doesnt-listen-at-specified-port"">Why Kestrel doesn't listen at specified port?
</a> but it doesn't help solve it. I cannot run it as a console and it was working before. Why has it stopped after switching to .net-core?</p>
",https://stackoverflow.com/questions/57224717/kestrel-not-listening-in-xunit-test,"['c#', 'unit-testing', '.net-core', 'xunit.net', 'kestrel-http-server']",1050,True,1,1
Missing attributes are not caught by the Python supported IDEs,"<p>Coming from a Java/C# background Developers are used to rely on the IDEs to tell and not let them run their code if an obvious bug is present (e.g. trying to access an nonexistent attribute from module/class).</p>

<p>In this simplest example I came up with, someone changed <code>Customer</code> class (see <code># Step 1</code>) and didn't refactor the rest of the project which will eventually throw an uncaught exception (see <code># Step 3</code>):</p>

<pre><code>from threading import Thread, Event
from random import randrange
import time

class Customer:
    def __init__(self, full_name, address, email):
        self.full_name = full_name
        self.address = address

        # Step 1 - For some reason (e.g. refactoring) someone decided to comment out/rename/remove the email attribute.
        #self.email = email

def my_long_running_task():

    # Step 2 - Wait for a user request to print its email with a 20% chance it will happen every second in this example. 
    # But in real life this could take hours or days until it's triggered since we don't control the user.
    while True:
        if randrange(5) == 1:
            # Step 3 - Once triggered, this will thrown exception: AttributeError: 'Customer' object has no attribute 'email'
            print(""Email:"" + customer1.email)
        time.sleep(1)

if __name__ == '__main__':
    customer1 = Customer(""Adam"", ""1 Street Lower"", ""adam@email.com"")
    print(""Full name: "" + customer1.full_name)
    print(""Address:"" + customer1.address)

    my_long_running_task()
</code></pre>

<p>Even if the Developer did test the script it doesn't mean it's bug free and the exception above will be thrown at a random point in time while in production.</p>

<p>Unit Testing would help but to enforce 100% code coverage is considered unreasonable and a bad practice as it lowers the quality of the actual tests.</p>

<p>VS Code and PyCharm are not flagging the missing reference/attribute <code>customer1.email</code>. Am I missing any extension/setting? Any suggestion/approach?</p>
",https://stackoverflow.com/questions/57290099/missing-attributes-are-not-caught-by-the-python-supported-ides,"['python', 'python-3.x', 'visual-studio-code', 'pycharm']",141,True,1,1
Vue Unit Testing: Using Functions imported Incorrectly into a Component,"<p>I'm trying to retrofit unit testing into an old Vue app that we've developed. The one gotcha that's been set by my senior is that I cannot change any of the code in the actual app (this is causing too much headache for me).</p>

<p>Now, I'm trying to test if a method is activated when a user clicks a button:</p>

<pre><code>import { mount, shallowMount, createLocalVue } from '@vue/test-utils';
import { expect } from 'chai';
import Vuex from 'vuex';
import sinon from 'sinon';
import AccountCreation from '@/components/.../AccountCreation.vue';
import createStoreConfig from '@/store/create-store-config';

const localVue = createLocalVue();
localVue.use(Vuex);

const storeConfig = createStoreConfig();
const store = new Vuex.Store(storeConfig);
store.state.selectedMemberType = 'writer';

describe('Account Creation', () =&gt; {
  const wrapper = shallowMount(AccountCreation, {
    methods: {
    },
    store,
    localVue,
  });
  it('should return a writer argument when the validate username button is clicked', () =&gt; {
      let ga = () =&gt; {console.log('test')}
      const button = wrapper.find('#accountCreation .col-xl-5 .card span ').trigger('click')
  })
});
</code></pre>

<p>I know there's no <code>expect</code> in this test.
And the actual method looks like this. I know the method is being triggered, but <code>mocha</code>/<code>chai</code> throws an error before it can set a success.</p>

<p>I can't share the actual code, but basically it will do something like this:</p>

<pre><code>validateUsername(fieldName) {
  ga('send', 'event', 'page' 'action' 'error')
}
</code></pre>

<p>There's more to the code, but none of it is run through since <code>ga</code> will throw a <code>ReferenceError</code> when run. Google Analytics was weirdly imported in <code>main.js</code>, so I can't stub it in the normal <code>sinon</code> or <code>mocha</code> way.</p>
",https://stackoverflow.com/questions/54541184/vue-unit-testing-using-functions-imported-incorrectly-into-a-component,"['javascript', 'unit-testing', 'vue.js', 'sinon', 'chai']",191,True,1,1
What is a good practice to write unit-test on .net core Ihostedservice?,"<p>I have a background task initiated in .net core 2.0 startup, inherits from  backgroundservice, implementing StartAsync, StopAsync and ExecuteAsync.  This task is to update some data in database table periodically based on some business logic.  </p>

<p>While I can run the backgroundtask as an application and test using logs, db check and with the help of other tools, can the unit-testing is necessary for testing the backgroundtask? If so how to register the task as a service with dependencies and trigger the start and stop methods to assert the actual vs expected? Appreciate some basic sample unit-test method on testing timer based .net core ihostedservice backgroundtask.</p>

<p>Here is my basic test start just for sample, but not completed yet.  Having said that, this is just a thought but not the exact working test.  Here is what need some help from the community.  Can also add some more asserts i.e. Assert.Verify()?</p>

<pre><code>  [Fact]
        public async void Run_background_task_success()
        {
            //Arrange
            IServiceCollection services = new ServiceCollection();

            services.AddHostedService&lt;BackgroundManagerTask&gt;();

            var serviceProvider = services.BuildServiceProvider();

            var service = serviceProvider.GetService&lt;IHostedService&gt;() as BackgroundManagerTask;

            var isExecuted = false;
            if(await service.StartAsync(CancellationToken.None))
{
isExecuted = true;
}

            await Task.Delay(10000);
            Assert.True(isExecuted);

            await service.StopAsync(CancellationToken.None);
        }
</code></pre>
",https://stackoverflow.com/questions/54627665/what-is-a-good-practice-to-write-unit-test-on-net-core-ihostedservice,"['unit-testing', 'microservices', 'background-process', 'asp.net-core-hosted-services']",2308,False,5,1
ViewModel concept still exists in Blazor?,"<p>After answering <a href=""https://stackoverflow.com/questions/40827377/viewmodel-concept-still-exists-in-asp-net-mvc-core"">this question</a> about whether the ViewModel is still applicable in MVC Core, I now find myself with a similar question in Blazor.</p>

<p>I'm starting to build my first complex Blazor page with a lot of state to manage.  Elements of the page will show/hide and update depending on data entered on other parts of the page.</p>

<p>I've worked with React and Redux in the past and found great value in having a single location for all the state, especially for unit testing purposes. </p>

<p>Accordingly, my plan is to have a view-model that contains not only the data I'm going to persist to the database, but also potentially flags such as <code>ShowSalesOrdersPanel</code> that will then be used in <code>if</code> statements in the razor view.</p>

<p>My question is, should this view-model be a separate class, or is the <code>@functions</code> section of the Blazor razor file effectively the view-model?  Should I just use that instead?</p>
",https://stackoverflow.com/questions/56133732/viewmodel-concept-still-exists-in-blazor,['blazor'],7078,True,9,2
How to generate jacoco reports for specific module in android studio?,"<p>I am very new to this environment. I came from a native iOS background.</p>

<p>By using this <a href=""https://blog.gouline.net/code-coverage-on-android-with-jacoco-92ec90c9355e"" rel=""noreferrer"">https://blog.gouline.net/code-coverage-on-android-with-jacoco-92ec90c9355e</a>, I am successfully generating the <code>JACOCO</code> test reports for my unit test class in my android project (app module only).</p>

<p>What I am doing is:</p>

<ol>
<li>I simply create <code>jacoco.gradle</code> file in the main project.</li>
<li>Apply from: <code>'../jacoco.gradle'</code> in <code>app/build.gradle</code> file</li>
<li><p>Added below code in the <code>app/build.gradle</code> file</p>

<pre><code>android { 
... 
    buildTypes { 
        debug { 
            testCoverageEnabled = true 
         } 
        ... 
    } 
... 
}
</code></pre></li>
<li><p>Open a terminal inside the Android Studio and run the command
like</p>

<pre><code>  **gradlew tasks** 
</code></pre></li>
<li><p>To generate a report, run the command</p>

<pre><code>**gradlew testBlueDebugUnitTestCoverage**
</code></pre></li>
<li><p>Finally I found my reports  at this path: <code>\app\build\reports\tests\testTabletDebugUnitTest</code></p></li>
</ol>

<p>By using this <a href=""http://vgaidarji.me/blog/2017/12/20/how-to-configure-jacoco-for-kotlin-and-java-project/"" rel=""noreferrer"">http://vgaidarji.me/blog/2017/12/20/how-to-configure-jacoco-for-kotlin-and-java-project/</a> I have successfully generated the jacoco report for the both Espresso and Coverage test classes (UI and Unit Testing), and also this project includes both java &amp;  kotlin classes.</p>

<p>Now my question is: I want to generate the <code>jacoco</code> test reports for specific module out of all other modules in my app.</p>

<p><strong>System Info:</strong></p>

<pre><code>Windows 10, 
Android Studio 3.3.1, 
Kotlin: ext.kotlin_version = '1.3.21'
Gradle:gradle:3.4.0-alpha01. 
</code></pre>
",https://stackoverflow.com/questions/55185434/how-to-generate-jacoco-reports-for-specific-module-in-android-studio,"['android-studio', 'android-gradle-plugin', 'code-coverage', 'jacoco', 'test-reporting']",2963,False,9,0
functional testing with TFS,"<p>i'm looking to perform functional tests with a special app we build.
that app operates all sorts of embedded functionality and i need to be able to build test cases that perform these actions as a scenario.</p>

<p>we thought we could simply use the TFS API to get info and just write back test runs and their results but it proved to be difficult task to do.</p>

<p>so we researched the ""associated automation"" feature inside test cases, but it seems that i need a special framework for this. i was told only unit testing frameworks such as xunit nunit and mstest can be integrated.
i need functional testing, scenarios that are more complicated than a unit test. </p>

<p>do u have any ideas? on how can i simply run my own tests and update the TFS with runs that i created?</p>
",https://stackoverflow.com/questions/54635090/functional-testing-with-tfs,"['c#', 'tfs', 'azure-devops', 'mstest', 'microsoft-test-manager']",239,True,0,1
JUnit: Run same test on multiple target classes,"<p>I'm trying to automate a way to grade multiple students' files at once in my intro to Java class. </p>

<p>How can I run the same test(s) on all the files in a folder assuming the following conditions are true:</p>

<ul>
<li>All files exist in the same folder (no sub-folders)</li>
<li>All files have a .java extension</li>
<li>All filenames are important identifiers</li>
<li>The code in every file meets the same requirements </li>
</ul>

<pre><code>    SayHelloWorld
    |-bsmithSayHelloWorld.java
    |-athomasSayHelloWorld.java
    |-cjenkinsSayHelloWorld.java
</code></pre>

<p>I'm comfortable with JUnit but I've only used it in a single-file, clunky way in the past through IntelliJ. </p>

<p>Here's a simple sample file I'd be testing against: </p>

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

    public static void main(String[] args) {
        System.out.println(sayHello());
    }
    public static String sayHello(){
        return ""hello Java"";
    }
}
</code></pre>

<p>I would really like to be able to automate unit testing on all the .java files that exist in a given folder and output the results to something I can work with (console, file, whatever).</p>

<p>Possible output might look like:</p>

<pre><code>bsmithSayHelloWorld helloWorldTest: pass
athomasSayHelloWorld helloWorldTest: fail
cjenkinsSayHelloWorld  helloWorldTest: pass
</code></pre>
",https://stackoverflow.com/questions/56369772/junit-run-same-test-on-multiple-target-classes,"['java', 'junit', 'parametrized-testing']",785,False,0,1
Suggestions for dependency injection to view controllers in swift,"<p>I'm making an iOS app with Swift that has different states for most of the view controllers composing the app. The few of the ""states"" the view controllers depend on are whether the user is logged in or not, or if an address is either registered, searched, or missing, etc.. Currently, the data are given to the view controllers in <code>prepare(for:sender)</code> methods.</p>

<p>The following is the structure of my app, and there are about a dozen more view controllers with the similar structure.</p>

<p><code>App.swift</code></p>

<pre class=""lang-swift prettyprint-override""><code>struct App {
  enum LoginState {
    case unregistered
    case registered(User) // User defined elsewhere
  }

  enum OtherState {
    case stateOne
    case stateTwo(AssociatedType)
    case stateThree(OtherAssociatedType)
  }

  // Default states
  var loginState: LoginState = .unregistered
  var otherState: OtherState = .stateOne
}
</code></pre>

<p><code>HomeViewController.swift</code></p>

<pre class=""lang-swift prettyprint-override""><code>class HomeViewController: UIViewController {
  var app: App!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)

    switch segue.identifier {
    case ""Other View Controller Segue"":
      let otherVC = segue.destination as! OtherViewController
      otherVC.app = app

    default:
      break
    }
}
</code></pre>

<p><code>AppDelegate.swift</code></p>

<pre class=""lang-swift prettyprint-override""><code>class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {
    let storybard = UIStoryboard(name: ""Main"", bundle: nil)
    let mainNavController = storyboard.instantiateViewController(withIdentifier: ""Main Navigation Controller"") as! UINavigationController
    let homeViewController = mainNavController.topViewController as! HomeViewController

    window?.rootViewController = mainNavController
    // 'injecting' app to the homeViewController
    homeViewController.app = App()

    return true
}
</code></pre>

<p>I can't find the original post what I found when I first encountered ""how can I pass data between view controllers"" about a year ago, but this is probably one of them: <a href=""https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers"">Passing Data between View Controllers</a> (which does not mention the term dependency injection anywhere).
Then I heard this term <strong>dependency injection</strong> about a month ago, and the fancy term seemed to fit my situation of handling a class (<code>HomeViewController</code> and <code>OtherViewController</code>) that needs to deal with data that can have states (<code>struct App</code>).</p>

<p>To verify this approach of tossing <code>app</code> instance in a segue, I've done some several nights of research.
But now I'm overloaded with too much information about: <a href=""https://www.objc.io/issues/15-testing/dependency-injection/"" rel=""nofollow noreferrer"">several dependency injection methodologies</a>, <a href=""https://www.natashatherobot.com/unit-testing-swift-dependency-injection/"" rel=""nofollow noreferrer"">unit testing in swift via DI</a>, a few DI frameworks <a href=""https://github.com/Swinject/SwinjectStoryboard"" rel=""nofollow noreferrer"">here</a>, <a href=""https://github.com/scribd/Weaver"" rel=""nofollow noreferrer"">here</a>, <a href=""https://github.com/Swinject/Swinject"" rel=""nofollow noreferrer"">here</a>, <a href=""https://github.com/thoughtbot/Perform"" rel=""nofollow noreferrer"">and here</a>, unit testing frameworks <a href=""https://github.com/Quick/Quick"" rel=""nofollow noreferrer"">here</a>, <a href=""https://github.com/Quick/Nimble"" rel=""nofollow noreferrer"">here</a>, and (now I can't add more links due to the lack of reputation..), and a whole bunch of medium / blog / SO posts.</p>

<p>The question is: 1. <em>Am I doing the so-called <strong>dependency injection</strong> here, and is this the ""right way""?</em> 2. <em>Can I proceed unit/UI tests with this approach?</em> 3. <em>If what I am doing is a legit dependcy injection, why would one need a dependency injection framework?</em></p>

<p>Dependency injection frameworks look unnecessary, <em>myterical</em>, (and scary), at least for me simply trying to write a maintainable app that follows SOLID principles.
I'm tired of abstract concepts or seemingly unrelated examples with my situation, so I'd be glad if someone help me out with these concepts and design decisions, including the need of frameworks.</p>
",https://stackoverflow.com/questions/56908556/suggestions-for-dependency-injection-to-view-controllers-in-swift,"['ios', 'swift', 'dependency-injection']",663,True,1,2
Tests run fine like Unit Test but fail to run in Test Explorer (Appium &amp; Specflow),"<p>I am working on automation test with Appium and Specflow . Below is my code </p>

<pre><code>var objectType = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
            from type in assembly.GetTypes()
            where type.FullName.Contains(""Model.ModelsUI"") &amp;&amp; 
            type.FullName.Contains(typeObjectName)
            select type).ToList();
</code></pre>

<p>Everytime I run it in Test Explorer, this statement throw the exception with error message below</p>

<blockquote>
  <p>System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.
      Could not load file or assembly 'Microsoft.IntelliTrace.Core, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.></p>
</blockquote>

<p>However in the same project, if I make it as [TestMethod] for Unit Testing and run this Unit Test. Then it has no problem and give exact expected result.
I have tried to look for solutions on internet and implement most of them eg: check MsTest Adapter installed, delete obj and bin file then rebuild .... but no cigar though. 
I am new. Please help me with this case. It would be really appreciated. Thanks in advance</p>
",https://stackoverflow.com/questions/59385249/tests-run-fine-like-unit-test-but-fail-to-run-in-test-explorer-appium-specflo,"['c#', 'unit-testing', 'appium', 'mstest', 'specflow']",343,False,0,1
Debug Integration test and web api parallely in single .net core 2.2 in single application?,"<p>I have created web Api in .net core 2.2 in visual studio 2017. In the same project I also add new project of unit testing to test the created web api. Now when I debug unit test, it is not working and I can not debug the unit test in debug mode of web api. Please help me to find out the solution of above problem.   </p>

<p>Created Api to get the list of users from database with search feature. Create XUnit test project in same solution to test the created Api. When I try to run XUnit test project, it is showing internal server error and the test is not debuging when I run the web Api. 
Below is the Sample code. There are 2 Project files in single solution. One is for Api and another is for Testing.</p>

<pre><code>[HttpPost]
        public ActionResult SearchCustomer(CustomerSearch objsearch)
        {
            var Search=_ourCustomerRespository.SearchCustomer(objsearch);

            if (Search.Count() == 0)
            return StatusCode(204,new {message = ""No Record Found!""});

            return Ok(Search);
        }




[Fact]
        public async Task SearchCustomers()
        {

            var response = await _TestFixture.Client.PostAsync(""api/Customer/SearchCustomer"", new StringContent(
            JsonConvert.SerializeObject(new CustomerSearch
            {
                custid = 2,
                custfname = """",
                custlname = """",
                custemail = """",
                custorderby = ""customerid"",
                custsortdirection = ""asc"",
                custpagesize = 10,
                custpagenumber = 0
            }), Encoding.UTF8, ""application/json""));
            response.StatusCode.Should().Be(HttpStatusCode.OK);
        }
</code></pre>
",https://stackoverflow.com/questions/56629118/debug-integration-test-and-web-api-parallely-in-single-net-core-2-2-in-single-a,"['asp.net-core-webapi', 'asp.net-core-2.1', 'xunit.net']",421,True,0,1
AddRange() is not working when adding list items to a Collection,"<p>Recently I got a task to work on one of the FxCop warning - <strong><em>Do not expose generic lists</em></strong>. So I tried changing the <code>List&lt;T&gt;</code> to <code>ICollection&lt;T&gt;</code>. But later point of time, while doing the unit testing I found that the <code>AddRange()</code> is not working properly as expected. It is not adding the collection of elements to the collection object.</p>

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

<pre><code>gc.ToList().AddRange(sampleList);
</code></pre>

<p>And I have two questions to ask</p>

<ol>
<li><p>Why it is not adding the items to the collection.
Below is the code:</p>

<pre><code>public class GenericClass
{
    public int Id;
    public string Name;
}  


class Program
{
     static void Main(string[] args)
     {

      ICollection&lt;GenericClass&gt; gc = new  List&lt;GenericClass&gt;();

    var sampleList = new List&lt;GenericClass&gt;()
                         {
                             new GenericClass {Id = 1, Name = ""ASD""},
                             new GenericClass {Id = 2, Name = ""QWER""},
                             new GenericClass {Id = 3, Name = ""BNMV""},
                         };

    Console.WriteLine(gc.GetType()); // gc is of type

    gc.ToList().AddRange(sampleList); // sampleList items are not getting added to gc.
    Console.ReadKey();
}
</code></pre>

<p>}</p></li>
<li><p><code>List&lt;T&gt;</code> inherits from <code>ICollection&lt;T&gt;</code> and <code>List&lt;T&gt;</code> has <code>AddRange()</code>, etc functions. When I tried to cast to parent reference (<code>ICollection&lt;T&gt;</code>) to child class object (<code>List&lt;T&gt;</code>), why doesn't Intellisense suggest <code>AddRange()</code>. Instead I need to do <code>.ToList()</code> and then it shows <code>AddRange()</code>.
<a href=""https://i.stack.imgur.com/imjsw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/imjsw.png"" alt=""Screenshot""></a></p></li>
</ol>

<p>I searched a lot for this. But couldn't find a reason that satisfied me. So please help me with the understanding. It will be a great help.</p>
",https://stackoverflow.com/questions/55390284/addrange-is-not-working-when-adding-list-items-to-a-collection,"['c#', 'generics', 'generic-collections']",8006,True,-2,2
Jest with jest-teamcity-reporter is intermittently reporting one test as failed,"<p>I have a very weird problem. I am using Jest for my react based javascript code unit testing. Also, I am using jest-teamcity-reporter to integrate test result into TeamCity CI. Intermittently one of the tests is reported as failed in the TeamCity even though the test is passed.</p>

<p>JEST console report says all test passed
<a href=""https://i.stack.imgur.com/SR0Jw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/SR0Jw.png"" alt=""enter image description here""></a></p>

<p>TeamCity report (ignore the count that will not match with the previous image as some of the test names are duplicated)
<a href=""https://i.stack.imgur.com/4JyUL.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4JyUL.png"" alt=""enter image description here""></a></p>

<p>Now I am not sure how to debug and resolve it. What parameters or logs to look for? I am unable to reproduce the issue in my local dev environment.</p>

<p>Strangely when it fails it will always report the first test as failed.</p>

<p>I added teamcity parameters to log original service messages and it seems there are failed tests.
<a href=""https://i.stack.imgur.com/aTbu0.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/aTbu0.png"" alt=""Marked failed test has no service message as failed""></a></p>
",https://stackoverflow.com/questions/56330239/jest-with-jest-teamcity-reporter-is-intermittently-reporting-one-test-as-failed,"['javascript', 'jestjs', 'teamcity']",613,False,0,0
How to access static block variables outside of class in java,"<p>I was working on some code in which I need to access the variable ""hs"" present in the static block of one class from another.
Note: Both the class are preset in different packages.</p>

<p>Code is as follow:</p>

<pre><code>public class A{
    static {
        HashSet&lt;String&gt; hs = new HashSet&lt;&gt;();
    }
}
</code></pre>

<p>I Googled about it but nothing found anything helpful.
Your help would be very appreciable.</p>

<p>EDIT: I am not allowed to make changes in this file still need to access it from the other file.</p>

<p>Why I need to do this cause I am doing unit testing by JUnit and there is nothing what this block is returning which I can put assertEquals() on. So the option I left with is to test the side-effects and this variable ""hs"" value is getting changed as a side-effect. That's why I need to access it from another file.</p>
",https://stackoverflow.com/questions/57535236/how-to-access-static-block-variables-outside-of-class-in-java,"['java', 'unit-testing', 'testing', 'static-block']",1592,True,-1,2
Test if a property in objectContaining is an Array or undefined,"<p>I am using Jest (TypeScript on Node.js) for unit testing and would like to check if a specific property is either an <code>Array</code> or <code>undefined</code> using <code>expect.objectContaining()</code>. This property may or may not exist in the object, hence why I want my test to include both cases.</p>

<p>My initial idea was to use</p>

<pre><code>propertyInQuestion: expect.any(Array || undefined)
</code></pre>

<p>inside <code>objectContaining()</code>, but it fails because an <code>Array</code> is expected. When I checked the documentation, it stated that an expected object must be a subset of the received object, so it contains properties that are present in the expected object. So what happens when a property is either present and must be of an <code>Array</code> type or is undefined and therefore not present in the object?</p>

<p>At the moment, test looks something like this</p>

<pre><code>expect(someObject).toEqual(
    expect.objectContaining({
        propertyInQuestion: expect.any(Array),
        something: expect.any(Array),
    })
);
</code></pre>

<p>and the property I'd like to check is <code>propertyInQuestion</code>, which can either be an <code>Array</code> or <code>undefined</code>.</p>

<p>Any sort of help is appreciated. Thank you!</p>
",https://stackoverflow.com/questions/57408215/test-if-a-property-in-objectcontaining-is-an-array-or-undefined,"['node.js', 'typescript', 'jestjs']",441,False,0,0
How to test methods with I/O that require sample files?,"<p>I'm trying to write a test with jasmine for a typescript method that reads a file and processes it. This method has two steps (outside of reading the file): validating the file and then processing it. I want to test that the method throws an exception when the file is invalid.</p>

<p>For my tests, I need example files to test, so I was wondering what the best practice to generate/store representative test files is. Should I create these by hand and save them with the tests? Should I write something that generates files to test? Write something that generates file data to test? Something else entirely?</p>

<p>From other questions (<a href=""https://stackoverflow.com/questions/1528134/unit-testing-file-i-o"">Unit Testing File I/O</a>) I can see that I don't need to test the I/O itself, just the method's functionality, but I do need some data to test the method with.</p>
",https://stackoverflow.com/questions/56947594/how-to-test-methods-with-i-o-that-require-sample-files,"['typescript', 'unit-testing', 'jasmine']",120,True,0,1
Golang test of REST API dumps entire database,"<p>I wrote a small web service to learn unit testing. There is one endpoint to get data with a three-letter string. My code runs fine. The right query is <code>http://localhost:8000/iata/thu</code>, with the last bit <code>thu</code> being the three-letter string. I can get the correct data with it. I can also successfully get 404 with wrong ones. Then I wrote the test. It fails and dumps the entire database.</p>

<p>The SQLite3 database, main.go, and main_test.go are in the same directory.</p>

<p>Here's main_test.go:</p>

<pre><code>package main

import (
    ""net/http""
    ""net/http/httptest""
    ""testing""
)

func TestIata(t *testing.T) {
    // ""thu"" is the three-letter code.
    // I also tried ""http://localhost:8000/iata/thu""
    req, err := http.NewRequest(""GET"", ""/iata/thu"", nil)
    if err != nil {
        t.Fatal(err)
    }
    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(iata)
    handler.ServeHTTP(rr, req)
    if status := rr.Code; status != http.StatusOK {
        t.Errorf(""handler returned wrong status code: got %v want %v"",
            status, http.StatusOK)
    }

    expected := `[{""airport_id"":""10"",""name"":""Thule Air Base"",""city"":""Thule"",""country"":""Greenland"",""iata"":""THU"",""icao"":""BGTL"",""latitude"":""76.5311965942"",""longitude"":""-68.7032012939"",""altitude"":""251"",""timezone"":""-4"",""dst"":""E"",""tz_db"":""America/Thule"",""type"":""airport"",""source"":""OurAirports""}]`
    if rr.Body.String() != expected {
        t.Errorf(""handler returned unexpected body: got %v want %v"",
            rr.Body.String(), expected)
    }
}
</code></pre>

<p>Here's main.go:</p>

<pre><code>package main

import (
    ""database/sql""
    ""encoding/json""
    ""log""
    ""net/http""

    ""github.com/gorilla/mux""
    _ ""github.com/mattn/go-sqlite3""
)

type datum struct {
    AirportID    string `json:""airport_id,omitempty""`
    ...
}

func check(err error) {
    ...
}

// Accesses the database and gets relevant rows.
func getRows(column string, searchTerm string) *sql.Rows {

    db, err := sql.Open(""sqlite3"", ""airports.db"")
    check(err)

    stmt := `SELECT * FROM airports WHERE ` + column + ` LIKE ? COLLATE NOCASE;`

    rows, err := db.Query(stmt, `%`+searchTerm+`%`)
    check(err)

    return rows
}

// Processes the data into a slice so it can be sent out as JSON.
func processData(rows *sql.Rows) []datum {
    data := []datum{}

    // For each row, insert data into a datum instance and then append to data slice.
    for rows.Next() {
        datum := datum{}
        rows.Scan(&amp;datum.AirportID,
            ...)
        data = append(data, datum)
    }
    rows.Close()

    return data
}

// Uses the above code to get data from the database, process it, and send it.
func getAndSendData(w http.ResponseWriter, r *http.Request, searchType string) {
    params := mux.Vars(r)
    searchTerm := params[searchType]

    datum := getRows(searchType, searchTerm)
    processed := processData(datum)

    if len(processed) == 0 {
        http.Error(w, ""Data not found."", 404)
        return
    }
    json.NewEncoder(w).Encode(processed)
}

func main() {
    router := mux.NewRouter()
    router.HandleFunc(""/iata/{iata}"", iata).Methods(""GET"")
    log.Fatal(http.ListenAndServe("":8000"", router))
}

func iata(w http.ResponseWriter, r *http.Request) {
    searchType := ""iata""
    getAndSendData(w, r, searchType)
}
</code></pre>

<p>Running the test gets the entire database dumped in the result:</p>

<pre><code>=== RUN   TestIata
--- FAIL: TestIata (0.21s)
    main_test.go:46: handler returned unexpected body: got [ENTIRE DATABASE DUMPED HERE] want [CORRECT DATA HERE]
FAIL
exit status 1
</code></pre>

<p>I've looked through a lot of tutorials, such as <a href=""https://blog.questionable.services/article/testing-http-handlers-go/"" rel=""nofollow noreferrer"">this</a> one, which I feel is pretty clear. As far as I can tell, my test code is correct. I've also tried running main.go before doing the test. But that shouldn't matter, right?</p>

<p>What am I missing?</p>
",https://stackoverflow.com/questions/55750991/golang-test-of-rest-api-dumps-entire-database,"['rest', 'unit-testing', 'go']",368,False,0,0
Should you test primitive functions in Python?,"<p>I am currently rewriting a large data framework for my company. My company has a basically nonexistent testing policy and I want to change that, but I am very new to testing software. Thus I wanted to ask the following question - </p>

<p>If I have the following function:</p>

<pre><code>def read_attributes(annotation_file=IMPORTED_PATH):
    attributes = {}
    with open(annotation_file) as ga:
        for idx, line in enumerate(ga):
            fields = [field.strip() for field in line.split('\t')]
            if idx == 0:
                continue
            else:
                attributes[fields[0]] = fields[6] #0 - sample, 6 - tissue

    return attributes
</code></pre>

<p>I don't see the point in actually unit-testing it, if I have a previous test that checks if file at <strong>IMPORTED_PATH</strong> actually exists. </p>

<p>I have tried to test whether certain keys are present in the resulting <strong>attributes</strong> dictionary, but I see that as volatile because file at <strong>IMPORTED_PATH</strong> can change it's values. I could also write an if statement checking whether <strong>fields</strong> variable has the necessary amount of entries, but that is more of an internal check than a test.</p>

<p>Should I test this and how would I go about it?</p>
",https://stackoverflow.com/questions/58930965/should-you-test-primitive-functions-in-python,"['python', 'python-3.x', 'unit-testing', 'testing', 'pytest']",68,True,0,1
Why is my assert.areequal failing when the debugger says they are equal?,"<p>This unit test should be passing and I can't figure out why it's not. The code works in my main controller, so I know it does work.  But I feel like it's assessing differently in my unit test.</p>

<p>I have tried various other asserts, with the exception of the false Booleans.  I don't want a false comparison.</p>

<pre><code>    [TestMethod]
    public void DownloadFileNames()
    {
        // Arrange
        string ftpBase = ""myfiles.com/public/doc"";
        string fileName = ""10408c"";

        Search model = new Search();
        model.FileName = fileName;

        //A string to hold the base FTP address:
        Search searchResults = new Search();
        List&lt;string&gt; fnl = new List&lt;string&gt;();
        var uriBuilder = new UriBuilder();

        // Act
        uriBuilder.Scheme = ""ftp"";
        uriBuilder.Host = ftpBase;

        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uriBuilder.Uri);
        reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
        Stream responseStream = response.GetResponseStream();
        List&lt;string&gt; files = new List&lt;string&gt;();
        StreamReader reader = new StreamReader(responseStream);
        while (!reader.EndOfStream)
            files.Add(reader.ReadLine());
        reader.Close();
        responseStream.Dispose();

        //Loop through the resulting file names.
        foreach (string folder in files)
        {

            if (folder.IndexOf(""."") &lt; 1)
            {
                var childDirectory = uriBuilder.Uri + folder + ""/"";
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(childDirectory);
                request.Method = WebRequestMethods.Ftp.ListDirectory;
                response = (FtpWebResponse)request.GetResponse();
                responseStream = response.GetResponseStream();
                reader = new StreamReader(responseStream);
                string result = reader.ReadToEnd();
                reader.Close();
                responseStream.Dispose();

                searchResults.Messages = result;

                if (result.Contains(model.FileName))
                {

                    if (!model.FileName.Contains("".dat""))
                    {
                        model.FileName = model.FileName.Replace("".dat"", """");

                        fnl.Add(ftpBase.Replace(ftpBase, uriBuilder.Uri + folder + ""/"") + model.FileName + "".dat"");
                    }
                    else
                    {
                        fnl.Add(ftpBase.Replace(ftpBase, uriBuilder.Uri + folder + ""/"") + model.FileName);
                    }
                    //UpdateFile(fnl);

                    searchResults.Messages = ""file found"";
                    break;
                }
                else
                {
                    searchResults.Messages = ""file not found"";
                }
            }
            else
            {
                //searchResults.Messages = ""Just Files"";
            }
        }

        // Assert
        Assert.AreEqual(fnl, ""ftp://myfiles.com/public/doc/cor/10408c.dat"");

    }
</code></pre>

<p>I expect the fnl and the string to match.  But the Expected gives this code instead.</p>

<p>""Expected:. ""</p>

<p>I suspect I am missing something, but since I am still green on unit testing, I have no idea what it is I am missing.</p>

<p>If you have nothing constructive to say, please just pass on any remarks.  I have looked for answers to my question, but nothing I found seemed to relate to my issue enough to be of any help.</p>
",https://stackoverflow.com/questions/57661975/why-is-my-assert-areequal-failing-when-the-debugger-says-they-are-equal,"['c#', 'unit-testing']",47,True,-1,1
How to import a config file so it can be found both by built bundle and module under Jest test?,"<p>I have a Node project written in TypeScript which uses Rollup as a bundler and Jest as unit test framework. It has the following structure (I omitted stuff I believe it's irrelevant for the question):</p>

<pre><code>__tests__
   greeter.test.ts
   config.json
config
   template.config.json
src
   modules
      greeter.ts
   index.ts
jest.config.ts
package.json
tsconfig.json
</code></pre>

<p><strong>src/index.ts:</strong></p>

<pre><code>import { greeter } from './modules/greeter'
console.log(greeter('Bojan'))
</code></pre>

<p><strong>src/modules/greeter.ts:</strong></p>

<pre><code>const config = require('./config.json')
const greeting = config.greeting;
console.log(greeting)

export function greeter(name: string): string {
    return greeting + "", "" + name
}
</code></pre>

<p><strong>__tests__/greeter.test.ts:</strong></p>

<pre><code>import {greeter} from '../src/modules/greeter';

test('greeter uses greeting specifies in the configuration file', () =&gt; {
  expect(greeter('ABC')).toBe('hi, ABC');
});

test('greeter uses the name specified as its runtime argument', () =&gt; {
  expect(greeter('ABC')).toContain('ABC');
});
</code></pre>

<p><strong>jest.config.js:</strong></p>

<pre><code>module.exports = {
    ""verbose"": true,
    ""transform"": {
        ""^.+\\.tsx?$"": ""ts-jest""
    },
    // ""moduleDirectories"": [
    //     ""node_modules"", 
    //     ""&lt;rootDir&gt;/__tests__/""
    // ],
    // ""modulePaths"": [
    //     ""&lt;rootDir&gt;/__tests__/""
    // ]
};
</code></pre>

<p><strong>package.json:</strong></p>

<pre><code>{
  ...
  ""main"": ""index.js"",
  ""scripts"": {
    ""clean"": ""rm -rf ./build/"",
    ""test"": ""jest --verbose --coverage --debug --env node"",
    ""build"": ""npx rollup -c"",
    ""start"": ""node ./build/app.js""
  },
  ...
  ""devDependencies"": {
    ""@types/jest"": ""^24.0.11"",
    ""@types/node"": ""^11.13.0"",
    ""jest"": ""^24.7.1"",
    ""rollup"": ""^1.9.0"",
    ""rollup-plugin-copy"": ""^1.0.0"",
    ""rollup-plugin-typescript"": ""^1.0.1"",
    ""ts-jest"": ""^24.0.2"",
    ""tslib"": ""^1.9.3"",
    ""typescript"": ""^3.4.2""
  },
  ""dependencies"": {}
}
</code></pre>

<p>The idea is that build creates <code>app.js</code> bundle which reads configuration from <code>config.json</code> which should be in the same directory.</p>

<p><strong>config.json:</strong></p>

<pre><code>{
    ""greeting"": ""hi""
} 
</code></pre>

<p>Bundle <code>app.js</code> contains:</p>

<pre><code>var config = require('./config.json');
</code></pre>

<p>...and running the <code>app.js</code> works fine (when <code>config.json</code> is provided) but when I run <code>npm test</code> (or simply <code>npx jest</code>) Jest errors with:</p>

<pre><code> FAIL  __tests__/greeter.test.ts
  ● Test suite failed to run

    Cannot find module './config.json' from 'greeter.ts'

    However, Jest was able to find:
        '../src/modules/greeter.ts'

    You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'json', 'jsx', 'ts', 'tsx', 'node'].

    See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

    &gt; 1 | const config = require('./config.json')
        |                ^
      2 | const greeting = config.greeting;
      3 | console.log(greeting)
      4 | 

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:229:17)
      at Object.&lt;anonymous&gt; (src/modules/greeter.ts:1:16)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.03s
Ran all test suites.
</code></pre>

<p>To rectify this error I'd need to keep <code>config.json</code> (used for unit testing only) next to <code>greeter.ts</code> (in <code>src/modules</code>) but I'd like to keep it in <code>__tests__</code>. I tried to change <em>moduleDirectories</em> and <em>modulePaths</em> in Jest config file to no avail. </p>

<p><strong>Is there a way to make <code>config.json</code> visible to <code>greeter.ts</code> module under Jest test while maintaining its visibility from a bundle <code>app.js</code> in runtime?</strong></p>
",https://stackoverflow.com/questions/55591678/how-to-import-a-config-file-so-it-can-be-found-both-by-built-bundle-and-module-u,"['javascript', 'node.js', 'typescript', 'jestjs', 'ts-jest']",2653,False,0,1
Where is FrameworkUap10 used in VSTest.Console.exe for Win Universal Apps Unit testing,"<p>I've been tasked with adding Unit Testing to our WinUA. The developer said he added a new unit test for UWP project to his solution and I'm to add calling this at build time. He wasn't sure how to do it and pointed me to this article: <a href=""https://learn.microsoft.com/en-us/windows/uwp/packaging/auto-build-package-uwp-apps"" rel=""nofollow noreferrer"">Set up automated builds for your UWP app</a></p>

<p>I've added a ""Visual Studio Test"" step and set the following:</p>

<pre><code>Test Assembly = **\*.UnitTests.build.appxrecipe
Other console options = /framework:FrameworkUap10
</code></pre>

<p>Running it throws the following error:</p>

<blockquote>
  <p>[error]Error: Invalid .Net Framework version:FrameworkUap10. Supported .Net Framework versions are Framework35, Framework40 and Framework45.</p>
</blockquote>

<p>If I remove the invalid framework, no error is thrown but also no tests are run. </p>

<p>I cannot find any information on the /framework:FrameworkUap10 option. Searched MS, here and web and all that comes up is its use in this article... nothing about installing it on the build machine.</p>

<p>How does one install FrameworkUap10?</p>
",https://stackoverflow.com/questions/54203900/where-is-frameworkuap10-used-in-vstest-console-exe-for-win-universal-apps-unit-t,"['testing', 'tfs', 'uwp']",216,True,0,1
In android how to unit test for a class is equal to another class where both classes are wrapped around by a wrapper class,"<p>I am using a wrapper class <strong>GenericApiResponse</strong> for api response:</p>

<pre><code>sealed class GenericApiResponse&lt;T&gt; {

    companion object {
     fun &lt;T&gt; create(error: Throwable): ApiErrorResponse&lt;T&gt; {
        return ApiErrorResponse(error.message ?: ""unknown error"") }

    fun &lt;T&gt; create(response: Response&lt;T&gt;): GenericApiResponse&lt;T&gt; {

           if(response.isSuccessful){
               val body = response.body()
               if (body == null || response.code() == 204) {
               return ApiEmptyResponse()    }
           else if(response.code() == 401){  return ApiErrorResponse(""401 Unauthorized. Token may be invalid."")     }
           else {   return ApiSuccessResponse(body = body)}
        }
        else{
          val msg = response.errorBody()?.string()
          val errorMsg = if (msg.isNullOrEmpty()) {
            response.message()
           } else {
            msg     }
         return ApiErrorResponse(errorMsg ?: ""unknown error"")
        }
    }   }
}


class ApiEmptyResponse&lt;T&gt; : GenericApiResponse&lt;T&gt;()

data class ApiSuccessResponse&lt;T&gt;(val body: T) : GenericApiResponse&lt;T&gt;() {}

data class ApiErrorResponse&lt;T&gt;(val errorMessage: String) : GenericApiResponse&lt;T&gt;()
</code></pre>

<p>and from my ViewModel <strong>MainViewModel</strong> I am calling a function from my <strong>MainRepository</strong> class:</p>

<pre><code> class MainViewModel @Inject constructor(val mainRepository: MainRepository) : ViewModel() {
.....
val source: LiveData&lt;GenericApiResponse&lt;GitResult&gt;&gt; = mainRepository.fetchApiresultFromClient(str_query)  
}
</code></pre>

<p>so in <strong>MainRepository</strong> it calls:</p>

<pre><code>class MainRepository @Inject constructor(val mainApiClient: MainApiClient) {
    ....
    fun fetchApiresultFromClient(strQuery: String)
         : LiveData&lt;GenericApiResponse&lt;GitResult&gt;&gt; {

          var returnedData =    mainApiClient.getApiResultFromServer(strQuery)
          return returnedData
     }
</code></pre>

<p><strong>MainApiClient</strong>:</p>

<pre><code>class MainApiClient  @Inject constructor(val mainApi: MainApi) {
   fun getApiResultFromServer(query :String )
        : LiveData&lt;GenericApiResponse&lt;GitResult&gt;&gt; {

    var apiResult =   mainApi.getAllRepo(query)
       return apiResult
    }
}
</code></pre>

<p><strong>MainApi:</strong> is the interface used for retrofit</p>

<p>Everything is working fine but I am having some problem when trying to implement some unit testing code for the app. I want to assert that when method is called from viewModel then the returned data is: </p>

<ul>
<li>is of type GenericApiResponse</li>
<li>is ApiSuccessResponse</li>
<li>value is same as i defined in test class; which is ApiSuccessResponse(TestUtil.obj_gitresult)</li>
</ul>

<p>So far I have tried:</p>

<pre><code>  @ExtendWith(InstantExecutorExtension::class)
  class MainViewModelTest {

    lateinit var  mainViewModel: MainViewModel

    @Mock
     lateinit var  mainRepository: MainRepository

    @Mock
    lateinit var  mainApiClient: MainApiClient


    @BeforeEach
    fun init()
    {
    MockitoAnnotations.initMocks(this)
    mainViewModel = MainViewModel(mainRepository)
    }

    @Test
    fun setSearchQuery_callsRepositoryMethod_returnSuccess() {

           //arrange
         mainViewModel.liveResult.value = ApiSuccessResponse(TestUtil.obj_gitresult) as GenericApiResponse&lt;GitResult&gt;

        Mockito.`when`(mainApiClient.getApiResultFromServer(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt()))
            .thenReturn(mainViewModel.liveResult)


           //act

        var repo_response = mainRepository.fetchApiresultFromClient(""java"")


        //assert
           // assertTrue(repo_response.value is  GenericApiResponse&lt;GitResult&gt; ) //for asserting return type is of type GenericResponse //--TestResult- java.lang.NullPointerException
           // assertTrue(repo_response.value is  ApiSuccessResponse&lt;GitResult&gt; ) //for asserting return type is of type ApiSuccessResponse //--TestResult- java.lang.NullPointerException
           //  assertEquals(mainViewModel.liveResult.value , repo_response.value ) //for asserting 2 generic types are equal //--TestResult- java.lang.NullPointerException
        }

}
</code></pre>

<p>but all of the 3 cases i used for testing fails and shows result java.lang.NullPointerException.</p>

<p>What am I doing wrong? how to solve it? How do I write the function for testing all of the above mentioned cases?</p>
",https://stackoverflow.com/questions/59473871/in-android-how-to-unit-test-for-a-class-is-equal-to-another-class-where-both-cla,"['android', 'unit-testing', 'kotlin', 'mockito']",635,False,0,0
Enzyme doesn&#39;t reflect the setState changes inside an asynchronous setState callback,"<p>I've trying to figure this out for a whole day and I can't get it to work.</p>

<p>I have a component that updates the state inside <code>componentDidMount</code>, and then in the <code>setState's</code> callback I am updating the state again but the callback runs asynchronously. This is because I make an http request in there whose response I use to update the state. During unit-testing I mock this module so it doesn't reach the network. But Enzyme doesn't reflect the state changes in the async callback. Which makes sense because it's asynchronous, but I haven't found any work around for this.</p>

<p>I've built a minified version of what I'm trying to achieve.</p>

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

<pre class=""lang-js prettyprint-override""><code>class Component extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: 0,
        };
        this._isMounted = false;
    }

    componentDidMount() {
        this._isMounted = true;
        this.setState(state =&gt; {
            const { value } = this.state;
            return {
                ...state,
                value: value + 15,
            };
        }, async () =&gt; {
            try {
                // If you remove this line, it works. 
                await Promise.resolve(15);
                if (this._isMounted) {
                    this.setState(state =&gt; {
                        const { value } = this.state;
                        // If you console.log during testing,
                        // this value is updated correctly, but Enzyme doesn't reflect it.
                        return {
                            ...state,
                            value: value + 15,
                        };
                    });
                }
            } catch(e) {
                // Do nothing...
            }
        });
    }

    componentWillUnmount() {
        this._isMounted = false;
    }

    render() {
        const { value } = this.state;
        return (
            &lt;div&gt;{ value } &lt;/div&gt;
        );
    }
}
</code></pre>

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

<pre class=""lang-js prettyprint-override""><code>describe('Component Enzyme Bug Testing', () =&gt; {
    it('should update value properly', () =&gt; {
        const wrapper = shallow(&lt;Component /&gt;, { disableLifecycleMethods: true });
        wrapper.instance().componentDidMount();
        expect(wrapper.state().value).toEqual(30);
    });
});
</code></pre>

<p>In the test run, <code>state().value</code> is 15, when the expected is 30. Which mean that it registered the first change, but not the second one.</p>
",https://stackoverflow.com/questions/59080404/enzyme-doesnt-reflect-the-setstate-changes-inside-an-asynchronous-setstate-call,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",977,True,0,1
How to handle controller dependecies in PHPUnit?,"<p>I am trying to write the test for my index controller, but I see that I need to pass the dependencies to it to be able to test its behavior, i applied the SOLID principles so I always instance the controllers using a dependency injection container, so I can do the same to instance the controller in the test file.</p>

<p>The question that is burning my head is whether or not that solution is correct because I understand that the point of the Unit Testing is to test the classes independently, and if I use the dependency container I'm are already putting another entity in game .. I mean , if the dependency container fails, then all my controller tests will fail too, without meaning that the controllers are doing their job wrong, then what would be the right solution?</p>

<pre><code>&lt;?php namespace App\Tests\Controller;

use \PHPUnit\Framework\TestCase;

use App\Controller\indexController;
use App\Controller\DependencyInjection;

class indexControllerTest extends TestCase
{
    public function testIndexControllerCheckIfReturnedCorrectHttpResponseCode ()
    {
        $controller = DependencyInjection::getInstance(indexController::class );

        $httpResponse = indexController()-&gt;index();

        return assertEqual( $httpResponse-&gt;getStatusCode(), 200 );
    }
}
</code></pre>
",https://stackoverflow.com/questions/58668111/how-to-handle-controller-dependecies-in-phpunit,"['php', 'unit-testing', 'testing', 'phpunit']",42,False,0,1
How to provide mock values in a FeedResponse for CosmosSDK v3+?,"<p>I'm writing a data access layer for my application and trying to mock out the CosmosDB SDK dependency for unit testing. I am using NUnit with NSubstitute and have come across the issue where I am trying to mock the return values for Container.GetItemQueryIterator. </p>

<p>I have successfully provided a mock feedIterator as a response for that call and a mock feedResponse as a return value for feedIterator.ReadNextAsync, but I cannot figure out how to inject any sort of values into the FeedResponse to test against</p>

<p>The code I'm trying to test looks like this:</p>

<pre class=""lang-cs prettyprint-override""><code>var feedIterator = container.GetItemQueryIterator&lt;T&gt;(queryDefinition);

  while (feedIterator.HasMoreResults){
    result.success = true;

    foreach (var item in await feedIterator.ReadNextAsync()){
      list.Add(item);
    }
  }
</code></pre>

<p>My attempt at mocking out the dependencies like this (Simplified):</p>

<pre class=""lang-cs prettyprint-override""><code>this.mockFeedResponse = Substitute.For&lt;FeedResponse&lt;T&gt;&gt;(this.mockApplicationList);         
this.mockFeedIterator = Substitute.For&lt;FeedIterator&lt;T&gt;&gt;();
this.mockFeedIterator.ReadNextAsync().ReturnsForAnyArgs(Task.FromResult(this.mockFeedResponse));
this.mockFeedIterator.HasMoreResults.Returns(true);
</code></pre>

<p>Looking at the AzureCosmosDB SDK documentation, there seems to be a  FeedResponse constructor for mocking that takes an IEnumerable as a parameter, but NSubstitute complains telling me it can't find this constructor when I attempt to pass in a list to use. Is there an alternative that I can feed some IEnumerable as a FeedResponse? Where am I going wrong?</p>
",https://stackoverflow.com/questions/58155907/how-to-provide-mock-values-in-a-feedresponse-for-cosmossdk-v3,"['c#', 'azure-cosmosdb', 'nsubstitute']",5280,True,8,3
How to load/retrieve In Memory Database (H2 Database) using karate Framework as a prerequisite step before Microservice REST API is called,"<p>Problem Statement :</p>
<ol>
<li>Microservices retrieves data from DB2 Database as part of Production</li>
<li>Different Set of data feasible in Different Environment</li>
<li>As part of it, it needs to ensure Retrieval logic is accurate</li>
<li>java Code Converts DB2 Data into JSON structure</li>
<li>Microservices logic doesnt control creating Database,its only limited to retrieval</li>
<li>As part of above requirement , In memory DB (H2)  is being discussed for Testing where data is loaded using DDL/DML and Expected JSON response to be generated manually as part of unit Testing</li>
</ol>
<p>Test Validation Objective : test &quot;Retrial Logic&quot; so that irrespective of Environment, same values are retrieved .When Microservices is invoked, internally Test Harness URL calls to In Memory Database to retrieve Actual response</p>
<p>Test Automation Framework in Place :</p>
<ol>
<li>Karate Framework</li>
</ol>
<p>Test Automation Approach:</p>
<ol>
<li>Load data into in Memory Database using DDL/DML (file) as part of Test Execution</li>
<li>Invoke Microservice Request using karate</li>
<li>Compare Actual Response against Expected JSON response captured in Step</li>
<li>Delete the Database as part of Cleanup</li>
</ol>
<p>Note - As it would be very tedious to write same  Test Automation logic which helps to convert Data into DB ( In Memory ) to JSON (Expected Response), Expected JSON response to be captured as base expected response</p>
<p>Its Expected to have Test Automation Maintenance to Update DDL/DML or expected JSON is there is any change in actual Retrieval Logic.</p>
<p>Refernce for In memory DB Testing :</p>
<p><a href=""https://www.baeldung.com/spring-jpa-test-in-memory-database"" rel=""nofollow noreferrer"">https://www.baeldung.com/spring-jpa-test-in-memory-database</a></p>
<p>#xyz-service-response.json is generated as part of unit testing while In memory DB is Created
@TestRetrivalLogicusingInMemoryRequirnments
Feature: demo reading files and using in a test</p>
<p>Background:</p>
<pre><code>* url 'http://localhost:8080/api/sample/v1.0/'
    * header Accept = 'application/json'
    * configure logPrettyResponse = true
    * configure ssl = true 
</code></pre>
<p>Scenario: using json as a string
Load data into In Memory Database ----&gt;&gt; This is expected Gherkin Statement. Need to understand how we can do in Karate</p>
<pre><code>Given path 'getDerivedRules'
    And request { &quot;pricingVerIds&quot;: [{ &quot;AncestorVersionId&quot;: 123456123, &quot;kidsVersionIds&quot;: [3432432,345324324] }],&quot;executionFlow&quot;: &quot;Cheque&quot;,&quot;PriceType&quot;: &quot;dollarinINYIELD&quot;, &quot;validationLevel&quot;: &quot;Aggrement_LEVEL&quot;}
    When  method POST 
    Then status 200 
    Then match $ == read('xyz-service-response.json')
</code></pre>
<p>Challenge and Query  :</p>
<p>As karate Gherkin statement doesn't have Java Glue Code , and it has own DSL, can this be achieved using Karate or we need to stick to RESTAssured or similar Framework</p>
<p>Request for Help :</p>
<p>Any suggestion or code snippet to handle above would be helpful</p>
",https://stackoverflow.com/questions/56498777/how-to-load-retrieve-in-memory-database-h2-database-using-karate-framework-as,"['microservices', 'karate', 'in-memory-database']",956,False,-1,1
Can we use CMake foreach in template source file?,"<p>For unit testing my functions, i have auto-generated the name, like it:</p>

<p>test_implode
test_range</p>

<p>into a CMake variable.</p>

<p>I want to call all automatically in C.
I also used config file (.in.c) in CMake </p>

<pre><code>set(CONFIG configuration)
configure_file(${CONFIG}.in.c ${CONFIG}.c)
set(CONFIG_SRC ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG}.c)
</code></pre>

<p>But the name of the function are just in a List in CMake, the C syntax is not valid. I could generate a variable in CMake with appropriate syntax, but generating output in config file would let the CMake source file clean and could be possibly very powerful.</p>

<p>Concretly, what I would like to do is that (imaginary syntax):</p>

<pre><code>#include ""tests.h""

void all_tests() {

    void(*tests)()[] = {
    @FOREACH(FUNC FUNCTIONS)@
        test_@FUNC@,
    @ENDFOREACH()@
        NULL
    };

    void(*test_function)() = tests[0];

    while(test_function) {
        test_function();
        test_function++;
    }
}
</code></pre>

<p>Similarly to blade or php.
Can I use CMake as a scripting language (or a foreach) or is it mandatory to put this in the CMake source file and store it into a variable ?</p>

<p>What I currently do, which is acceptable, works. But I'm learning and I would like to know if it's still possible or not</p>

<pre><code>foreach(PHP_FUNCTION ${PHP_FUNCTIONS})
  list(APPEND GENERATED_C_CODE_RUN_TEST ""\n\ttest_${PHP_FUNCTION}()"")
endforeach()

set(GENERATED_C_CODE_RUN_TEST ""${GENERATED_C_CODE_RUN_TEST};"")
set(CONFIG configuration)
configure_file(${CONFIG}.in.c ${CONFIG}.c)
set(CONFIG_SRC ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG}.c)
add_executable(...);
</code></pre>

<pre><code>#include ""tests.h""

void all_tests() {

    @GENERATED_C_CODE_RUN_TEST@
}
</code></pre>
",https://stackoverflow.com/questions/57829274/can-we-use-cmake-foreach-in-template-source-file,"['c', 'cmake']",758,True,3,1
Async method blocking on unawaited task,"<p>In my current project, I have a piece of code that, after simplifying it down to where I'm having issues, looks something like this:</p>

<pre><code>private async Task RunAsync(CancellationToken cancel)
{
    bool finished = false;
    while (!cancel.IsCancellationRequested &amp;&amp; !finished)
        finished = await FakeTask();
}

private Task&lt;bool&gt; FakeTask()
{
    return Task.FromResult(false);
}
</code></pre>

<p>If I use this code without awaiting, I end up blocking anyway:</p>

<pre><code>// example 1
var task = RunAsync(cancel); // Code blocks here...
... // Other code that could run while RunAsync is doing its thing, but is forced to wait
await task;

// example 2
var task = RunAsync(cancelSource.Token); // Code blocks here...
cancelSource.Cancel(); // Never called
</code></pre>

<p>In the actual project, I'm not actually using FakeTask, and there usually will be some Task.Delay I'm awaiting in there, so the code most of the time doesn't actually block, or only for a limited amount of iterations.</p>

<p>In unit testing, however, I'm using a mock object that does pretty much do what FakeTask does, so when I want to see if RunAsync responds to its CancellationToken getting cancelled the way I expect it to, I'm stuck.</p>

<p>I have found I can fix this issue by adding for example <code>await Task.Delay(1)</code> at the top of RunAsync, to force it to truly run asynchronous, but this feels a bit hacky. Are there better alternatives?</p>
",https://stackoverflow.com/questions/55243987/async-method-blocking-on-unawaited-task,"['c#', '.net', 'asynchronous', 'async-await']",1768,True,3,4
How to test small program with user input in Haskell,"<p>Im taking a software testing class. And we were allowed to choose what language to write our code and tests in. And I choose Haskell. I know, maybe not the best way to learn testing (= but...</p>
<p>The unit-testing and coding has been working great!</p>
<p>But I am also required to use mocking to get a higher grade.</p>
<p>My problem is that I don't know very much Haskell (like Monads and stuff).</p>
<p>I have written and tested Calculator. And now I want to test my main. My instructor used Mockito for Java to check that the program had the correct flow.</p>
<p>Is it possible to test that my if-statements are correct?
I have tried reading up on testing IO actions through Monads, but I don't quite understand it.
Maybe I should just learn more about Monads before trying to solve this?</p>
<p>Any help or reading suggestions are very much appreciated!</p>
<pre><code>import Calculator

main :: IO ()
main = do
        putStrLn(&quot;What should I calculate? ex 3*(2+2)  | quit to exit&quot; )
        line &lt;- getLine
        if line /= &quot;quit&quot;
        then do if correctInput line
                then do putStrLn( show $ calculate line) 
                        main
                else do putStrLn &quot;Wrong input&quot; 
                        main
        else putStrLn &quot;goodbye&quot;
</code></pre>
",https://stackoverflow.com/questions/58750508/how-to-test-small-program-with-user-input-in-haskell,"['haskell', 'testing']",785,True,3,2
How to load your classes in Jest?,"<p>So this question seems really stupid, but I've been searching and searching, and have not found an answer.</p>

<p>I'm trying out the Jest framework for unit testing my custom javascript project, which is not using React or any other framework.  My project structure currently looks like this:</p>

<ul>
<li>project

<ul>
<li>js

<ul>
<li>main.js &lt;-- all my classes are in here, es6 style, if that matters</li>
</ul></li>
<li>--tests--

<ul>
<li>card.test.js &lt;-- tests are in here</li>
</ul></li>
</ul></li>
</ul>

<p>Inside main.js there is class Card defined.  I doubt there are any issues with the file, as I've run it perfectly fine in the browser.</p>

<pre><code>""use strict"";

class Card 
{
  ...
}
</code></pre>

<p>The one test I've written so far, just to see if it works is:</p>

<pre><code>require('../js/main.js');

test(""stuff"", () =&gt; {
    let card = new Card(1, 1);
});
</code></pre>

<p>When I try to run the test:</p>

<p><code>yarn test</code></p>

<p>But all I'm getting is:</p>

<pre><code>    ReferenceError: Card is not defined

      2 |
      3 | test(""stuff"", () =&gt; {
    &gt; 4 |       let card = new Card(1, 1);
        |                  ^
      5 | });

      at Object.&lt;anonymous&gt;.test (__tests__/card.test.js:4:13)
</code></pre>

<p>It seems like main.js is getting loaded, because if I add a console.log() in it, that gets output when I run the test.  So why is it complaining that Card is not defined?</p>
",https://stackoverflow.com/questions/54756853/how-to-load-your-classes-in-jest,"['javascript', 'ecmascript-6', 'jestjs', 'yarnpkg']",1539,True,3,2
Unit testing middleware in Laravel mocking route with parameter,"<p>I am developing a Laravel application. I am now doing Unit testing on the Middleware. I am having a problem with mocking the route.</p>

<p>This is my middleware class</p>

<pre><code>class CheckIfDepartmentIdPresent
{
    public function handle($request, Closure $next)
    {
        if (! $request-&gt;route()-&gt;hasParameter('department')) {
            return abort(Response::HTTP_FORBIDDEN);
        }

        //check if the id is valid against the database, 
        //if it is valid then return $next($request)

        return abort(Response::HTTP_FORBIDDEN);
    }
}
</code></pre>

<p>I named the middleware as department.present.</p>

<p>In the unit test I write my first test like this.</p>

<pre><code>public function test_request_fail_if_id_parameter_is_missing_in_route()
{
    Route::middleware('department.present')
            -&gt;any('/department/test', function () {
                return 'OK';
            });
    $response = $this-&gt;get('/department/test');
    $this-&gt;assertEquals(Response::HTTP_FORBIDDEN, $response-&gt;getStatusCode());
}
</code></pre>

<p>The above test method is working fine. It is working as expected. Now I want to mock the route. In the middleware, I am getting the route parameter like this.</p>

<pre><code>$request-&gt;route('department');
</code></pre>

<p>So that I need to mock a route with parameter. If I mocked like this.</p>

<pre><code>$path = ""/department/{$department-&gt;id}"";
        Route::middleware('department.present')
            -&gt;any($path, function () {
                return 'OK';
            });
</code></pre>

<p>My middleware still not be able to fetch the department id using $request->route('department'). So I need to mock a route with a placeholder for the parameter and then the middleware will be able to fetch the route parameter value by name. How can I fake/mock that? Is there a way to do that?</p>
",https://stackoverflow.com/questions/54307167/unit-testing-middleware-in-laravel-mocking-route-with-parameter,"['laravel', 'unit-testing', 'laravel-routing', 'laravel-middleware']",521,False,3,0
Code stuck when querying CosmosDB in java integration test,"<p>I'm writing integration test for an API.
In DAO class, when I try to fetch data from Cosmos DB using AsyncDocumentClient instance queryDocuments method, program has stuck indefinitely.</p>

<p>This is how my function call looks like:</p>

<pre><code>Iterator&lt; FeedResponse&lt;Document&gt;&gt; getDataFromCosmos = asyncDocumentClientInstance.queryDocuments(collectionLink, querySpec, feedOptions).toBlocking().getIterator();
</code></pre>

<p><strong>This is happening only when I run the test cases (in test mode).
But the code and API is working fine when I run in normal mode.</strong></p>

<p>This is how my test class looks like:
(I'm doing integration testing, not unit testing)</p>

<pre><code>import org.junit.runner.RunWith;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)

public class ApiTest extends TestngInitializer

{

@Autowired

ServiceImpl serviceImpl;

    @Test
    public void apiTest()
    {
    RequestClass requestObject = new requestObject();
    // hardcoding requestObject data variables using setters

    ResponseClass response = serviceImpl.apiMethod(requestObject,HttpHeaders);

    //Assertions on response

    }

}
</code></pre>

<p>My TestngInitializer class looks like (Setting path to get all spring beans)</p>

<pre><code>@ContextConfiguration(locations = {""classpath:/META-INF/biz-context.xml"",""classpath:/META-INF/service-context.xml""})

public class TestngInitializer
{

}
</code></pre>

<p>When I try to debug line by line, when control has reached <code>BlockingObservable.java</code>, control is waiting indefinitely for some thread to finish which is not the case when I run the code in normal mode.</p>

<pre><code>BlockingUtils.awaitForComplete(latch, subscription);
</code></pre>

<p>If anyone can help me on this, that would be great.</p>

<p>Here is the small reproducible code I tried as well:</p>

<pre><code>@Test
public void testDBLocally()
{
    AsyncDocumentClient asyncDocumentClient = readDocumentClient(); //calling below function
    FeedOptions feedOptions = new FeedOptions();
    feedOptions.setEnableCrossPartitionQuery(true);
    String collectionLink = ""/dbs/link_to_collection"";
    SqlQuerySpec querySpec = new SqlQuerySpec(""select * from some_document c "");

    //here I tried two approaches
    //first approach using iterator
    Iterator&lt;FeedResponse&lt;Document&gt;&gt; iterator = asyncDocumentClient.queryDocuments(collectionLink,querySpec,feedOptions).toBlocking().getIterator();
    while(iterator.hasNext())
    {
        //control stuck indefinitely at iterator.hasNext()
        //control never reached inside while loop
    }

    //second approach using last()
     FeedResponse&lt;Document&gt; response = capsReadDocumentClient.queryDocuments(collectionLink, querySpec, feedOptions).toBlocking().last(); //control stuck here
     documentList = response.getResults(); //control never reached here

}

public AsyncDocumentClient readDocumentClient() {
    String HOST = ""https://azure-cosmosdb.documents.azure.com:443/"";
    String MASTER_KEY = ""SOME_MASTER_KEY""; 
    return new AsyncDocumentClient.Builder()
            .withServiceEndpoint(HOST)
            .withMasterKeyOrResourceToken(MASTER_KEY)
            .withConnectionPolicy(ConnectionPolicy.GetDefault())
            .withConsistencyLevel(ConsistencyLevel.Session)
            .build();
}
</code></pre>
",https://stackoverflow.com/questions/58959062/code-stuck-when-querying-cosmosdb-in-java-integration-test,"['java', 'spring', 'rx-java', 'integration-testing', 'azure-cosmosdb']",615,False,3,0
Why is defining chunked objects (for lack of a better term) in a function valid JavaScript?,"<p>I recently read <a href=""https://medium.com/javascript-scene/unit-testing-react-components-aeda9a44aae2"" rel=""nofollow noreferrer"">this article</a> on unit testing React.</p>

<p>In it the author uses syntax like this:</p>

<pre><code>describe('ClickCounter component', async assert =&gt; {
  const createCounter = clickCount =&gt;
    render(&lt;ClickCounter clicks={ clickCount } /&gt;)
  ;
  {
    const count = 3;
    const $ = createCounter(count);
    assert({
      given: 'a click count',
      should: 'render the correct number of clicks.',
      actual: parseInt($('.clicks-count').html().trim(), 10),
      expected: count
    });
  }
  {
    const count = 5;
    const $ = createCounter(count);
    assert({
      given: 'a click count',
      should: 'render the correct number of clicks.',
      actual: parseInt($('.clicks-count').html().trim(), 10),
      expected: count
    });
  }
});
</code></pre>

<p>The part that I'm confused about is the content of the callback function that has <code>assert</code> as its argument.</p>

<p>In it he just chains one object after another. He basically does this:</p>

<pre><code>const myFunc = () =&gt; {
  {
    // object that confuses me, with promise (`assert`) which resolves
  }
  {
    // another object
  }
}
</code></pre>

<p>And somehow the code in these objects gets executed. I have never seen code like this in any course I watched or book I read on JavaScript. I have also never experienced such syntax used in any other library or framework. But, I tested it and the code works, the tests all run.</p>

<p>Notice how he also never returns anything. And even though he uses the keyword <code>async</code> he doesn't <code>await</code> anything.</p>

<p>Why are these chunked objects valid JavaScript? How does it work? And is there a definitive nomenclature for this? I have looked on MDN (and Google) and didn't find anything.</p>
",https://stackoverflow.com/questions/55645678/why-is-defining-chunked-objects-for-lack-of-a-better-term-in-a-function-valid,"['javascript', 'async-await', 'es6-promise']",29,True,2,1
Jest/node.js: customise console.log output?,"<p>I have some <code>AWS</code> lambdas written in <code>typescript</code> that I'm unit testing with <code>jest</code>.</p>

<p>The tests are working fine, but the output from <code>console.log</code> lines in the code verbose and difficult to scan.</p>

<p>When a test is run, in my console I see something like:</p>

<pre><code>  console.log src/main/ts/worker/receivemail/ReceiveMailWorker.ts:24
    ctor()

  console.log src/main/ts/shared/LambdaUtil.ts:12
    initConfig() doing initialisation

  ...
</code></pre>

<p>Jest (or something else?) is writing three lines of output for every call to <code>console.log()</code>.</p>

<p>When I'd rather see something like: </p>

<pre><code>ctor()
initConfig() doing initialisation
...
</code></pre>

<p>I wouldn't mind seeing some timestamps too.</p>

<p>Is there any way to configure / control this logging output?</p>

<p>Things to note: </p>

<ul>
<li>I don't want to change the actual code - I especially don't want to add a fully blown logging library or anything like that.</li>
<li>I still want to see the console logging (i.e. <code>--silent</code> is definitely not what I want).</li>
<li>I'm not trying to <em>test</em> the console logging, I just want to make it easier to read.</li>
<li>I tried <code>--verbose=false</code> - but it didn't seem to make any difference.</li>
</ul>
",https://stackoverflow.com/questions/58785221/jest-node-js-customise-console-log-output,"['javascript', 'node.js', 'jestjs', 'ts-jest']",122,False,2,0
Modern CMake project for header-only library with unit test,"<p>I am developing a header-only library that uses C++17 features. The project structure is like this:</p>

<pre><code> - project
   - README.md
   - LICENSE.md
   - CMakeLists.txt
   - include
     - proj_library.h
   - test
     - unittest
       - CMakeLists.txt
       - main.cpp
       - test.cpp
</code></pre>

<p>The unit tests use <a href=""https://github.com/onqtam/doctest"" rel=""nofollow noreferrer"">doctest</a> unit testing framework, which I currently do not include in the project.</p>

<p>How should my main CMakeLists.txt file and the unit test CMakeLists.txt files look like to:</p>

<ul>
<li>make clients use C++17 (or later) language standard as the library uses <code>std::optional</code> and the like</li>
<li>enable generating nice IDE project (I am using Visual Studio 2017)</li>
<li>enable the equivalent of <code>-Wall</code> <code>-Wextra</code> <code>-pedantic</code> options in as compiler-agnostic way as possible (I plan compilation using at least GCC, Clang, and VS 2017)</li>
</ul>

<p>So far I have this, which I based on several open-source projects and articles:</p>

<p>Main CMakeLists.txt:</p>

<pre><code>cmake_minimum_required(VERSION 3.15)

project(""lib-headeronly"")

add_library(${PROJECT_NAME} INTERFACE)

target_include_directories(${PROJECT_NAME} INTERFACE include/)

target_compile_features(${PROJECT_NAME} INTERFACE cxx_std_17)

enable_testing()
add_subdirectory(test/unittest)
</code></pre>

<p>Unit test CMakeLists.txt:</p>

<pre><code>cmake_minimum_required(VERSION 3.15)

include(CTest)

add_executable(unittest)
target_sources(unittest
    PRIVATE
    main.cpp
    test.cpp)

target_include_directories(unittest
    PRIVATE $&lt;BUILD_INTERFACE:${PROJECT_SOURCE_DIR}&gt;/include
    $&lt;BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}&gt;)

target_compile_features(unittest PRIVATE cxx_std_17)

add_test(NAME unittest COMMAND unittest)

</code></pre>

<p>Currently, while the library is under development, I do not need fancy targets for installation and the like. I just need facilities for building unit tests on several platforms.</p>

<p>Any suggestions?</p>
",https://stackoverflow.com/questions/57919183/modern-cmake-project-for-header-only-library-with-unit-test,"['c++', 'unit-testing', 'cmake']",1288,False,2,0
Mocking ViewContext&#39;s StreamWriter to output ViewEngineResults.View.RenderAsync result?,"<p>I inherited an application with little-to-no unit testing and I'm trying to mock out a service class. The class takes in a viewModel as a string and a model as an object then returns the view as a string. It looks like the developer implemented something similar to <a href=""https://stackoverflow.com/a/40932984/3407541"">this</a>.</p>

<pre class=""lang-cs prettyprint-override""><code>using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using FluidMvcViewEngine;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace Some.Api.Services
{
    public class ViewRenderService
    {
        private readonly IActionContextAccessor _context;
        private readonly IFluidViewEngine _fluidViewEngine;
        private readonly ITempDataProvider _tempDataProvider;

        public ViewRenderService(IActionContextAccessor context, IFluidViewEngine razorViewEngine, ITempDataProvider tempDataProvider)
        {
            _context = context;
            _fluidViewEngine = razorViewEngine;
            _tempDataProvider = tempDataProvider;
        }

        public async Task&lt;string&gt; RenderToStringAsync(string viewName, object model, CancellationToken ct = default(CancellationToken))
        {
            var actionContext = _context.ActionContext;

            using (var writer = new StringWriter())
            {
                var viewResult = _fluidViewEngine.GetView(viewName, viewName, false);

                if (viewResult.View == null)
                {
                    throw new ArgumentNullException(""exception message goes here"");
                }

                var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                {
                    Model = model
                };

                var viewContext = new ViewContext(
                    actionContext,
                    viewResult.View,
                    viewDictionary,
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    writer,
                    new HtmlHelperOptions()
                );

                await viewResult.View.RenderAsync(viewContext);
                return writer.ToString();
            }
        }
    }
}
</code></pre>

<p>The code works, but there aren't any tests for the service. I was able to mock everything with nSubstitute and it runs through with no exceptions, but I really don't understand what <code>writer.ToString()</code> is supposed to be writing out or how to mock it. </p>

<p>I can see that <code>await viewResult.View.RenderAsync(viewContext);</code> is rendering the viewContext, and that the ViewContext is taking in an instance of the StringWriter. However, I'm not able to step into the ViewEngineResult.View.RenderAsync method to see how the StringWriter works.</p>

<pre class=""lang-cs prettyprint-override""><code>using System.Threading.Tasks;
using FluentAssertions;
using FluidMvcViewEngine;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using NSubstitute;
using Xunit;

namespace Some.Tests.UnitTests.Services
{
    public class ViewRenderServiceTest
    {
        private readonly IActionContextAccessor _context;
        private readonly IFluidViewEngine _fluidViewEngine;
        private readonly ViewRenderService _service;
        private readonly ITempDataProvider _tempDataProvider;
        private readonly IView _view;
        private readonly IViewEngine _viewEngine;

        public ViewRenderServiceTest()
        {
            _context = Substitute.For&lt;IActionContextAccessor&gt;();
            _fluidViewEngine = Substitute.For&lt;IFluidViewEngine&gt;();   
            _tempDataProvider = Substitute.For&lt;ITempDataProvider&gt;(); 
            _view = Substitute.For&lt;IView&gt;();
            _viewEngine = Substitute.For&lt;IViewEngine&gt;();   

            _service = new ViewRenderService(_context, _fluidViewEngine, _tempDataProvider);         
        }

        [Fact]
        public async Task RenderToStringAsyncTest()
        {
            // Arrange
            var stringToRender = ""RENDERED"";
            var someObject = new { Id = default(int), Name = ""Bob"" };

            // Mock IActionContextAccessor 
            MockIActionContextAccessor();

            // Mock IFluidViewEngine
            MockIFluidViewEngine(stringToRender);

            // Act
            var test = await _service.RenderToStringAsync(stringToRender, someObject);

            // Assert
            test.Should().Be(stringToRender);
        }

        private void MockIActionContextAccessor()
        {
            var httpContext = Substitute.For&lt;HttpContext&gt;();
            var routeData = Substitute.For&lt;RouteData&gt;();
            var actionDescriptor = Substitute.For&lt;ActionDescriptor&gt;();
            var modelState = Substitute.For&lt;ModelStateDictionary&gt;();

            _context.ActionContext.Returns(new ActionContext(httpContext, routeData, actionDescriptor, modelState));
        }

        private void MockIFluidViewEngine(string stringToRender)
        {
            _view
                .RenderAsync(Arg.Any&lt;ViewContext&gt;())
                .Returns(Task.FromResult(stringToRender));

            _view
                .Path
                .Returns(string.Empty);

            _viewEngine
                .GetView(Arg.Any&lt;string&gt;(), Arg.Any&lt;string&gt;(), Arg.Any&lt;bool&gt;())
                .Returns(ViewEngineResult.Found(stringToRender, _view));


            _fluidViewEngine
                .GetView(Arg.Any&lt;string&gt;(), Arg.Any&lt;string&gt;(), Arg.Any&lt;bool&gt;())
                .Returns(ViewEngineResult.Found(stringToRender, _view));
        }
    }
}
</code></pre>

<p>Once everything was wired up I was expecting to see <code>RENDERED</code> but all I get is an empty string.</p>
",https://stackoverflow.com/questions/56353942/mocking-viewcontexts-streamwriter-to-output-viewengineresults-view-renderasync,"['c#', 'asp.net-core', 'asp.net-core-mvc', 'asp.net-core-2.2', 'nsubstitute']",516,True,2,1
Jenkins kubernetes-plugin Parallelise declarative Jenkinsfile,"<p>Using kubernetes-plugin Parallelise declarative Jenkinsfile how do you run stages in parallel, when each stage uses the same container? (eg: sonar_qube analysis and unit testing both run on a maven container. </p>

<p>I have tried the following in Jenkinsfile: </p>

<pre><code>def label = ""my-build-${UUID.randomUUID().toString()}""

podTemplate(label: label, containers: [
  containerTemplate(name: 'maven', image: 'maven:3.5.3-jdk-8-alpine', command: 'cat', ttyEnabled: true),
  containerTemplate(name: 'maven2', image: 'maven:3.5.3-jdk-8-alpine', command: 'cat', ttyEnabled: true),
],
volumes: [
  hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock'),
  hostPathVolume(mountPath: '/root/.m2/repository', hostPath: '/root/.m2'),
  hostPathVolume(mountPath: '/tmp', hostPath: '/tmp')
]) {

node(label) {
    def myRepo = checkout scm
    def gitCommit = myRepo.GIT_COMMIT
    def gitBranch = myRepo.GIT_BRANCH

    def didFail = false
    def throwable = null

    try {        
        stage('Tests In Parallel') {
            parallel StaticCodeAnalysis: {
                container('maven'){
                    withSonarQubeEnv('sonarqube-cluster') {
                      // requires SonarQube Scanner for Maven 3.2+
                      sh "" mvn help:evaluate -Dexpression=settings.localRepository""

                      sh ""mvn clean""
                      sh ""mvn compiler:help jar:help resources:help surefire:help clean:help install:help deploy:help site:help dependency:help javadoc:help spring-boot:help org.jacoco:jacoco-maven-plugin:prepare-agent""
                      sh ""mvn org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=$SONAR_HOST_URL -Dsonar.login=$SONAR_AUTH_TOKEN -Dsonar.exclusions=srcgen/**/* -Dmaven.test.skip=true""
                    }
                }
            }, unitTests: {
                container('maven2') {
                  sh ""mvn clean package""

                  junit allowEmptyResults: true, testResults: '**/surefire-reports/*.xml'
                }
            },
            failFast: true
        }       
    } catch (e) {
        didFail = true
        throwable = e
    } finally {
        sh ""rm -rf /tmp/${label}""
    }
    if (didFail) {
        echo ""Something went wrong.""
        error throwable
    }        

  }
}
</code></pre>

<p>All seems to work, and on the blue ocean UI I can see the two stages running correctly at the same time. However when one of the stages in parralell stage finishes, the other fails with 'java.lang.NoClassDefFoundError's' for classes that have definitely already been used and where there as stage was running. </p>

<p>It almost looks like all slaves that a spun up use the same workspace directoy ie: /home/jenkins/workspace/job_name/</p>

<p>The maven commands create folder
- /home/jenkins/workspace/job_name/target/classes
- but when you see the failing, its ask if the container that was been used lots all its content from the classes folder. </p>
",https://stackoverflow.com/questions/55908216/jenkins-kubernetes-plugin-parallelise-declarative-jenkinsfile,"['jenkins', 'parallel-processing', 'jenkins-kubernetes', 'kubernetes-jenkins-plugin']",519,False,1,0
How to unit test HttpClient retry logic using junit,"<p>I am working on apache http client to consume services and I have a requirement to retry the requests based on timeout and based on response code.
For this I have implemented the code as below. How can I write the junit tests for retry logic for both timeout and response code scenarios. I would like to write a unit test in such a way that when I send any post/get request if it returns 429 error code response or any TimeOutException I should make sure retry logic is executed properly. I did not get an idea on how to write unit test for retry logic.
By googling I found the below link but it doesn't helpful to me.</p>

<p><a href=""https://stackoverflow.com/questions/39579202/unit-testing-defaulthttprequestretryhandler"">Unit testing DefaultHttpRequestRetryHandler</a></p>

<p>I am using junit,Mockito to write unit tests and PowerMock to mock static methods.</p>

<pre><code>public class GetClient {

private static CloseableHttpClient httpclient;

public static CloseableHttpClient getInstance() {

        try {
            HttpClientBuilder builder = HttpClients.custom().setMaxConnTotal(3)
                    .setMaxConnPerRoute(3);
            builder.setRetryHandler(retryHandler());
            builder.setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
            int waitPeriod = 200;

            @Override
            public boolean retryRequest(final HttpResponse response, final int executionCount,
                final HttpContext context) {

                int statusCode = response.getStatusLine().getStatusCode();
                return (((statusCode == 429) || (statusCode &gt;= 300 &amp;&amp; statusCode &lt;= 399))
                            &amp;&amp; (executionCount &lt; 3));
            }

            @Override
            public long getRetryInterval() {
                return waitPeriod;
            }
            });            

            httpclient = builder.build();

        } catch (Exception e) {
            //handle exception
        }
        return httpclient;
    }

     private static HttpRequestRetryHandler retryHandler() {
        return (exception, executionCount, context) -&gt; {
            if (executionCount &gt; maxRetries) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof InterruptedIOException) {                
                // Timeout
                return true;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {
                // Connection refused
                return false;
            }
            if (exception instanceof SSLException) {
                // SSL handshake exception
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        };
    }
}

public CloseableHttpResponse uploadFile(){    
        CloseableHttpClient httpClient = GetClient.getInstance();
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(post);
        } catch (Exception ex) {
            //handle exception
        }
        return response;    
   }
</code></pre>

<p>Can anyone help me on this.</p>
",https://stackoverflow.com/questions/57327029/how-to-unit-test-httpclient-retry-logic-using-junit,"['java', 'junit', 'mockito', 'apache-httpclient-4.x', 'powermock']",3635,True,1,1
$root gets overwritten by shallowMount wrapper $root,"<p>I have a problem with Unit testing a Vue component.</p>

<p>I need to override the <code>$root</code> thats created by the <code>shallowMount</code> function.</p>

<p>I have a plugin component which is assigning its <code>$root</code>s data to its local data:</p>

<pre><code>data() {
  return {
    noStoreNotifications: [],
    isHistoryOpen: false,
    pluginSettingWithoutStore: this.$root._pluginSetting.withoutStore,
    pluginSettingShowNotification: this.$root._pluginSetting.showHistory,
    pluginSettingMaxHistoryLength: this.$root._pluginSetting.maxHistoryLength,
    pluginSettingReverseHistory: this.$root._pluginSetting.reverseHistory,
  };
},
</code></pre>

<p>Since this plugin is used in multiple repositories, with different components and use cases, I need to be able to access its wrapper to get some data from it.</p>

<p>The plugin works fine but the unit test for it is not working as I would expect, but it makes sense why its not working.</p>

<p>As I wrote, I need to access the components wrapper object through <code>$root</code>. 
And normally I would use:</p>

<pre><code>cosnt data = {
  mocks: {
    $root: {
      _eventHub: new Vue(),
      _notificationContainer: null,
      _pluginSetting: {},
    },
  },
}
</code></pre>

<p>within the initial mount of the component</p>

<pre><code>const wrapper = shallowMount(Notifications, data);
</code></pre>

<p>However this doesnt work, because the <code>shallowMount</code> method creates a wrapper with its own unique <code>$root</code>, which overrides mine.</p>

<p>Is there a way to override its <code>$root</code> to my specification before the component gets created?</p>
",https://stackoverflow.com/questions/58286720/root-gets-overwritten-by-shallowmount-wrapper-root,"['javascript', 'unit-testing', 'vue.js']",19,False,1,0
How to set up unit testing when developing Directus extensions?,"<p>What is a good project setup for developing Directus extensions such as hooks and custom endpoint, while using unit testing with PHPUnit?</p>

<p>Directus extensions live under the same codebase as the core project itself. That's a problem for having the extension code under version control. So what I have now is a symlink from <code>directus/public/extensions/custom/hooks</code> to a directory outside. In there, I have the usual <code>src/</code> and <code>tests/</code>, and I've done <code>composer install --dev phpunit ^8</code> and I PHPUnit is in place, and is loading my own classes. Now, how do I bring Directus in here, because Directus is not, AFAIK, on Composer. Maybe make a <code>lib/</code>, checkout Directus from GitHub in there, and have it included in <code>autoload/classmap</code> in composer.json?</p>

<p>Or would it alternatively be better to fork the whole Directus, and use a close of the whole Directus repo for extension dev? How to develop more than one extension?</p>

<p>Or something else?</p>
",https://stackoverflow.com/questions/58476595/how-to-set-up-unit-testing-when-developing-directus-extensions,"['php', 'unit-testing', 'phpunit', 'directus']",414,False,1,1
"Gradle tests fail locally, but succeed on CI servers","<p>I have a Gradle Java project set up with JUnit unit testing. There are some tests that are supposed to fail. They do so on my machine, but it succeeds without errors on CI servers.</p>

<p>The natural first assumption is that something must be wrong with the CI server configuration. However, after not being able to get it to fail on CodeShip, I tried it with Travis and got the same result. In CodeShip, the peculiar thing is that the log told me that it simply did not find any tests (so of course there were no failed tests).</p>

<p>The test files are on the git repo (not ignored) and all scripts, be it Gradle or CI server configuration, are very simple. So I currently have no idea what is the issue here. For example, this is the .travis.yml:</p>

<pre><code>language: java
jdk:
  - oraclejdk8
</code></pre>

<p>And this is the <code>build.gradle</code>:</p>

<pre><code>plugins {
    id 'java'
}

group 'net.roughdesign.ajiwa'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1'
}

test {
    useJUnitPlatform()
}
</code></pre>

<p>What could possibly cause this behaviour?</p>
",https://stackoverflow.com/questions/56715387/gradle-tests-fail-locally-but-succeed-on-ci-servers,"['java', 'gradle', 'junit', 'continuous-integration']",1079,True,1,1
Vue + Jest global config carrying over into spec files,"<p>I'm using VueJS and Jest for unit testing my components. </p>

<p>I'm also using the Bootstrap Vue library for styling. I need to use this plugin in my Jest tests in order to remove some console warnings about unknown plugins.</p>

<p>I have created a setup file as so:</p>

<pre><code>import { createLocalVue } from '@vue/test-utils'
import BootstrapVue from 'bootstrap-vue'

const localVue = createLocalVue()

localVue.use(BootstrapVue)
</code></pre>

<p>And configured Jest to use this before every test. </p>

<pre><code>setupFiles: ['&lt;rootDir&gt;/tests/unit/setup']
</code></pre>

<p>However, to remove the warnings from the console, I need to use the <code>localVue</code> instance when mounting the component:</p>

<pre><code>const wrapper = shallowMount(MyComponent, {
      localVue,
      propsData: { value: 'someVal }
    })
</code></pre>

<p>However there is no way that I can see to get the <code>localVue</code> instance created in the <code>setup.js</code> into the test spec files. </p>

<p>If I do this:</p>

<pre><code>import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'

Vue.use(BootstrapVue)
</code></pre>

<p>It works fine, but this is bad as we should not be using the Global Vue instance in Jest tests.</p>

<p><strong>Is there a way to do what I want to do, or am I going to have to construct the Bootstrap Vue plugins (and others as they come along...) into every single test file?</strong></p>
",https://stackoverflow.com/questions/58024549/vue-jest-global-config-carrying-over-into-spec-files,"['javascript', 'unit-testing', 'vue.js', 'jestjs', 'vue-test-utils']",2040,True,5,1
Is there a way to prevent the infinite loop after creating an iterable custom object in Python - 3.x?,"<p>I'm setting up a library to spawn as many threads as I can and have them complete any task they are assigned too. When unit testing the creation of the object containing 'n' number of threads and trying to iterate over each one at the object level I am running into an infinite loop.</p>

<p>I fixed the pickling issue with race conditions, but now when trying to output how many threads were created in a for loop, when debugging I encounter an infinite loop. </p>

<pre class=""lang-py prettyprint-override""><code>from __future__ import print_function

try:
    import sys
    from threading import Thread, Lock, current_thread
    from queue import Queue
except ImportError:
    raise ImportError


class Worker(Thread):
    """""" Thread executing tasks from a given tasks queue """"""

    def __init__(self, tasks):
        Thread.__init__(self)
        self.tasks = tasks
        self.daemon = True
        self.start()

    def run(self):
        while True:
            func, args, kargs = self.tasks.get()
            try:
                # Acquire locking mechanism for threads to prevent race condition
                Lock.acquire()
                func(*args, **kargs)
                # Release locking mechanism
                Lock.release()
            except Exception as e:
                # An exception happened in this thread
                raise e
            finally:
                if self.tasks is None:
                    # Mark process done once there are no more tasks to process
                    self.tasks.task_done()


class SpawnThreads:
    """"""Pool of threads consuming tasks from a queue.""""""

    def __init__(self, num_threads: int):
        self.tasks = Queue(num_threads)
        self.num_threads = num_threads
        for _ in range(self.num_threads):
            Worker(self.tasks)

    def __iter__(self):
        return self

    def __next__(self):
        next_value = 0
        while next_value &lt; self.num_threads:
            try:
                next_value += 1
            except Exception:
                raise StopIteration
        return next_value

    def add_task(self, func, *args, **kargs):
        """"""Add a task to the queue.""""""
        self.tasks.put((func, args, kargs))

    def task_list(self, func, args_list):
        """"""Add a list of tasks to the queue.""""""
        for args in args_list:
            self.add_task(func, args)

    def wait_completion(self):
        """""".Wait for completion of all the tasks in the queue.""""""
        self.tasks.join()

    def get_qsize(self):
        """"""Return the approximate size of the queue.""""""
        return self.tasks.qsize()

    def get_current_thread(self):
        return current_thread()
</code></pre>

<p>This is the unittest to evaluate the creation of the thread spawning object and iterate and access each individual thread.</p>

<pre class=""lang-py prettyprint-override""><code>import pytest
import unittest
import SpawnThreads


@unittest
class TestThreadFactory(unittest.TestCase):

    def test_spawn_threads(self):
        workforce = SpawnThreads(5)

        self.assertIsNotNone(workforce)

        print(workforce)

        for w in workforce:
            print(w)
</code></pre>

<p>The expected output should be the address space/object, which is each thread (5 total).</p>

<p>More Specifically I would like to see this result 5 times in the console:</p>

<pre class=""lang-py prettyprint-override""><code>&lt;ThreadFactory.thread_factory.SpawnThreads object at 0x0000024E851F5208&gt;
</code></pre>

<p>I am getting the integer 5 returned infinitely instead of the 5 addresses of threads.</p>
",https://stackoverflow.com/questions/57433964/is-there-a-way-to-prevent-the-infinite-loop-after-creating-an-iterable-custom-ob,"['python', 'python-3.x', 'multithreading', 'loops', 'iterable']",386,True,1,2
Unit test Best Practices when testing Exceptions,"<p>So I've been unit testing an android application, and while there are cases that I test with fail scenarios, I don't test them quite the way this answer is suggesting (<a href=""https://stackoverflow.com/questions/31423643/try-catch-in-a-junit-test/31423712"">Try catch in a JUnit test</a>).</p>

<p>I test it the way it shows on the code below. The answer is suggesting that you should have on test method signature the ""throws Exception"", since if it actually throws an exception you don't expect, it will fail the test. However i tried it with and without that piece of code, and it fails the same way.
The answer provided above, also approaches this kind of test with the use of ""rule"", which i haven't used, since everything i need i have them inside my try catch block, and the instantiations are done inside a @Before method.</p>

<pre><code>@Test
public void testMethod() {
   try{
   //code that will throw exception
   fail(""Exception was not thrown"");
   } catch (/* types of exceptions */) {
   //my asserts
   }
}
</code></pre>

<p>What I'm after is which approach is considered ""best practice"" and the reason behind it.</p>
",https://stackoverflow.com/questions/58337403/unit-test-best-practices-when-testing-exceptions,"['java', 'android', 'unit-testing', 'junit4']",5958,True,1,3
How to use resetMocks:true with module factory mocks,"<p>I would like to mock imported modules while keeping my unit tests independent of each other.</p>

<p>Setting resetMocks:true in my Jest config file means that behaviour set up using <a href=""https://jestjs.io/docs/en/es6-class-mocks#calling-jestmock-docs-en-jest-object-jestmockmodulename-factory-options-with-the-module-factory-parameter"" rel=""nofollow noreferrer"">module factory mocking</a> is lost (<a href=""https://github.com/facebook/jest/issues/7573"" rel=""nofollow noreferrer"">issue</a>). Setting up module mocks in any other way doesn't work (<a href=""https://github.com/facebook/jest/issues/2582"" rel=""nofollow noreferrer"">issue</a>).</p>

<p>Changing to resetMocks:false couples the unit tests and makes the order they are executed matter, which goes against unit testing best practices.</p>

<p>I have tried calling <code>jest.mock('./a', () =&gt; {/* implementation */})</code> inside <code>beforeEach()</code> and at the top of <code>test()</code>. I have also tried to use a reference to a <code>jest.fn()</code> inside the module factory mock and then call <code>.mockImplementation()</code> on that reference.</p>

<p>Minimum demonstration:</p>

<pre class=""lang-js prettyprint-override""><code>// greeter.ts
export class Greeter {
    sayHello(): string {
        return 'hello world!';
    }
}
</code></pre>

<pre class=""lang-js prettyprint-override""><code>// module-mocking.spec.ts
import { Greeter } from ""./greeter"";

jest.mock('./greeter', () =&gt; ({
    Greeter: jest.fn(() =&gt; ({ sayHello: () =&gt; 'goodbye world!' }))
}));

test('mocked module behaviour should exist', () =&gt; {
    const result = new Greeter().sayHello();

    expect(result).toEqual('goodbye world!');
});

</code></pre>

<p>This test fails with the error:</p>

<blockquote>
  <p>TypeError: (intermediate value).sayHello is not a function</p>
</blockquote>

<p>Moving the <code>jest.mock()</code> inside <code>beforeEach()</code> or into <code>test()</code> results in:</p>

<blockquote>
  <p>Expected: ""goodbye world!"" Received: ""hello world!""</p>
</blockquote>

<h1>Edit</h1>

<p>I managed to work around this by using <code>require</code> instead of <code>import</code>. The question still remains for ES6 imports.</p>

<pre class=""lang-js prettyprint-override""><code>// module-mocking.spec.ts
const greeter = require(""./greeter"");

let mockGreeter: any;

beforeEach(() =&gt; {
    mockGreeter = { sayHello: () =&gt; 'goodbye world!' };
    greeter.Greeter = jest.fn(() =&gt; mockGreeter);
});

test('mocked module behaviour should exist', () =&gt; {
    const result = new Greeter().sayHello();

    expect(result).toEqual('goodbye world!');
});
</code></pre>
",https://stackoverflow.com/questions/56442208/how-to-use-resetmockstrue-with-module-factory-mocks,['jestjs'],407,False,1,0
Why and when you should create a new project in a visual studio solution?,"<p>Why and When you should create a new project in a visual studio solution?
To be more specific, when you should separate the main project in multiple projects?</p>

<p>We all know that Database files should be separated by main project, that Entity Framework models should be separated, but what about ""components""?</p>

<p>Let's assume i have a WebAPI project, with some Apis and some features, including Entity Framework and Database files. 
Atm these features are included in the main project and my solution structure is:</p>

<pre><code>- App.Api [Main project, With Feature1, Feature2, Feature3, FeatureX, Reference projects App.Models]
|- ApiControllers
|- Helpers
|- Managers
|- Assets
|- Web.config

- App.Models [Models Project]
|- Entity Framework Auto Generated Models

- App.Database [Database Project]
|- Sql Files 
</code></pre>

<p>What if i split my features in multiple projects and include them in the main project, using the main project as ""HEAD"" of the other projects?
Something like:</p>

<pre><code>- App.Api [Main project, reference Projects App.Feature.Feature1, App.Feature.Feature2, App.Feature.Feature3, App.Feature.FeatureX, App.Models]
|- ApiControllers
|- Web.config

- App.Feature.Feature1 [Library Project - Feature 1, splitted from main project]
|- Managers
|- Helpers
|- Other files *.cs

- App.Feature.Feature2 [Library Project - Feature 2, splitted from main project]
|- Managers
|- Helpers
|- Other files *.cs

- App.Feature.Feature3 [Library Project - Feature 3, splitted from main project]
|- Managers
|- Helpers
|- Other files *.cs

- App.Feature.FeatureX [Library Project - Feature X, splitted from main project]
|- Managers
|- Helpers
|- Other files *.cs

- App.Models [Models Project]
|- Entity Framework Auto Generated Models

- App.Database [Database Project]
|- Sql Files 
</code></pre>

<p>After that i could but some unit testing attached to each project:</p>

<pre><code>- App.Api [Main project]
- App.Feature.Feature1 [Feature 1, splitted from main project]
- App.Feature.Feature1.Tests
- App.Feature.Feature2 [Feature 2, splitted from main project]
- App.Feature.Feature2.Tests
- App.Feature.Feature3 [Feature 3, splitted from main project]
- App.Feature.Feature3.Tests
</code></pre>

<p>So, this is the question. Why, why not and when create multiple projects?</p>

<p>I find more clean this approach instead of first</p>
",https://stackoverflow.com/questions/58952316/why-and-when-you-should-create-a-new-project-in-a-visual-studio-solution,"['c#', 'project', 'new-project']",182,False,1,0
How to test the method passed to subscribe method of the PubSubEvent in the Wpf Prism library?,"<p>I have two ViewModels, <strong>MainWindowShellViewModel</strong>(shellVm) and <strong>MainWindowContentViewModel</strong>(contentVm). The shellVm publishes an event and the contentVm subscribes to it.</p>

<p>The shell VM looks something like the following. I have omitted many details.</p>

<pre><code>// ctor
public MainWindowShellViewModel(IEventAggregator eventAggregator)
{
    _EventAggregator = eventAggregator ?? throw new ArgumentNullException(nameof(IEventAggregator) + "" service injected is null!!!"");

    _AppStartingClosingEventToken = _EventAggregator.GetEvent&lt;AppStartingClosingEvent&gt;();
}

private void MainWindowShellLoaded()
{
    var payload = new AppStartingClosingEventData();
    payload.Data = ""MainWindowStarting"";
    _AppStartingClosingEventToken.Publish(payload);
}
</code></pre>

<p>The AppStartingClosingEvent is a no brainer type as follows.</p>

<pre><code>public class AppStartingClosingEvent : PubSubEvent&lt;AppStartingClosingEventData&gt;
{ }

public class AppStartingClosingEventData
{
    public string Data { get; set; }
}
</code></pre>

<p>And finally, the contentVm looks as follows.</p>

<pre><code>public MainWindowContentViewModel(IEventAggregator eventAggregator)
{
    _AppClosingEventToken.Subscribe(AppStartingClosing);
}
private void AppStartingClosing(AppStartingClosingEventData appStartingClosingEventData)
{
    if (appStartingClosingEventData.Data == ""MainWindowStarting"")
        LoadState(appStartingClosingEventData);
    if (appStartingClosingEventData.Data == ""MainWindowClosing"")
        SaveState(appStartingClosingEventData);
}
</code></pre>

<p>I want to test the that the method <strong>AppStartingClosing</strong> inside of contentVm is called with proper data. I am using Moq
I am running out of ideas. Please suggest. Tried the following but so far no success. </p>

<p><a href=""https://stackoverflow.com/questions/2375178/how-do-i-test-prism-event-aggregator-subscriptions-on-the-uithread"">How do I test Prism event aggregator subscriptions, on the UIThread?</a></p>

<p><a href=""https://stackoverflow.com/questions/21014195/using-moq-to-verify-a-prism-event-subscription-fails"">Using Moq to verify a Prism event subscription fails</a></p>

<p><a href=""https://stackoverflow.com/questions/36141498/unit-testing-with-moq-prism-6-and-event-aggregation"">Unit testing with Moq, Prism 6, and Event Aggregation</a></p>

<p><a href=""https://stackoverflow.com/questions/3694195/moq-event-aggregator-is-it-possible"">Moq Event Aggregator Is it possible</a>
            // <a href=""https://stackoverflow.com/questions/10998455/verifying-a-delegate-was-called-with-moq"">Verifying a delegate was called with Moq</a></p>

<p>EDIT</p>

<p>Here is what I have tried.</p>

<pre><code>// Arrange
var mockingKernel = new MoqMockingKernel();
var eventAggregatorMock = mockingKernel.GetMock&lt;IEventAggregator&gt;();
var eventBeingListenedTo = new AppStartingClosingEvent();
eventAggregatorMock.Setup(e =&gt; e.GetEvent&lt;AppStartingClosingEvent&gt;()).Returns(eventBeingListenedTo);            
var vm = mockingKernel.Get&lt;MainWindowContentViewModel&gt;();
var evData = new AppStartingClosingEventData();
evData.Data = ""MainWindowStarting"";

        // Act
eventBeingListenedTo.Publish(evData);
</code></pre>

<p>Now, what should I do? I am not even clear if I have approached correctly.</p>
",https://stackoverflow.com/questions/54040178/how-to-test-the-method-passed-to-subscribe-method-of-the-pubsubevent-in-the-wpf,"['moq', 'prism']",182,True,1,1
C Mocking: How to do it correctly,"<p>I recently got into Unit-Testing embedded C Code.
I'd like to test each module fully isolated from all the others.  This approach requires me to simulate (or ""fake"")
all the dependencies and external calls a module makes.</p>

<p>Doing just that, I would end up with multiple definitions for the same function -- all the fakes would have the same identifier.</p>

<p>I believe the most common approach to avoid having multiple definitions is to compile one binary
for each test -- instead of one big program for all tests.</p>

<p>However this introduces new difficulties.  I need a main()-Function for every Module under Test. Also each program now prints its own summary instead of one the total
test summary.  Oh and its quite tedious to set up the build environment to do this...</p>

<p>There is very likely a smart way to do this.  <strong>How is it done correctly?</strong></p>
",https://stackoverflow.com/questions/57363896/c-mocking-how-to-do-it-correctly,"['c', 'mocking', 'automocking']",97,False,1,0
Rerunning groups of tests in xunit for diferent program modes,"<p>I have a program which can run in three modes, each of which have somewhat different operational logic, and a different data set.</p>

<p>I am adding unit testing to this project using XUnit, and would like to have a set of tests that fires once for each of the program modes.</p>

<p>I could do this using [InlineData()] for each test with a range of values from 1-3, and then select each mode from an array. However, the problem with this approach is that <em>switching mode takes around 20 seconds, and I'd rather have my set of tests run once for each of my three modes, rather than changing modes each time I ran a test.</em></p>

<p>Does anyone have any suggestions for how I could call a set of tests for N different modes, each with a different data set, only switching once for each mode?</p>
",https://stackoverflow.com/questions/54681918/rerunning-groups-of-tests-in-xunit-for-diferent-program-modes,"['c#', 'unit-testing', 'xunit', 'xunit.net']",50,True,1,1
Testing views constraints programmatically ( In Unit test ),"<p>I have built all my UI programmatically without using IB in Xcode. Now I want to assert that the constraints are correct in my Unit Tests ( Yes, not in UI testing ).</p>

<p>I have some constraints like these :</p>

<pre><code>footer.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
footer.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
footer.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
footer.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.08).isActive = true
</code></pre>

<p>Now I want to test this in my unit testing. I can assert that the footer is not nil, and that it has the expected properties except for the dimensions, as they show up as 0 always. For instance, this is something I tried but it did not work :</p>

<pre><code>XCTAssertTrue(subject.getFooterView().frame.origin.y == subject.view.frame.origin.y)
</code></pre>

<p>Which I think should be true but it fails. If I print the values of each property, I can see that the value <strong>subject.view.frame.origin.y</strong> is <em>414</em> but the value <strong>subject.getFooterView().frame.origin.y</strong> is always <em>zero</em>.</p>

<p>Same happens with all the other properties, for instance <strong>frame.size.width</strong>, etc, are always <em>zero</em> for my footer.</p>

<p>Can someone help me to understand this?</p>
",https://stackoverflow.com/questions/57394388/testing-views-constraints-programmatically-in-unit-test,"['swift', 'unit-testing']",1742,True,1,1
How to access my MongoDB instance from my project to my xunit test project class?,"<p>I would like to mention that I have started learning how to build apis in asp net core 2.1 from microsoft's official documentation and I'm a beginner at this.</p>

<p>I have taken a sample task of building an api for a simple employee achievement form with MongoDB as my server, and have done documentation with Swashbuckle and currently stuck in unit testing my controller methods with xunit while i run my tests it returns me error:</p>

<blockquote>
  <p>Message: System.NullReferenceException : Object reference not set to an instance of an object.</p>
</blockquote>

<p>I have tried debugging my unit tests and I have found that every time my database instance ""_empModel"" returns null. Why does this happen?</p>

<p>What is the proper way to access this mongoDb instance in my xunit project to perform my tests?</p>

<p>Here is the link of my code snapshots: <a href=""https://drive.google.com/file/d/1jydiyuO_rSbx-2PXK0ZP8YoF8ho55avx/view?usp=sharing"" rel=""nofollow noreferrer"">https://drive.google.com/file/d/1jydiyuO_rSbx-2PXK0ZP8YoF8ho55avx/view?usp=sharing</a></p>
",https://stackoverflow.com/questions/54082347/how-to-access-my-mongodb-instance-from-my-project-to-my-xunit-test-project-class,"['c#', 'asp.net', 'mongodb']",411,False,0,2
"When trigged action, mockNavigationController return current viewController, not pushed","<p>I learning TTD, and have problem with navigation controller in Unit-testing.
    When I'm trying to push Detail View Controller through navigation stack (pushViewController(ViewController, animated:) ) with my mock controller, in test push function not perform (its perform only first time, when navigationController initialise).
On simulation iPhone, app work correctly.
    In code mockNavigationController have value pushedVC, that changes when pushViewController perform.
    When user tap on cell, dataProvider (delegate and dataSource for tableCell) post notification to ViewController (sut), that implements showDetails method.</p>

<p>I'd try take topViewController from navigationController:
 sut.navigationController?.topViewController - it's return sut ViewController.
Try not initialise navigationController in test. sut.navigationController?.topViewController - it's return nil.</p>

<p>This beginning of XCTestCase</p>

<pre class=""lang-swift prettyprint-override""><code>var sut: EatersListViewController!

    override func setUp() {
        super.setUp()

        let storyBoard = UIStoryboard(name: ""Main"", bundle: nil)
        let vc = storyBoard.instantiateViewController(withIdentifier: String(describing: EatersListViewController.self))
        sut = vc as? EatersListViewController

        sut.loadViewIfNeeded()
    }
</code></pre>

<p>This test function</p>

<pre class=""lang-swift prettyprint-override""><code>func testSelectedRowPushedDetailVC() {
        let mockNavigationController = MockNavigationController(rootViewController: sut)
        UIApplication.shared.keyWindow?.rootViewController = mockNavigationController

        let eater1 = Eater(name: ""Foo"")
        sut.dataProvider.manager!.addEater(eater: eater1)

        sut.loadViewIfNeeded()

        sut.tableView.delegate?.tableView?(sut.tableView, didSelectRowAt: IndexPath(row: 0, section: 0))

        guard let detailEaterVC = mockNavigationController.pushedVC as? DetailEaterViewController else {
            XCTFail()
            return
        }
        detailEaterVC.loadViewIfNeeded()

        XCTAssertNotNil(detailEaterVC.eaterNameLabel)
        XCTAssertEqual(detailEaterVC.eaterData, eater1)
}
</code></pre>

<p>This function from ViewController </p>

<pre class=""lang-swift prettyprint-override""><code>@objc func showDetails(withNotification notification: Notification) {
        guard
            let userInfo = notification.userInfo,
            let eater = userInfo[""eater""] as? Eater,
            let detailEaterVC = storyboard?.instantiateViewController(withIdentifier: String(describing: DetailEaterViewController.self)) as? DetailEaterViewController else { return }
        detailEaterVC.eaterData = eater
        navigationController?.pushViewController(detailEaterVC, animated: true)
}
</code></pre>

<p>And MockNavigationController</p>

<pre class=""lang-swift prettyprint-override""><code>extension EatersListViewControllerTests {
    class MockNavigationController: UINavigationController {

        var pushedVC: UIViewController?

        override func pushViewController(_ viewController: UIViewController, animated: Bool) {
            pushedVC = viewController
            super.pushViewController(viewController, animated: animated)
        }
    }
}
</code></pre>

<p>I'd expected that XCTAssert work correct, but every time test failed on XCTFail() line. I think somewhere error, and don't know here.</p>

<pre class=""lang-swift prettyprint-override""><code>XCTAssertNotNil(detailEaterVC.eaterNameLabel)
XCTAssertEqual(detailEaterVC.eaterData, eater1)
</code></pre>

<p>Need help with code, where I wrong. Thanks for reading.</p>
",https://stackoverflow.com/questions/55743142/when-trigged-action-mocknavigationcontroller-return-current-viewcontroller-not,"['ios', 'swift', 'unit-testing', 'uinavigationcontroller', 'mocking']",730,True,0,1
How to fix the below test case when i am migrating from angularjs 1.6.9 to 1.7.8,"<p>i am trying to migrate my angularjs application from v1.6.9 to v1.7.8. my test case are failing with </p>

<blockquote>
  <p>angular-mock.js($rootScope)</p>
  
  <p>ERROR: No response Defined! in angularjs/angular-mocks.js(1607)</p>
  
  <p>ERROR:$rootScope:INPROG</p>
</blockquote>

<p>since i am new to jasmine karma testing i have tried with $rootscope.flush(). but i am not able to resolve it .</p>

<p>this is my first unit testing with Angularjs and jasmine karma, not able to find the exact reason and i have gone through the release notes of the other releases as well.</p>

<p>with $rootScope i found that they have modified its scope to the function not generic.</p>

<p>Below is my spec.js:
I am getting error with $rootscope,flush(). could some please help me out to resolve this issue as it is required.</p>

<pre><code>       $httpBackend.when('GET','/application/api/prefernce-definition')
          .respond(successResponsePrefernces);
        $httpBackend.when('POST','/application/api/setprefernce-definition')
          .respond(201);
        $httpBackend.when('POST','/application/api/v1/set-prefernces');
        $httpBackend.when('POST','/application/api/v2/balances')
          .respond(accountApiResponse);

        //assertion for expecting proper get request for preferences-definition
        $httpBackend.expectGET(,'/application/api/v1/prefernce-prefernces');

        //fetch and set prefernces
        $scope.onclickSetting();
        $rootScope.flush();
        $timeout.flush();

        //now save the settings
        $scope.saveViewSettings();
// getting error in this line after the flush
        $rootScope.flush();
        $timeout.flush();

        var viewMode = $scope.model.viewSettings.viewMode,
           viewModeExpected = successResponsePreferences.preferenceDefinitionList[0];

        expect(viewMode.default).toBe(viewModeExpected.defaultPreferenceValue);
        expect(viewMode.selected).toBe(viewModeExpected.currentUserPreferenceValue);
        expect($scope.$broadcast).toHaveBeenCalledWith(""ShowFilter"");

        //should update the prefernces in cache
        expect(viewMode.selected).toBe(cacheService.getPreferences().viewMode);
        expect(analyticsService.sendAction).toHaveBeenCalledwith(
          Constant.ACCOUNT_BALANCES.MODULE_NAME,
          Constant.ACCOUNT_BALANCES,VIEW_SETTINGS,
          []
          );
        expect(analyticsService.sendAction).toHaveBeenCalledwith(
          Constant.ACCOUNT_BALANCES.MODULE_NAME,
          Constant.ACCOUNT_BALANCES,VIEW_SETTINGS,
          [Constant.EXTD_MODE, Constant.NO_GROUPING]
          );
        });
</code></pre>

<hr>

<p>Below are the errors:</p>

<blockquote>
  <p>Error: No response defined! In 
  ../bower_components/angular-mocks/angular-mocks.js(line 1607) $httpBackend@/../bower_components/angular-mocks/angular-mocks.js:1607:63. </p>
</blockquote>
",https://stackoverflow.com/questions/58716828/how-to-fix-the-below-test-case-when-i-am-migrating-from-angularjs-1-6-9-to-1-7-8,"['angularjs', 'karma-jasmine', 'angular-mock', 'angularjs-1.7']",192,False,0,0
"How to write Jasmine unit testing code of a http call from a service , which fetches the data from another service in Angular 2+","<p>I have tried to write unit testing of a httpmock one of a service which uses a method (function) to get http get call, but failed to write. </p>

<p><strong>saveservice.service.ts -- file</strong></p>

<pre><code>const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
const envURL = sessionStorage.getItem('apiBaseURL');
 httpGet&lt;T&gt;(url) {
    const URL = envURL + url;
    return this.http.get&lt;T&gt;(URL, httpOptions);
  }
</code></pre>

<p>this is how workservice and save service are connected.Now I want to write unit test case for work.component.ts file,but Iam unable to write the httpmock calls there .</p>

<p>For info, apiUrl is present in a different file named env.ts file-- env.ts</p>

<p><strong>env.ts -- file</strong></p>

<pre><code>export const apivalue= {

    apiBaseUrl:""https://example.co/"",
  };
</code></pre>

<p><strong>work.service.ts</strong></p>

<pre><code>import {SaveserviceService } from '../../.././saveservice.service';

getworklist(employeeID){

    return this.saveservice.httpGet('work/v1/works?employeeid=' + employeeID);
  }
</code></pre>

<p>this is how workservice and save service are connected.Now I want to write unit test case of for work.component.ts file,but Iam unable to write the httpmock calls there .</p>

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

<pre><code>ngOnit(){
this.employeeID:this.id;
   this.workservice.getworkList(this.employeeID).subscribe(
      (data) =&gt; {
        this.workList = data;
       console.log("" ggghfghfgh"", this.worklist);
      }, (error) =&gt; {
        console.log(error);}
</code></pre>

<p>Above one is work.component.ts file for which i should write unit test cases.Please help me to complete it.</p>

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

<pre><code> let httpMock: HttpTestingController;
 let injector: Injector;
  let workservice: WorksService;
let saveservice123: SaveService;

 providers: [
        Injector,
        HttpClient,
        HttpClientTestingModule,
        saveService,
        worksService
      ],

  httpMock = TestBed.get(HttpTestingController);
    workservice = TestBed.get(WorksService);
    saveservice123 = TestBed.get(SaveService)

  fit('getting work detsails indivually', async(() =&gt; {

    fixture = TestBed.createComponent(worksComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    workservice.getworklist(123).subscribe(() =&gt;{});

    const request = httpMock.expectOne(""work/v1/works?employeeid="")
    // expect(request.request.method).toBe('httpGet');
    // request.flush(xxxxx);

</code></pre>

<p>its throwing below  error </p>

<pre><code>Error: Expected one matching request for criteria ""Match URL: work/v1/works?employeeid="", found none.
</code></pre>

<p>Please help , how to know to write unit test cases for this type..
I also tried to spy also,</p>

<pre><code>const mockdata = { id:1, title: ""Hello world"",  paste: ""console.log('Hello world');""}
     const spyOnAdd = spyOn(service, ""getworkList"").and.returnValue(mockdata);

</code></pre>
",https://stackoverflow.com/questions/58249940/how-to-write-jasmine-unit-testing-code-of-a-http-call-from-a-service-which-fet,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",75,False,0,0
Unit Testing - Prism - Xamarin.Forms - INavigationService issue,"<p>I recently started working on a Xamarin.Forms app for iOS and Android. I added a unit testing project with xUnit packages. </p>

<p>As of right now, The app has one view and one viewmodel. I wanted to wire everything up. so the viewmodel only has one property. the property is initialized to string.empty. So I am just checking to make sure it's not null. The viewmodel does a dependency on NagivationService.</p>

<p>in my App.xaml.cs - the view and viewmodel are registered for navigation.</p>

<pre><code>protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterForNavigation&lt;NavigationPage&gt;();
    containerRegistry.RegisterForNavigation&lt;ViewAPage, ViewAPageViewModel&gt;();
}
</code></pre>

<p>I created a mock of the App</p>

<pre><code>public class AppMock : App
{
    public AppMock(IPlatformInitializer initializer)
        : base(initializer) {}

    // Added as a work around
    public new INavigationService NavigationService =&gt; base.NavigationService;

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        base.RegisterTypes(containerRegistry);
        containerRegistry.Register&lt;ILoggerFacade, XunitTestOutputLogger&gt;();
    }
}
</code></pre>

<p>The Test Fixture</p>

<pre><code>public class ViewAViewModelFixture : FixtureBase, IDisposable
{
    public ViewAViewModelFixture(ITestOutputHelper testOutputHelper)
        : base(testOutputHelper) {
    }

    private AppMock CreateApp()
    {
        var initializer = new XunitPlatformInitializer(_testOutputHelper);
        return new AppMock(initializer);
    }

    protected AppMock App
    {
        get
        {
            if ( app == null )
            {
                this.App = CreateApp();
            }
            return this.app;
        }
        set
        {
            this.app = value;
        }
    }
    private AppMock app;

    [Fact]
    public void Email_IsEmpty()
    {            
        ViewAViewModel vm = (ViewAViewModel)this.App.Container.Resolve(typeof(ViewAViewModel));

        string email = vm.Email;

        Assert.Equal(expected: string.Empty, actual: email);
    }

    public void Dispose()
    {
        PageNavigationRegistry.ClearRegistrationCache();
    }
}
</code></pre>

<p>When I attempt to run the above test I am getting the following error:</p>

<pre><code>Message: Unity.Exceptions.ResolutionFailedException : Resolution of the dependency failed, type = 'App.ViewModels.ViewAViewModel', name = '(none)'.
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Prism.Navigation.INavigationService, is an interface and cannot be constructed. Are you missing a type mapping?
</code></pre>

<p>I am not sure what I am missing. When I run the app locally in an Android Emulator or iOS simulator it works fine. so I tried the following: </p>

<pre><code>[Fact]
public void Email_IsEmpty()
{
    var app = this.App;
    var NavService = app.NavigationService;

    NavService.NavigateAsync(""/ViewA"");

    ViewA view = (ViewA)this.App.MainPage;

    Assert.IsType&lt;ViewAViewModel&gt;(view.BindingContext);
    ViewAViewModel vm = view.BindingContext as ViewAViewModel;

    string email = vm.Email;

    Assert.Equal(expected: string.Empty, actual: email);
}
</code></pre>

<p>this test passes, while the other one obviously fails. </p>

<p>Anyone see what I am missing?</p>
",https://stackoverflow.com/questions/54395369/unit-testing-prism-xamarin-forms-inavigationservice-issue,"['unit-testing', 'xamarin.forms', 'prism']",532,False,0,0
Hybrid Angular App Testing with Karma Cannot Load HTML,"<p>We have a hybrid Angular app that uses karma for unit testing. I'm trying to add our first suite of tests but I'm getting some errors that indicate karma cannot find the <code>dashboard.component.html</code>. </p>

<p>View:</p>

<pre><code>import { Component, OnInit } from '@angular/core';

@Component({
    templateUrl: './views/components/dashboard/dashboard.component.html'
})
export class DashboardComponent implements OnInit {
    constructor() {}

    ngOnInit() {
        console.log('works!');
    }
}
</code></pre>

<p>Here is my <code>karma.config.js</code></p>

<pre><code>module.exports = function(config) {
    config.set({
        basePath: '',
        frameworks: ['angular', 'jasmine'],
        files: [
            { pattern: 'src/test.ts', watched: false },
            { pattern: 'dist/views/components/dashboard/dashboard.component.html', included: false, watched: true }
        ],
        exclude: [],
        preprocessors: {
            'src/test.ts': ['webpack', 'sourcemap']
        },
        webpack: require('./webpack-base.config'),
        reporters: ['progress'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        singleRun: true,
        concurrency: Infinity,
        browsers: ['Chrome_Headless'],
        customLaunchers: {
            Chrome_Headless: {
                base: 'Chrome',
                flags: [
                    '--headless',
                    '--disable-gpu',
                    '--remote-debugging-port=9222'
                ]
            },
            Chrome_without_security: {
                base: 'Chrome',
                flags: [
                    '--headless',
                    '--disable-gpu',
                    '--remote-debugging-port=9222',
                    '--disable-web-security'
                ]
            }
        },
        // workaround for typescript and chrome/headless
        mime: {
            'text/x-typescript': ['ts', 'tsx']
        }
    });
};
</code></pre>

<p>Our hybrid app gets compiled using Webpack. All view files are copied over to <code>/view</code>. Here is our webpack file:</p>

<pre><code>/* eslint-env node */
const webpack = require('webpack');
const helpers = require('./helpers');
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractSass = new ExtractTextPlugin({
    filename: 'css/[name].[hash].css',
    disable: process.env.NODE_ENV === 'development'
});

module.exports = {
    mode: 'development',
    entry: {
        app: './src/js/index.ts'
    },
    resolve: {
        extensions: ['.ts', '.js', '.html'],
        alias: {
            '@angular/upgrade/static':
                '@angular/upgrade/bundles/upgrade-static.umd.js'
        }
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        // Workaround for angular/angular#11580
        new webpack.ContextReplacementPlugin(
            // The (\\|\/) piece accounts for path separators in *nix and Windows
            /angular(\\|\/)core(\\|\/)@angular/,
            helpers.root('./src'), // location of your src
            {} // a map of your routes
        ),
        new HtmlWebpackPlugin({
            template: './src/index.html',
            inject: 'body'
        }),
        new CopyWebpackPlugin([
            { from: './src/views', to: 'views' },
            { from: './src/js/components', to: 'views/components', ignore: ['*.ts', '*.scss']},
            { from: './src/img', to: 'img' },
            { from: './src/config.js', to: '' }
        ]),
        extractSass
    ],
    devtool: 'inline-source-map',
    devServer: {
        contentBase: './dist',
        historyApiFallback: {
            disableDotRule: true
        }
    },
    output: {
        filename: 'js/[name].[hash].js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                loaders: ['awesome-typescript-loader', 'angular-router-loader']
            },
            {
                test: /\.scss$/,
                use: extractSass.extract({
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                url: false,
                                import: true,
                                minimize: true,
                                sourceMap: true,
                                importLoaders: 1
                            }
                        },
                        {
                            loader: 'sass-loader',
                            options: {
                                sourceMap: true
                            }
                        }
                    ],
                    fallback: 'style-loader'
                })
            }
        ]
    },
    optimization: {
        splitChunks: {
            cacheGroups: {
                commons: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'all'
                }
            }
        }
    }
};
</code></pre>

<p>Finally here is my very simple test:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DashboardComponent } from './dashboard.component';

describe('The Dashboard', () =&gt; {
    let component: DashboardComponent;
    let fixture: ComponentFixture&lt;DashboardComponent&gt;;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [DashboardComponent]
        }).compileComponents();
    }));

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

    it('should be created', () =&gt; {
        expect(component).toBeTruthy();
    });
});
</code></pre>

<p>This app works correctly as it should when <code>npm start</code>. Again the problem that I'm getting is a 404 of the HTML file. </p>

<blockquote>
  <p>ERROR: 'Unhandled Promise rejection:', 'Failed to load
  views/components/dashboard/dashboard.component.html', '; Zone:',
  'ProxyZone', '; Task:', 'Promise.then', '; Value:', 'Failed to load
  views/components/dashboard/dashboard.component.html', undefined</p>
</blockquote>

<p>I've tried overriding the test spec in the <code>TestBed.configureTestingModule()</code> to look for the HTML file in different places. I've tried adding a new files pattern in the karma.config.js. I've also tried a combination of the two to no success.</p>
",https://stackoverflow.com/questions/54537989/hybrid-angular-app-testing-with-karma-cannot-load-html,"['angular', 'unit-testing', 'karma-runner', 'karma-webpack', 'angular-hybrid']",535,True,0,1
How do I observe DOM changes in an Angular/Jasmine unit test?,"<p>I have an Angular 8 application that uses Jasmine and Karma for unit testing.</p>

<p>I have a fairly simple method that copies a string to the user's clipboard, and I am trying to unit test it. The method creates and destroys a temporary textarea as part of this copy process. I need to capture this textarea when it is created.</p>

<pre><code>  copyToClipboard() {
    // Create a textarea to hold the string.
    const text = document.createElement('textarea');
    text.value = this.value;
    text.id = 'temporary_copy_area';
    document.body.appendChild(text);

    // Copy the contents of the textarea to the clipboard.
    text.select();
    document.execCommand(""copy"");

    // Clean up.
    document.body.removeChild(text);
  }
</code></pre>

<p>I created a <code>MutationObserver</code> in the test's <code>beforeEach</code> and I'm observing the document body. I disconnect in the <code>afterEach</code>.</p>

<pre><code>  beforeEach(() =&gt; {
    observer = new MutationObserver((changes) =&gt; {
      console.log('observed an event');
    });
    observer.observe(document.body, {subtree: true, childList: true})
  });

  afterEach(() =&gt; {
    observer.disconnect();
  });
</code></pre>

<p>A simple test that just calls the SUT produces no log messages:</p>

<pre><code>  it('should copy to the clipboard', () =&gt;
  {
    component.copyToClipboard();
  });
</code></pre>

<p>I know the code is executing, because the test text does wind up in the clipboard.</p>

<p>If I comment out the <code>afterEach</code>, the observer stays connected and I'll see events if I manipulate the page.</p>

<p>I tried commenting out the <code>removeChild</code> in the copy method, just in case the events were being suppressed because they canceled out. That didn't help.</p>
",https://stackoverflow.com/questions/57080730/how-do-i-observe-dom-changes-in-an-angular-jasmine-unit-test,"['javascript', 'angular', 'unit-testing', 'jasmine', 'mutation-observers']",1346,False,0,0
Using Two Different Mocks in Go Unit Test,"<p>I am learning to do unit testing using mocks in Go for the first time, using gomock's mockgen utility. My unit tests work fine except for one of them. The method-under-test has two dependencies: one on a database, and the other on an external service it makes rest api calls to. The mock for the database (mockRepo) works fine in that the method-under-test properly invokes the mock instead of the actual repo code. The mock for the rest client, however, continues to invoke the actual rest client and not the mock code. I can't figure out why. Can someone explain why and help fix?</p>

<p>Here is my unit test:</p>

<pre><code>func TestService_CreateWorkspace(t *testing.T) {
    ts := NewTestService(t)
    defer ts.mockCtrl.Finish()

    ts.mockClient.EXPECT().POST(gomock.Any(), gomock.Any(), gomock.Any()).Times(1).Return(&amp;http.Response{StatusCode: 200}, nil)

    testWs := TestWorkspaces()[""max-ws""]
    ts.mockRepo.EXPECT().Create(testWs).Times(1).Return(&amp;testWs, nil)

    ws, err := ts.service.CreateWorkspace(&amp;testWs)

    assert.Equal(t, testWs, ws)
    assert.NoError(t, err)
}
</code></pre>

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

<pre><code>type TestService struct {
    mockCtrl   *gomock.Controller
    mockClient *MockRestClient
    mockRepo   *MockRepository
    service    Service
}

func NewTestService(t *testing.T) *TestService {
    mockCtrl := gomock.NewController(t)
    mockRepo := NewMockRepository(mockCtrl)
    mockClient := NewMockRestClient(mockCtrl)
    return &amp;TestService{
        mockCtrl:   mockCtrl,
        mockClient: mockClient,
        mockRepo:   mockRepo,
        service:    NewService(mockRepo),
    }
}
</code></pre>

<p>Is there an issue with assigning the same mock controller to two different mock objects? Not really sure what's going on here. Any help appreciated.</p>
",https://stackoverflow.com/questions/55817579/using-two-different-mocks-in-go-unit-test,"['unit-testing', 'go', 'mocking', 'gomock']",933,False,-2,1
Jasmine Testing - How to test for a css class being applied?,"<p>I am currently creating my first JS project and am trying Jasmine unit testing for the first time.</p>
<p>In my code, I want to test the function in one of my classes which applies a css class to a button element. However I am having difficulty getting the Jasmine test to pass and I am not sure why.</p>
<p>The test fails due to the test not seeing the css class '.btn-active' in the targeted button, which is telling me that the function is not running, however I am unsure as to how to achieve this.</p>
<p>JS Class:</p>
<pre><code>
class ModeSelection {
        constructor() {
                this.easyBtn = $('#easy-mode');
                this.mediumBtn = $('#medium-mode');
                this.hardBtn = $('#hard-mode');
        }
        //applies the active class depending upon the button selected
        easyMode() {
                this.easyBtn.on('click', () =&gt; {
                        this.easyBtn.addClass('btn-active');
                        this.mediumBtn.removeClass('btn-active');
                        this.hardBtn.removeClass('btn-active');

                        $('.card-med').addClass('remove');
                        $('.card-hard').addClass('remove');
                });
        }
</code></pre>
<p>Please note, I have set a fixture before each test which contains the html button that I am looking to apply the class too.</p>
<p>Fixture:</p>
<pre><code>beforeEach(function() {
        setFixtures(`
&lt;div class=&quot;mode-select row&quot;&gt;
                        &lt;div class=&quot;col-sm-12 mode-header&quot;&gt;
                           &lt;h4&gt;Select your difficulty&lt;/h4&gt; 
                        &lt;/div&gt;
                        
                        &lt;div class=&quot;col-xs-12 col-sm-4&quot;&gt;
                            &lt;button id=&quot;easy-mode&quot; class=&quot;btn btn-mode btn-easy&quot;&gt;Easy&lt;/button&gt;
                        &lt;/div&gt;
                         &lt;div class=&quot;col-xs-12 col-sm-4&quot;&gt;
                            &lt;button id=&quot;medium-mode&quot; class=&quot;btn btn-mode btn-med&quot;&gt;Medium&lt;/button&gt;
                        &lt;/div&gt;
                         &lt;div class=&quot;col-xs-12 col-sm-4&quot;&gt;
                            &lt;button id=&quot;hard-mode&quot; class=&quot;btn btn-mode btn-hard btn-active&quot;&gt;Hard&lt;/button&gt;
                        &lt;/div&gt;
&lt;/div&gt;
      `)
});
</code></pre>
<p>Jasmine Test:</p>
<pre><code>
 describe('Check easy mode functions', function() {
        beforeEach(function() {
            this.mode = new ModeSelection();

        });

      it('btn-active to be applied when easy function activated', function() {

            var spy = spyOn(this.mode, 'easyMode').and.callThrough();


            expect($('#easy-mode')).toHaveClass('btn-active')
        });

 });


</code></pre>
<p>Apologies if this is fairly basic, however I am quite new to Jasmine and was just seeking the best way to get this test to work.</p>
<p>Thank</p>
<p>Sam</p>
",https://stackoverflow.com/questions/56499199/jasmine-testing-how-to-test-for-a-css-class-being-applied,"['javascript', 'jquery', 'unit-testing', 'testing', 'jasmine']",5500,True,4,1
How to unit-test a AWS Lambda use lambda-local with mocha?,"<p><strong>Background</strong></p>

<p>I am working on a project that is build with <strong>Serverless</strong> framework with  <strong>serverless-appsync-plugin</strong>. I implemented a single endpoint(AWS Lambda) to handle all the requests generate from Appsync through graphQL. The endpoint will route the request to the corresponding function to perform the operation.</p>

<p><strong>Problem</strong></p>

<p>Now that I have developed around 10+ operations, I want to automate the process of unit-testing. For simplicity, I decided to run that single endpoint as a lambda locally for all the testing (against running appsync-offline). </p>

<p>So, I used <a href=""https://www.npmjs.com/package/lambda-local"" rel=""nofollow noreferrer"">lambda-local</a> with <a href=""https://mochajs.org/"" rel=""nofollow noreferrer"">mocha</a>. However, I am not able to get a test-case to fail, based on the response I got from the lambda.</p>

<pre><code>it('db should have a user of uId: 123',  async function () {
  lambdaLocal.execute({
    event: makeUserEvent({userId: '123'}),
    callbackWaitsForEmptyEventLoop: false,
    lambdaPath,
    callback: function(err, data) {
      if(err) {
        console.log(1)
        expect.fail(null, null, 'You are not supposed to be here') //should fail here
      } else {
        console.log(2)
        // some checking here, may fail or may not fail
        expect.fail(null, null, 'return fail if the userId is 234') //should fail here too
      }
    }
  });
  console.log(3)
})
</code></pre>

<p>In both of the situation I want it to fail, it is not failing the test cases for either <code>callback('failed', null)</code> or <code>callback(null, 'success')</code>. </p>

<p><strong>So, what is the right way to make the lambda-local to fail a test case?</strong></p>
",https://stackoverflow.com/questions/56291060/how-to-unit-test-a-aws-lambda-use-lambda-local-with-mocha,"['unit-testing', 'lambda', 'aws-lambda', 'mocha.js']",1080,True,0,1
Angular unit testing form validation,"<p>I'm learning angular 8 and I'm using Karma for unit testing. I have created a basic registration form which works correctly but I'm facing issues in testing.</p>

<p>Upon testing I'm getting 2 failures </p>

<blockquote>
  <p>RegisterComponent > form should be valid
      Error: Expected validator to return Promise or Observable.</p>
</blockquote>

<p>and</p>

<blockquote>
  <p>RegisterComponent > should call onSubmit method
      Error:  : Expected a spy, but got FormGroup({ validator: Function, asyncValidator: null, _onCollectionChange: Function, pristine: true, touched: false, _onDisabledChange: [  ], controls: Object({ name: FormControl({ validator: Function, asyncValidator: null, _onCollectionChange: Function, pristine: true, touched: false, _onDisabledChange: [ Function ], _onChange: [ Function ], _pendingValue: '', value: '', status: 'INVALID', errors: Object({ required: true }), valueChanges: EventEmitter({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, __isAsync: false }), statusChanges: EventEmitter({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null, __isAsync: false }), _parent:  }), email: FormControl({ validator: Function, asyncValidator: Function, _onCollectionChange: Function, pristine: true, touched: false, _onDisabledChange: [ Function ], _onChange: [ Function ], _pendingValue: '', value: '' ....
      Usage: expect().toHaveBeenCalledTimes()</p>
</blockquote>

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

<pre class=""lang-js prettyprint-override""><code>import { ActivatedRoute, Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { AuthenticationService } from '@/_services';
import { MustMatch } from '@/_helpers/validators';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
@Component({ templateUrl: 'register.component.html' })
export class RegisterComponent implements OnInit {
  registerForm: FormGroup;
  submitted = false;
  returnUrl: string;
  error = '';

  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService
  ) {
    if (this.authenticationService.currentUserValue) {
      this.router.navigate(['/']);
    }
  }

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', Validators.required, Validators.email],
      phone: ['', Validators.required],
      password: ['', Validators.required, Validators.minLength(6)],
      confirmPassword: ['', Validators.required],
    }, {
        validator: MustMatch('password', 'confirmPassword')
      });

    this.returnUrl = this.route.snapshot.queryParams.returnUrl || '/';
  }

  get f() {
    return this.registerForm.controls;
  }

  onSubmit() {
    this.submitted = true;
    if (this.registerForm.invalid) {
      return;
    }

    this.submitted = false;
  }
}
</code></pre>

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

<pre class=""lang-js prettyprint-override""><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { RegisterComponent } from './register.component';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { DebugElement } from '@angular/core';

describe('RegisterComponent', () =&gt; {
  let component: RegisterComponent;
  let fixture: ComponentFixture&lt;RegisterComponent&gt;;
  let de: DebugElement;
  let el: HTMLElement;
  const fakeActivatedRoute = {
    snapshot: {
      queryParams: {
        returnUrl: '/'
      }
    }
  };
  const routerSpy = jasmine.createSpyObj('Router', ['navigate']);

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule, HttpClientTestingModule],
      declarations: [RegisterComponent],
      providers: [
        { provide: Router, useValue: routerSpy },
        { provide: ActivatedRoute, useFactory: () =&gt; fakeActivatedRoute }
      ]

    }).compileComponents().then(() =&gt; {
      fixture = TestBed.createComponent(RegisterComponent);
      component = fixture.componentInstance;
      component.ngOnInit();
      fixture.detectChanges();
      de = fixture.debugElement.query(By.css('form'));
      el = de.nativeElement;
    });
  }));

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

  it('form invalid when empty', () =&gt; {
    component.registerForm.controls.name.setValue('');
    component.registerForm.controls.email.setValue('');
    component.registerForm.controls.phone.setValue('');
    component.registerForm.controls.password.setValue('');
    component.registerForm.controls.confirmPassword.setValue('');
    expect(component.registerForm.valid).toBeFalsy();
  });

  it('username field validity', () =&gt; {
    const name = component.registerForm.controls.name;
    expect(name.valid).toBeFalsy();

    name.setValue('');
    expect(name.hasError('required')).toBeTruthy();

  });

  it('email field validity', () =&gt; {
    const email = component.registerForm.controls.email;
    expect(email.valid).toBeFalsy();

    email.setValue('');
    expect(email.hasError('required')).toBeTruthy();
  });

  it('phone field validity', () =&gt; {
    const phone = component.registerForm.controls.phone;
    expect(phone.valid).toBeFalsy();

    phone.setValue('');
    expect(phone.hasError('required')).toBeTruthy();

  });

  it('password field validity', () =&gt; {
    const password = component.registerForm.controls.password;
    expect(password.valid).toBeFalsy();

    password.setValue('');
    expect(password.hasError('required')).toBeTruthy();

  });

  it('confirmPassword field validity', () =&gt; {
    const confirmPassword = component.registerForm.controls.confirmPassword;
    expect(confirmPassword.valid).toBeFalsy();

    confirmPassword.setValue('');
    expect(confirmPassword.hasError('required')).toBeTruthy();

  });

  it('should set submitted to true', () =&gt; {
    component.onSubmit();
    expect(component.submitted).toBeTruthy();
  });

  it('should call onSubmit method', () =&gt; {
    spyOn(component, 'onSubmit');
    el = fixture.debugElement.query(By.css('button')).nativeElement;
    el.click();
    expect(component.registerForm).toHaveBeenCalledTimes(1);
  });

  it('form should be valid', () =&gt; {
    component.registerForm.controls.name.setValue('sasd');
    component.registerForm.controls.email.setValue('sadasd@asd.com');
    component.registerForm.controls.phone.setValue('132456789');
    component.registerForm.controls.password.setValue('qwerty');
    component.registerForm.controls.confirmPassword.setValue('qwerty');
    expect(component.registerForm.valid).toBeTruthy();
  });
});
</code></pre>

<p>I can't seem to understand what is causing this issue. Have gone through several docs and tutorials for this but it doesn't seem to work.</p>
",https://stackoverflow.com/questions/57457293/angular-unit-testing-form-validation,"['angular', 'forms', 'unit-testing', 'validation']",42824,True,11,2
Unit Test with Asp.Net Web Api and customer filter,"<p>I am working on the Unit Testing in Asp.Net Mvc Web Api.
I have 2 projects</p>

<p>1: Catalog.Api - This contains all the controllers</p>

<p>2: Catalog.UnitTests - This contains the Unit Test for controllers</p>

<p>All Controllers are Inherit with ""ApiController"" and every controller has custom filter [AuthenticationFilter]. Here is my values controller.</p>

<pre><code>    [AuthenticationFilter]
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable&lt;string&gt; Get()
        {
            return new string[] { ""value1"", ""value2"" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return ""value"";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
</code></pre>

<p>And my custom is check the authorization token. Here it is</p>

<pre><code>public class AuthenticationFilter: AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)

        {
            var request = actionContext.Request;
            var authorization = request.Headers.Authorization;

            if (authorization == null || authorization.Scheme != ""Bearer"")
            { 
                ShowAuthenticationError(actionContext, ""Authorization required"");
                return;
            }

            if (string.IsNullOrEmpty(authorization.Parameter))
            {
                ShowAuthenticationError(actionContext, ""Missing Jwt Token"");
                return;
            }

            var token = authorization.Parameter;

            var principal = AuthenticateToken(token);
            if (principal == null)
            { 
                ShowAuthenticationError(actionContext, ""Invalid token"");
                return;
            }
            base.OnAuthorization(actionContext);
        }
        private static void ShowAuthenticationError(HttpActionContext filterContext, string message)
        {
            var responseDTO = new ResponseDTO() { Code = 401, Message = message };
            filterContext.Response =
            filterContext.Request.CreateResponse(HttpStatusCode.Unauthorized, responseDTO);
        }
    }
    public class ResponseDTO
    {
        public int Code { get; set; }
        public string Message { get; set; }
    }
</code></pre>

<p>Now in the Unit Test project i have a class and unit test method.</p>

<pre><code>        [TestMethod]
        public void CheckFilter()
        {
            try
            {
                var controller = new ValuesController();
                var controllerContext = new HttpControllerContext();
                var request = new HttpRequestMessage();
                request.Headers.Add(""Authorization"", ""bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InVhbGkiLCJlbWFpbCI6InVhbGlAaW5yZWFjaGNlLmNvbSIsIm5iZiI6MTU2NDY0NjIyMSwiZXhwI"");

                controllerContext.Request = request;
                controller.ControllerContext = controllerContext;

                var result = controller.Get();
                Assert.IsTrue(result.Any());

            }
            catch (Exception ex)
            {
                Assert.Fail();
            }
        }
</code></pre>

<p>I am calling my controller by adding reference of API project into my unit test project. So all controllers are available in the unit test project.</p>

<p>Issue is that when i call the values controller it always return the data. And when i remove the request and header so it is also returning the data but in that case that will be unauthorized.</p>

<p>I think my custom filter is not calling. How should that would be called and authenticate the user.</p>
",https://stackoverflow.com/questions/57308170/unit-test-with-asp-net-web-api-and-customer-filter,"['asp.net-mvc', 'unit-testing', 'authorize-attribute']",1635,True,3,1
How to test custom web component with jest?,"<p>I would like to test some custom web components and use jest.js as test runner (due to its support for ES6).</p>

<p>Chromium supports commands like</p>

<pre><code>window.customElements.define('my-custom-element', MyCustomElementClass);
</code></pre>

<p>to register a custom web component. </p>

<p>However, <code>window.customElements</code> does not seem to be known in the context of jest tests.</p>

<p>As a work around I tried to use <strong>jest in combination with puppeteer and express</strong> to run the <code>customElements</code> part in Chromium.</p>

<p>However, I have difficulties to inject the custom element class <code>TreezElement</code> in the evaluated code:</p>

<p>treezElement.js:</p>

<pre><code>class TreezElement extends HTMLElement {
    connectedCallback () {
      this.innerHTML = 'Hello, World!';
    }
}
</code></pre>

<p>treezElement.test.js:</p>

<pre><code>import TreezElement from '../../src/components/treezElement.js';
import puppeteer from 'puppeteer';
import express from 'express';

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

    let port = 3000;

    let browser;
    let page;
    let element;
    const width = 800;
    const height = 800;

    beforeAll(async () =&gt; {

        const app = await express()                   
                    .use((req, res) =&gt; {                       
                        res.send(
                        `&lt;!DOCTYPE html&gt;
                        &lt;html&gt;            
                            &lt;body&gt;
                            &lt;div id=""root""&gt;&lt;/div&gt;                           
                            &lt;/body&gt;
                        &lt;/html&gt;`
                        )
                    })
                    .listen(port);

        browser = await puppeteer.launch({
          headless: false,
          slowMo: 80,
          args: [`--window-size=${width},${height}`]
        });

        var pages = await browser.pages();
        page = pages[0]; 

        await page.setViewport({ width, height });        

        await page.goto('http://localhost:3000'); 

        element = await page.evaluate(({TreezElement}) =&gt; {
            console.log('TreezElement:')
            console.log(TreezElement);
            window.customElements.define('treez-element', TreezElement);
            var element = document.create('treez-element');
            document.body.appendChild(element);
            return element;           
         }, {TreezElement}); 

    });


    it('TreezElement', ()=&gt;{   

    });    

    afterAll(() =&gt; {
        browser.close();
    });        

});
</code></pre>

<p>Maybe <code>TreezElement</code> is not serializable and therefore <code>undefined</code> is passed to the function. </p>

<p>If I try to import the custom element class <code>TreezElement</code> directly from within the evaluated code ...</p>

<pre><code>element = await page.evaluate(() =&gt; {
            import TreezElement from '../../src/components/treezElement.js';
            console.log('TreezElement:')
            console.log(TreezElement);
            window.customElements.define('treez-element', TreezElement);
            var element = document.create('treez-element');
            document.body.appendChild(element);
            return element;           
         });
</code></pre>

<p>... I get the error</p>

<blockquote>
  <p>'import' and 'export' may only appear at the top level</p>
</blockquote>

<p><strong>=> What is the recommended way to test custom web components with jest?</strong></p>

<p>Some related stuff:</p>

<ul>
<li><p><a href=""https://stackoverflow.com/questions/53463201/web-component-htmlelement-unit-testing"">Web Component / HtmlElement : unit testing</a></p></li>
<li><p><a href=""https://itnext.io/testing-your-javascript-in-a-browser-with-jest-puppeteer-express-and-webpack-c998a37ef887"" rel=""noreferrer"">https://itnext.io/testing-your-javascript-in-a-browser-with-jest-puppeteer-express-and-webpack-c998a37ef887</a></p></li>
<li><p><a href=""https://stackoverflow.com/questions/57379078/how-to-mock-dependencies-for-es6-unit-tests"">How to mock dependencies for ES6 unit tests?</a></p></li>
<li><p><a href=""https://stackoverflow.com/questions/51625029/cant-get-test-coverage-with-jest-puppeteer"">Can&#39;t get test coverage with jest + puppeteer</a></p></li>
<li><p><a href=""https://jestjs.io/docs/en/puppeteer"" rel=""noreferrer"">https://jestjs.io/docs/en/puppeteer</a></p></li>
</ul>
",https://stackoverflow.com/questions/57478484/how-to-test-custom-web-component-with-jest,"['unit-testing', 'jestjs', 'puppeteer', 'web-component']",17899,True,11,5
How to test multiple withLatestFrom store injections in NgRx-Effects?,"<p>In our angular webapp we have some NgRx-effects that use different information from different parts of our store. For this we are using the recommended <code>withLatestFrom</code>-approach:</p>

<pre class=""lang-js prettyprint-override""><code>withLatestFrom(
   this.store.pipe(select(...)),
   this.store.pipe(select(...)),
   ...
)
</code></pre>

<p>While this approach seems to be working fine in production, it feels horrible for unit testing the effects.</p>

<p>For our unit-tests we are currently using jasmine-marbles, jasmine spy-objects and the ngrx MockStore (NgRx 7+). The hard part is to provide the necessary store state, so that the selectors can work properly.</p>

<p><strong>EXAMPLE-EFFECT</strong>, for which we do not have a unit-test:</p>

<pre class=""lang-js prettyprint-override""><code>@Effect()
getStammdatenDetails$: Observable&lt;Action&gt; = this.actions$.pipe(
   ofType(StammdatenItemDetailActionTypes.REQUEST_DETAILS),
   withLatestFrom(
      this.store.pipe(select(fromRoot.getMetadata)),
      this.store.pipe(select(fromRoot.getCustomerId)),
      this.store.pipe(select(fromRoot.getRouterParams))
   ),
   mergeMap(([action, metadata, customerId, params]) =&gt; {
      *effect logic*
   })
);
</code></pre>

<p>Maybe someone here can provide more insight or a useful link to a piece of documentation we are missing?</p>

<p>I would really appreciate any help in regards if there is a convenient method to unit tests such effects, or how to refactor those effects to be more ""testable"" (without moving the problem to another piece of code, which we cannot test afterwards).</p>
",https://stackoverflow.com/questions/55395785/how-to-test-multiple-withlatestfrom-store-injections-in-ngrx-effects,"['angular', 'typescript', 'unit-testing', 'testing', 'ngrx']",2474,True,2,1
How to guarantee same library versions for Compile and Test configurations,"<p>I have a medium-sized <em>sbt</em> project (~20 sub-projects, ~50 direct dependencies, ~400 transitive dependencies). I'm preparing the project to enable unit-testing [0]. I've run into strange problems and noticed that the exact versions used for certain dependencies differ between the <code>Compile</code> and <code>Test</code> targets, i.e. unit tests (<code>sbt test</code>) run with different versions of libraries than the project directly (<code>sbt run</code>).</p>

<p>I produced a diff between the output of <code>sbt Compile/dependencyList</code> [1] and <code>sbt Test/dependencyList</code> and see about 50 dependencies with differing versions. I know that I can use the <code>dependencyOverride</code> settings, but it seems impractical to do manually for hundreds of dependency. I would also have to update that list every time we would like to update our direct dependencies.</p>

<p>What is the intended way to handle this situation? I.e. how can I make sure that I am using the the same versions of dependencies during unit tests as when running in production?</p>

<p>[0]: Better late than never! :)</p>

<p>[1]: <code>dependencyList</code> is a command from <a href=""https://github.com/jrudolph/sbt-dependency-graph"" rel=""nofollow noreferrer"">sbt-dependency-graph</a>.</p>
",https://stackoverflow.com/questions/55686652/how-to-guarantee-same-library-versions-for-compile-and-test-configurations,"['unit-testing', 'dependencies', 'sbt', 'dependency-management']",326,True,2,2
How can I test dates and datetimes in different formats?,"<p>I have a web app that I am unit testing.  I'm trying to test the drf serializers, but the serializers change the format of datetimes, so identical dates formatted differently are failing the test because they're not identical.</p>

<p>I've tried formatting the serializer timeDateField, but all of the strftime formats they use are zero-padded, and my test Users last-login attribute gives the date without zero-padding. I think the solution <em>could</em> be solved the way that the selected answer describes <a href=""https://stackoverflow.com/questions/9525944/python-datetime-formatting-without-zero-padding"">here</a> but that seems a bit sketchy, and ideally, I, as someone who will have to maintain this code, want a cleaner or more pythonic solution.</p>

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

<pre><code>class UserTest(TestCase):

    def setup(self):

        last_login = datetime.datetime(2000, 1, 1, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
        date_joined = datetime.datetime(2019, 2, 2, hour=2, minute=2, second=2, microsecond=2, tzinfo=None)
        birthdate = timezone.now().date()
        renewal = timezone.now().date()

        return User.objects.create(username='test_user', first_name='test_first', last_name='test_last',
                                   email='test_mail', last_login=last_login, date_joined=date_joined,
                                   birthdate=birthdate, gender='U', renewal=renewal)

    def test_user_serializer(self):
        self.u = self.setup()
        serializer = UserSerializer(self.u, many=False)
        data = serializer.data
              .....
    # tests for serialized attributes
        self.assertEquals((data['last_login']), self.u.last_login)  # FAILING THE TEST
</code></pre>

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

<pre><code>class UserSerializer(serializers.ModelSerializer):

    last_login = serializers.DateTimeField
    date_joined = serializers.DateTimeField
    birthdate = serializers.DateField
    renewal = serializers.DateField

    class Meta:
        model = User
        fields = ('__all__')
</code></pre>

<p>Here is the error I am getting:</p>

<pre><code>self.assertEquals(data['last_login'], self.u.last_login)
AssertionError: '2000-01-01T00:00:00Z' != datetime.datetime(2000, 1, 1, 0, 0)
</code></pre>

<p>In the model, the last_login attribute is a dateTimeField.</p>

<p>Should I be trying to change the formats of one of the elements being tested or is there a way to write a test that compares the dates irrespective of format?</p>

<p>Please advise.  Thank you.  </p>
",https://stackoverflow.com/questions/56780926/how-can-i-test-dates-and-datetimes-in-different-formats,"['python', 'unit-testing', 'datetime', 'django-rest-framework', 'django-serializer']",1351,True,2,3
Spring Boot - Mock a POST REST request to an external API,"<p>I have a Spring-Boot 1.5.21 application that serves as a REST gateway between an Angular UI and an external API that provides the data (long story - acts as auth between UI and datasource). A request comes to the Spring-Boot application, it calls the data source API with the request payload.</p>

<p>I am new to Unit Testing for Spring-Boot and am trying to write a test for the POST REST method in the Gateway application that creates a new record (create). I've read a couple of tutorials and other websites detailing how to unit test Spring-Boot APIs but nothing that helps me in my situation.</p>

<p>I want to:</p>

<ul>
<li>Unit test the REST Controller method and check that the @RequestBody is valid</li>
<li>I do not want a record created in the datasource</li>
</ul>

<p>Controller Method:</p>

<pre><code>@PostMapping(value = ""/"" + Constants.API_CHANGE_REQUEST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String submitChangeRequest(@RequestBody ChangeRequestWrapper changeRequestWrapper) {
    logger.info(""API Request: Posting Change Request: "" + changeRequestWrapper.toString());
    return restService.makeApiPost(sharedDataService.buildApiUrlPath(Constants.API_CHANGE_REQUEST), changeRequestWrapper);
}
</code></pre>

<p>AppConfig:</p>

<pre><code>@PropertySource({""classpath:application.properties""})
@Configuration
public class AppConfig {

    @Resource
    private Environment env;

    @Bean
    public RestTemplate restTemplate() {
        RestTemplateBuilder builder = new RestTemplateBuilder();
        return builder
                .setConnectTimeout(Constants.API_TIMEOUT_CONNECT)
                .setReadTimeout(Constants.API_TIMEOUT_READ)
                .basicAuthorization(env.getProperty(""bpm.user""), env.getProperty(""bpm.password""))
                .build();
    }
}
</code></pre>

<p>RestServiceImpl:</p>

<pre><code>@Service
public class RestServiceImpl implements RestService {

    private static final Logger logger = LoggerFactory.getLogger(RestServiceImpl.class);

    @Autowired
    private RestTemplate myRestTemplate;

    @Value(""${bpm.url}"")
    private String restUrl;

    public String getApiUri() {
        return restUrl;
    }

    public String makeApiCall(String payload) /*throws GradeAdminException */{
        logger.info(""Implementing API call."");
        logger.debug(""userApi: "" + payload);
        return myRestTemplate.getForObject(payload, String.class);
    }

    public String makeApiPost(String endpoint, Object object) {
        logger.info(""Implementing API post submission"");
        logger.debug(""userApi endpoint: "" + endpoint);
        return myRestTemplate.postForObject(endpoint, object, String.class);
    }
}
</code></pre>

<p>SharedDataServiceImpl:</p>

<pre><code>@Service
public class SharedDataServiceImpl implements SharedDataService {

    @Autowired
    private RestService restService;

    @Override
    public String buildApiUrlPath(String request) {
        return buildApiUrlPath(request, null);
    }

    @Override
    public String buildApiUrlPath(String request, Object parameter) {
        String path;
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(restService.getApiUri());

        if (parameter != null) {
            builder = builder.path(getApiPath(request) + ""/{object}"");
            UriComponents buildPath = builder.buildAndExpand(parameter);
            path = buildPath.toUriString();
        } else {
            builder = builder.path(getApiPath(request));
            path = builder.build().toUriString();
        }

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

<p>What I've done for the GET methods:</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(ClientDataRequestController.class)
@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigWebContextLoader.class)
public class ClientDataRequestControllerTest {

    @Autowired
    private MockMvc mvc;

    @Before
    public void setUp() {

    }

    @Test
    public void test_no_endpoint() throws Exception {
        this.mvc.perform(get(""/"")).andExpect(status().isNotFound()).andReturn();
    }

    @Test
    public void test_controller_no_endpoint() throws Exception {
        this.mvc.perform(get(""/api/"")).andExpect(status().isOk()).andReturn();
    }

    @Test
    public void test_getStudent_valid_parameters() throws Exception {
        this.mvc.perform(get(""/api/students/?pidm=272746"")).andExpect(status().isOk()).andReturn();
    }
}
</code></pre>

<p>I would greatly appreciate some assistance with this.</p>

<p><strong>Solution:</strong></p>

<p>I've since found <a href=""https://stackoverflow.com/questions/20504399/testing-springs-requestbody-using-spring-mockmvc"">this SO answer</a> that has solved my problem.</p>
",https://stackoverflow.com/questions/56738006/spring-boot-mock-a-post-rest-request-to-an-external-api,"['java', 'rest', 'spring-boot', 'junit', 'mocking']",7098,True,2,1
Making covariant interface backward compatible,"<p>We have an interface to deal with DAL with pretty simple definition:</p>

<pre><code>interface IRepository&lt;T&gt; : IQueriable&lt;T&gt; // so we can read data from database
{
   Save(T document); // dozen of methods here
} 
</code></pre>

<p>Mostly we use two implementations: real version and in memory version for unit testing. Here is declarations of one of class:</p>

<pre><code>public RealRepository : IRepository&lt;AccountEntity&gt; { ... } 
// typical IOC usage
services.AddSingleton&lt;IRepository&lt;AccountEntity&gt;, RealRepository&lt;AccountEntity&gt;&gt;();
</code></pre>

<p>Now we are working to spin off for main codebase to custom version of project and we need custom fields in data and occassional custom behavior in repository. Most of classes are fine with base implementation but others would require specific implementation. So my goal is to get to following services in:</p>

<pre><code>var repository = new RealRepository&lt;CustomAccountEntity&gt;();
services.AddSingleton(IRepository&lt;AccountEntity&gt;, repository);
// for new classes
services.AddSingleton(IRepository&lt;CustomAccountEntity&gt;, repository);
</code></pre>

<p>I tried to add <code>out T</code> to IRepository but I am using T in input parameters and this gave compile time ""Invalid variance"" error.</p>

<p>I can see a solution by adding second type parameter to interface so it looks like:</p>

<pre><code>IRepository&lt;TBase, out TChild&gt; : IQueriable&lt;TChild&gt; {
    Save (T document);
}
</code></pre>

<p><strong>Finally, Question: How can make change 100% backward compatible?</strong></p>

<p>What I tried: </p>

<ol>
<li>Add <code>IRepository&lt;T&gt;: IRepository&lt;T,T&gt;</code> -> complies, but <code>RealRepository</code> is not implementing <code>IRepository</code> anymore.</li>
<li>Add 2 interfaces in implementation: <code>public class RealRepository&lt;TBase, TChild&gt;: IRepository&lt;TBase, TChild&gt;, IRepository&lt;TChild&gt;</code> but this gives compliation error 'cannot implement both ... and ... because they may unify for some type parameter substitutions'</li>
</ol>
",https://stackoverflow.com/questions/55150924/making-covariant-interface-backward-compatible,"['c#', '.net', 'generics', 'interface', 'covariance']",58,True,2,1
Why use Dapper if I don&#39;t want to write my query on sql,"<p>The project I am working on has 90% of the business logic in stored procedure. I looked at Dapper as a possible path to move some of these business rules to the Application layer. The benefits to me are evident, in that I can do unit testing etc etc. </p>

<p>Dapper seems to help with mapping objects, to classes through sql queries. This is not enough for me, because I'd like to build my queries into an application class like service, and then unit test them before I go to my Repository( aka Dapper). 
I'd expect the ORM to translate my query into sql. Dapper seams not to be meant to be used this way. So I wonder what is the point if I still have to build all my business logic in sql. </p>

<p>My question, is do I need a different ORM like hibernate? I guess I am looking for some guidance on how to evaluate this tool. </p>
",https://stackoverflow.com/questions/54541326/why-use-dapper-if-i-dont-want-to-write-my-query-on-sql,['orm'],1614,True,2,2
FakeItEasy - Is it possible to test constraints asynchronously (i.e. MatchesAsync)?,"<p>I've run into difficulty testing System.Net.Http.HttpClient with FakeItEasy.  Consider this scenario:</p>

<pre><code>//Service that consumes HttpClient
public class LoggingService
{
    private readonly HttpClient _client;

    public LoggingService(HttpClient client)
    {
        _client = client;
        _client.BaseAddress = new Uri(""http://www.example.com"");
    }

    public async Task Log(LogEntry logEntry)
    {
        var json = JsonConvert.SerializeObject(logEntry);
        var httpContent = new StringContent(json, Encoding.UTF8, ""application/json"");
        await _client.PostAsync(""/api/logging"", httpContent);
    }
}

public class LogEntry
{
    public string MessageText { get; set; }
    public DateTime DateLogged { get; set; }
}
</code></pre>

<p><strong>Unit Testing</strong></p>

<p>From a unit testing perspective, I want to verify that HttpClient posts the specified logEntry payload to the appropriate URL (<a href=""http://www.example.com/api/logging"" rel=""nofollow noreferrer"">http://www.example.com/api/logging</a>).  (<em>Side Note: I can't test the HttpClient.PostAsync() method directly because my service uses the concrete implementation of HttpClient and Microsoft does not provide an interface for it.  However, I can create my own HttpClient that uses a FakeMessageHandler (below) as a dependency, and inject that into the service for testing purposes.  From there, I can test DoSendAsync()</em></p>

<pre><code>//Helper class for mocking the MessageHandler dependency of HttpClient
public abstract class FakeMessageHandler : HttpMessageHandler
{
    protected sealed override Task&lt;HttpResponseMessage&gt; SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        return DoSendAsync(request);
    }

    public abstract Task&lt;HttpResponseMessage&gt; DoSendAsync(HttpRequestMessage request);
}
</code></pre>

<p>In theory, I should be able to use the Matches() method in FakeItEasy to write a custom matching function.  This would look something like this:</p>

<pre><code>//NUnit Test
[TestFixture]
public class LoggingServiceTests
{
    private LoggingService _loggingService;
    private FakeMessageHandler _fakeMessageHandler;
    private HttpClient _httpClient;

    [SetUp]
    public void SetUp()
    {
        _fakeMessageHandler = A.Fake&lt;FakeMessageHandler&gt;();
        _httpClient = new HttpClient(_fakeMessageHandler);
        _loggingService = new LoggingService(_httpClient);
    }

    [Test]
    public async Task Logs_Error_Successfully()
    {
        var dateTime = new DateTime(2016, 11, 3);
        var logEntry = new LogEntry
        {
            MessageText = ""Fake Message"",
            DateLogged = dateTime
        };
        await _loggingService.Log(logEntry);

        A.CallTo(() =&gt; _fakeMessageHandler.DoSendAsync(
            A&lt;HttpRequestMessage&gt;.That.Matches(
                m =&gt; DoesLogEntryMatch(""Fake Message"", dateTime, HttpMethod.Post,
                    ""https://www.example.com/api/logging"", m)))
        ).MustHaveHappenedOnceExactly();
    }


    private bool DoesLogEntryMatch(string expectedMessageText, DateTime expectedDateLogged,
        HttpMethod expectedMethod, string expectedUrl, HttpRequestMessage actualMessage)
    {
        //TODO: still need to check expectedMessageText and expectedDateLogged from the HttpRequestMessage content
        return actualMessage.Method == expectedMethod &amp;&amp; actualMessage.RequestUri.ToString() == expectedUrl;
    }


}
</code></pre>

<p>Checking the URL and the HttpMethod is easy enough (as demonstrated above).  But, in order to check the payload, I need to check the content of the HttpRequestMessage.  Here's where it gets tricky.  The only way I've found to read the content of an HttpRequestMessage is to use one of the built-in async methods (i.e. ReadAsStringAsync, ReadAsByteArrayAsync, ReadAsStreamAsync, etc.)  As far as I can tell, FakeItEasy does not support async/await operations inside of the Matches() predicate.  Here's what I tried:</p>

<ol>
<li><p>Convert DoesLogEntryMatch() method to async, and await the ReadAsStringAsync() call <strong>(DOES NOT WORK)</strong></p>

<pre><code>    //Compiler error - Cannot convert async lambda expression to delegate type 'Func&lt;HttpRequestMessage, bool&gt;'.
    //An async lambda expression may return void, Task or Task&lt;T&gt;,
    //none of which are convertible to 'Func&lt;HttpRequestMessage, bool&gt;'
    A.CallTo(() =&gt; _fakeMessageHandler.DoSendAsync(
        A&lt;HttpRequestMessage&gt;.That.Matches(
            async m =&gt; await DoesLogEntryMatch(""Fake Message"", dateTime, HttpMethod.Post,
                ""http://www.example.com/api/logging"", m)))
    ).MustHaveHappenedOnceExactly();


private async Task&lt;bool&gt; DoesLogEntryMatch(string expectedMessageText, DateTime expectedDateLogged,
    HttpMethod expectedMethod, string expectedUrl, HttpRequestMessage actualMessage)
{
    var message = await actualMessage.Content.ReadAsStringAsync();
    var logEntry = JsonConvert.DeserializeObject&lt;LogEntry&gt;(message);

    return logEntry.MessageText == expectedMessageText &amp;&amp;
           logEntry.DateLogged == expectedDateLogged &amp;&amp;
    actualMessage.Method == expectedMethod &amp;&amp; actualMessage.RequestUri.ToString() == expectedUrl;
}
</code></pre></li>
<li><p>Leave DoesLogEntryMatch as a non-async method, and don't await ReadAsStringAsync().  This seems to work when I tested it, but I have read that doing this could cause deadlocks in certain situations.</p>

<pre><code>private bool DoesLogEntryMatch(string expectedMessageText, DateTime expectedDateLogged,
    HttpMethod expectedMethod, string expectedUrl, HttpRequestMessage actualMessage)
{
    var message = actualMessage.Content.ReadAsStringAsync().Result;
    var logEntry = JsonConvert.DeserializeObject&lt;LogEntry&gt;(message);

    return logEntry.MessageText == expectedMessageText &amp;&amp;
           logEntry.DateLogged == expectedDateLogged &amp;&amp;
    actualMessage.Method == expectedMethod &amp;&amp; actualMessage.RequestUri.ToString() == expectedUrl;
}
</code></pre></li>
<li><p>Leave DoesLogEntryMatch as a non-async method, and await ReadAsStringAsync() inside of a Task.Run().  This spawns a new thread that will await the result, but allows the original method call to run synchronously.  From what I've read, this is the only ""safe"" way to call an asynchronous method from a synchronous context (i.e. no deadlocks).  This is what I wound up doing.</p>

<pre><code>private bool DoesLogEntryMatch(string expectedMessageText, DateTime expectedDateLogged,
    HttpMethod expectedMethod, string expectedUrl, HttpRequestMessage actualMessage)
{
    var message = Task.Run(async () =&gt; await actualMessage.Content.ReadAsStringAsync()).Result;
    var logEntry = JsonConvert.DeserializeObject&lt;LogEntry&gt;(message);

    return logEntry.MessageText == expectedMessageText &amp;&amp;
           logEntry.DateLogged == expectedDateLogged &amp;&amp;
    actualMessage.Method == expectedMethod &amp;&amp; actualMessage.RequestUri.ToString() == expectedUrl;
}
</code></pre></li>
</ol>

<p>So, I got this working, but it seems like there should be a better way of doing this in FakeItEasy.  Is there something equivalent to a MatchesAsync() method that would take a predicate that supports async/await?  </p>
",https://stackoverflow.com/questions/55008666/fakeiteasy-is-it-possible-to-test-constraints-asynchronously-i-e-matchesasyn,"['c#', 'asynchronous', 'async-await', 'dotnet-httpclient', 'fakeiteasy']",2617,True,3,1
Writing automated test cases for electron app build with electron react boilerplate,"<p>I have just started to build a cross-platform app with electron along with react for that purpose, I have used electron react boilerplate for simplicity and set the standard to my app.</p>

<p>Where i face problem in writing some automated test cases is, there is already a test folder inside application root, which basically does unit testing and component testing. As it is said that, it is best practice to use spectron along with mocha and chai. What is the best possible way to set up them for automated testing?</p>

<p>I have already installed spectron with mocha and used the testing code provided in (<a href=""https://github.com/electron/spectron#application-api"" rel=""nofollow noreferrer"">https://github.com/electron/spectron#application-api</a>) official documentation of the electron.But where i was stuck is in providing path i.e.   </p>

<pre><code>args: [path.join(__dirname, '..')] 
</code></pre>

<p>As it supposes the app architecture like:</p>

<pre><code> |__ my project
      |__ ...
      |__ main.js
      |__ package.json
      |__ index.html
      |__ ...
      |__ test
         |__ spec.js  &lt;- You are here! ~ Well you should be.
</code></pre>

<p>but i don't have this architecture, instead, have the default architecture of electron-react boilerplate,my question here is how can i arrange this path for electron-react boilerplate?</p>
",https://stackoverflow.com/questions/56182770/writing-automated-test-cases-for-electron-app-build-with-electron-react-boilerpl,"['reactjs', 'automated-tests', 'electron']",794,True,2,1
Best Practices for Unit Testing Builder Objects?,"<p>There is great debate about whether or not setters/getters should be unit tested.</p>

<p>Example
<a href=""https://stackoverflow.com/questions/6197370/should-unit-tests-be-written-for-getter-and-setters"">Should unit tests be written for getter and setters?</a></p>

<p>I believe that builder objects fall within the same conversation. I want to know best practices for unit testing a builder object. Here are my thoughts.</p>

<p>i. confirm that builder object can be created</p>

<p>ii. confirm that output reflects input</p>

<p>iii. confirm that omitted constructs will throw exception (if they are required)</p>

<p>Additionally, if the builder object is required for instantiating another object, does it make sense to also create a test to confirm that the second object instantiates with given builder? Any critiques on what I am missing or should omit is appreciated.</p>

<pre><code>@RunWith(AndroidJUnit4.class)
public class MyBuilderTest {

    private Context mContext;
    private ApiClient mApiClient;
    private Profile mProfileBuilder;
    private ProfilePojo mProfileSampleResponse;

    @Before
    public void setUp() {
        mContext = InstrumentationRegistry.getTargetContext();
        mProfileSampleResponse= new Gson().fromJson(Utils.getLocalJsonFile(mContext,
                R.raw.profile_info), ProfilePojo.class);
    }

    @Test
    public void checkLocalProfileResponse() {
        assertNotNull(mProfileSampleResponse);
    }

    @Test
    public void checkProfileBuilder() {
        mProfileBuilder  = new Profile.ProfileBuilder()
                .setFirstName(mProfileSampleResponse.firstName)
                .setLastName(mProfileSampleResponse.lastName)
                .isVerified(mProfileSampleResponse.isVerified)
                .create();

        assertNotNull(mProfileBuilder);
        assertNotNull(mProfileBuilder.getFirstName());
        assertNotNull(mProfileBuilder.getLastName());

        assertEquals(mProfileSampleResponse.isVerified, mProfileBuilder.getIsVerified);
        assertEquals(mProfileSampleResponse.firstName, mProfileBuilder.getFirstName);
        assertEquals(mProfileSampleResponse.lastName, mProfileBuilder.getLastName);
    }

    @Test
    public void checkApiClientBuilder() {
        mApiClient= new ApiClient(mContext, mProfileBuilder);

        assertNotNull(mApiClient);
    }

}
</code></pre>

<p>In my case, I also need to test request and responses. The profile information I build with the ProfileBuilder can be passed into the ApiClient and the ApiClient will make request for me. Should all of this be inside of one test class?</p>
",https://stackoverflow.com/questions/56658417/best-practices-for-unit-testing-builder-objects,"['java', 'android', 'unit-testing', 'junit']",208,False,2,0
How to test redux-saga&#39;s generator that calls external api?,"<p>I'm complete beginner when it comes to writing tests, yet I have been given task to test some api's implementation, which is done using redux and redux-saga. The scenario is that user fills prepared form with his username, password and my generator function ""authenticateUser"" calls proper endpoint from api (api handlers were automatically generated from Swagger, and are imported from private registry), to create token and check whether user exists in database. If so, token is saved to session/local storage and store is updated with corresponding values. </p>

<pre><code>
import { userAuthenticated, userAuthenticationRejected } from ""../actions/user"";
import { call, put } from ""redux-saga/effects"";
import createApi from ""@my-module"";

export function* authenticateUser(action) {
  const myApi = yield call(createApi, {
    cors: true,
    securityHandlers: {
      Basic: () =&gt; true,
      Bearer: () =&gt; true
    }
  });

  try {
    const response = yield call(myApi.token_create, {
      data: {
        username: action.payload.username,
        password: action.payload.password
      }
    });
    if (response.status === 200) {
      const body = yield call([response, ""json""]);
      const accessToken = body.access;
      window.sessionStorage.setItem(""accessToken"", accessToken);
      if (action.payload.persistAuthenticationToken) {
        window.localStorage.setItem(""accessToken"", accessToken);
      }

      yield put(
        userAuthenticated({
          username: action.payload.username,
          accessToken
        })
      );
    } else {
      throw new Error(""Unauthorized"");
    }
  } catch (error) {
    yield put(userAuthenticationRejected());
  }
}
</code></pre>

<p>I got completely lost while reading about testing approaches. I've tried simple unit testing with consecutive ""generator.next().value"" but after first yield it couldn't even get into ""try"" block and throws out ""undefined"" sooner than expected. </p>

<pre><code>test(""User authentication"", () =&gt; {
  const action = {
    payload: {
      username: ""test"",
      password: ""test""
    }
  };
  const generator = cloneableGenerator(authenticateUser)(action);
  console.log(generator.next().value);

  // {
  //   '@@redux-saga/IO': true,
  //   combinator: false,
  //   type: 'CALL',
  //   payload: {
  //     context: null,
  //     fn: [Function: createApi],
  //     args: [ [Object] ]
  //   }
  // }

  console.log(generator.next().value);

  // {
  //   '@@redux-saga/IO': true,
  //   combinator: false,
  //   type: 'PUT',
  //   payload: {
  //     channel: undefined,
  //     action: { type: 'USER_AUTHENTICATION_REJECTED' }
  //   }
  // }

  console.log(generator.next().value);

  // undefined

});
</code></pre>

<p>When I looked at integration tests, which seems to be preferred way, I couldn't just simply transfer relatively straightforward examples to my specific case. </p>

<p>I'll appreciate any help, because I just don't know where to start.</p>
",https://stackoverflow.com/questions/57948819/how-to-test-redux-sagas-generator-that-calls-external-api,"['javascript', 'reactjs', 'redux', 'jestjs', 'redux-saga']",2016,True,2,1
How to mock database results in service layer unit test?,"<p>I'm new to Mocking things in Unit tests and I've started experimenting with Mockito. Is the following possible using Mockito?</p>

<p>I am trying to write unit tests for a layered webservice application. At this point I am testing the Service layer, which calls the DAO layer to acquire data from the database.
I need to mock the database results so that I'm not making real update calls to the database every time my unit tests run.</p>

<p>I was thinking of doing this by mocking the DAO object that my service layer calls, but I need to do that without changing the source code. If I'm currently unit testing the service layer, how can I make it use a mocked DAO layer?</p>

<p>My Unit Test looks like this:</p>

<pre><code>@Test
public void testUpdate() {
RequestObject request = new RequestObject();
request.setEntityId(1234);
request.setLob('testLOB');
ResponseObject response = service.updateMember(request);
}
</code></pre>

<p>My Service method:</p>

<pre><code>public ResponseObject updateMember(RequestObject request) {
ResponseObject result = DAO.updateMember(request);
}
</code></pre>

<p>Is it possible to Mock the DAO without mocking the Service in this instance? 
EDIT: I am using Maven for dependency management.</p>
",https://stackoverflow.com/questions/57510833/how-to-mock-database-results-in-service-layer-unit-test,"['java', 'unit-testing', 'jdbc', 'junit', 'mockito']",3766,True,2,3
Proper way to conduct or quit a unit test based on a real-time value,"<p>I have a class that checks if the current day of the week is Wednesday. It looks like this:</p>

<pre><code>public class Wednesday
{
    public string IsWednesday()
    {
        if (DateTime.Now.DayOfWeek == DayOfWeek.Wednesday)
        {
            return ""It’s Wednesday"";
        }
        else
        {
            return ""It’s not Wednesday"";
        }
    }
}
</code></pre>

<p>Don't worry about the return type, I know that it's bad in this particular example to return a magic string. We're focused on its purpose, not implementation.</p>

<p>I would love to cover it with unit tests for both cases of the current weekday being Wednesday and being anything but Wednesday.</p>

<p>I am new to unit testing and I'm wondering what the best solution would be in this example.</p>

<p>Right now, I'm using VS2019 with MS Test V2. I've tested both scenarios like this:</p>

<pre><code>[TestClass]
public class WednesdayTests
{
    [TestMethod]
    public void IsWednesday_CurrentWeekDayIsWednesday_ReturnsItsWedndesday()
    {
        if (!(DateTime.Now.DayOfWeek == DayOfWeek.Wednesday))
        {
            return; 
        }

        // Arrange
        Wednesday wednesdayObj = new Wednesday();

        // Act
        string result = wednesdayObj.IsWednesday();

        // Assert
        Assert.AreEqual(""It’s Wednesday"", result);
    }

    [TestMethod]
    public void IsWednesday_CurrentWeekDayIsNotWednesday_ReturnsItsNotWednesday()
    {
        if (!(DateTime.Now.DayOfWeek != DayOfWeek.Wednesday))
        {
            return;
        }

        Wednesday wednesdayObj = new Wednesday();

        string result = wednesdayObj.IsWednesday();

        Assert.AreEqual(""It’s not Wednesday"", result);
    }
}
</code></pre>

<p>Is it considered OK to return out of a test method when some condition is not met, like in my case?</p>

<p>Or is there something inherently wrong with my solution?</p>

<p>Glad to hear any suggestions from experienced software developers!</p>

<p>P.S. Just noticed that the test will only be conducted if it's actually Wendesday :) Wow, that's for sure is not the solution!</p>
",https://stackoverflow.com/questions/58249734/proper-way-to-conduct-or-quit-a-unit-test-based-on-a-real-time-value,"['c#', 'visual-studio', 'unit-testing', 'mstest']",184,True,2,2
Edit method at runtime in .Net Core C#,"<p>I'm working on a unit testing framework and part of that is intercepting calls to methods. I had a prototype using pointer manipulation on the pointers in <code>MethodBase.MethodHandle</code> but in some cases it would stop working depending on if the debugger was attached or not and in other cases it wouldn't work with functions (had it working for Actions though).</p>

<p>I suspect pointer manipulation is still a possible option but I don't know the memory layout or anything.</p>

<p>The fallback option I came up with is having the test method call my function with the function they want to call and then I generate a dynamic method, copying the IL and altering call instructions to call my methods instead. But it's not a great solution.</p>

<p>I looked through tens of sources but these are the ones that got me closest:</p>

<ul>
<li><a href=""https://stackoverflow.com/a/36415711/2350981"">https://stackoverflow.com/a/36415711/2350981</a></li>
<li><a href=""https://github.com/pardeike/Harmony"" rel=""nofollow noreferrer"">https://github.com/pardeike/Harmony</a> (uses pointer change in source code)</li>
</ul>

<p>How do I dynamically edit/wrap a method at runtime?</p>
",https://stackoverflow.com/questions/57219143/edit-method-at-runtime-in-net-core-c,"['c#', 'pointers', 'reflection']",264,False,2,0
How can you verify a method with a specific NSpecification parameter in C# unit tests?,"<p>I am currently writing unit tests for a CommandHandler.
I use Moq 4.12.0 and xUnit 2.4.1 for the tests.
I wanted to verify whether that a method was called with a certain <a href=""https://github.com/jnicolau/NSpecifications"" rel=""nofollow noreferrer"">NSpecification</a>. </p>

<p>I'm pretty new in the unit-testing world.</p>

<p>This is the CommandHandler:</p>

<pre class=""lang-cs prettyprint-override""><code>public class DeleteAlarmCodesCommandHandler : IRequestHandler&lt;DeleteAlarmCodesCommand, CommandResult&lt;IEnumerable&lt;AlarmCode&gt;&gt;&gt;
    {
        private readonly Domain.Model.IAlarmCodeRepository _alarmCodeRepository;

        public DeleteAlarmCodesCommandHandler(
            Domain.Model.IAlarmCodeRepository alarmCodeRepository)
        {
            _alarmCodeRepository = alarmCodeRepository;
        }

        public async Task&lt;CommandResult&lt;IEnumerable&lt;AlarmCode&gt;&gt;&gt; Handle(DeleteAlarmCodesCommand request, CancellationToken cancellationToken)
        {            
            ASpec&lt;Domain.Model.AlarmCode&gt; spec = Spec&lt;Domain.Model.AlarmCode&gt;.Any;

            if (request.AlarmId != null)
            {
                spec &amp;= Domain.Model.AlarmCodeSpecifications.ForAlarmId(request.AlarmId);
            }

            if (request.LanguageISO != null)
            {
                spec &amp;= Domain.Model.AlarmCodeSpecifications.ForLanguageISO(request.LanguageISO);
            }

            try
            {
                var alarmCodes = await _alarmCodeRepository.DeleteAsync(spec);
                await _alarmCodeRepository.SaveAsync();

                return new CommandResult&lt;IEnumerable&lt;AlarmCode&gt;&gt;(alarmCodes.Select(x =&gt; x.ToViewModel()));
            }
            catch (Domain.ApiDomainException ex)
            {
                return new CommandResult&lt;IEnumerable&lt;AlarmCode&gt;&gt;(ApiErrors.FromException(ex));
            }
        }
    }
</code></pre>

<p>And this is my unit test to check whether the DeleteAsync() is called with the specification.</p>

<pre class=""lang-cs prettyprint-override""><code>[Fact]
public async Task Should_DeleteWithAlarmIdOne_WhenCalledWitParameterAlarmIdOne()
{
    // Arrange
    var repo = new Mock&lt;IAlarmCodeRepository&gt;();
    var command = new DeleteAlarmCodesCommand() { AlarmId = 1 };

    var commandHandler = new DeleteAlarmCodesCommandHandler(repo.Object);

    // Act
    var result = await commandHandler.Handle(command, It.IsAny&lt;CancellationToken&gt;());

    var spec = Spec&lt;AlarmCode&gt;.Any &amp; AlarmCodeSpecifications.ForAlarmId(command.AlarmId);

   // Assert            
   repo.Verify(x =&gt; x.DeleteAsync(spec), Times.Once);
   repo.Verify(x =&gt; x.SaveAsync(), Times.Once);
}
</code></pre>

<p>The problem is that the reference to both objects are different, as they are created when they are needed. So Moq sees them as completely different objects.
Because when I run the test, I get the following result in the result pane.</p>

<pre><code>   Duration: 182 ms

  Message: 
    Moq.MockException : 
    Expected invocation on the mock once, but was 0 times: x =&gt; x.DeleteAsync(x =&gt; (True AndAlso (Convert(Convert(x.AlarmId, Int32), Nullable`1) == Convert(value(Services.Domain.Model.AlarmCodeSpecifications+&lt;&gt;c__DisplayClass0_0).alarmId, Nullable`1))))

    Performed invocations:

       Mock&lt;IAlarmCodeRepository:1&gt; (x):

          IAlarmCodeRepository.DeleteAsync(x =&gt; (True AndAlso (Convert(Convert(x.AlarmId, Int32), Nullable`1) == Convert(value(Services.Domain.Model.AlarmCodeSpecifications+&lt;&gt;c__DisplayClass0_0).alarmId, Nullable`1))))
          IRepository`1.SaveAsync()

  Stack Trace: 
    Mock.Verify(Mock mock, LambdaExpression expression, Times times, String failMessage)
    Mock`1.Verify[TResult](Expression`1 expression, Func`1 times)
    DeleteAlarmCodesCommandHandler_Handle.Should_DeleteWithAlarmIdOne_WhenCalledWitParameterAlarmIdOne() line 46
    --- End of stack trace from previous location where exception was thrown ---
</code></pre>

<p>Is there a way with Moq to verify calls with complex objects, like the Spec.</p>

<p>Or how can I test this better?</p>

<p><strong>Update</strong></p>

<p>This is the definition of IAlarmCodeRepository.</p>

<pre class=""lang-cs prettyprint-override""><code> public interface IAlarmCodeRepository : IRepository&lt;AlarmCode&gt;
    {
        IUnitOfWork UnitOfWork { get; }

        Task AddAsync(AlarmCode entity);

        Task&lt;AlarmCode&gt; GetOneAsync(int id);

        Task&lt;AlarmCode&gt; GetOneAsync(ASpec&lt;AlarmCode&gt; spec);

        Task&lt;IEnumerable&lt;AlarmCode&gt;&gt; FindAsync(ASpec&lt;AlarmCode&gt; spec);

        Task&lt;bool&gt; Exists(ASpec&lt;AlarmCode&gt; spec);

        Task&lt;IEnumerable&lt;AlarmCode&gt;&gt; DeleteAsync(ASpec&lt;AlarmCode&gt; spec);

        Task&lt;AlarmCode&gt; DeleteOne(int id);

        Task&lt;IEnumerable&lt;short&gt;&gt; GetDistinctAlarmIds();
    }
</code></pre>

<pre><code>public interface IRepository&lt;T&gt;
         where T : IAggregateRoot
    {
        Task SaveAsync();
    }
</code></pre>

<pre><code> public async Task SaveAsync()
        {
            await UnitOfWork.CommitAsync();
        }
</code></pre>

<p>This are the AlarmSpecifications.</p>

<pre class=""lang-cs prettyprint-override""><code> public static class AlarmCodeSpecifications
    {
        public static ASpec&lt;AlarmCode&gt; ForAlarmId(short? alarmId)
        {
            return new Spec&lt;AlarmCode&gt;(o =&gt; o.AlarmId == alarmId);
        }
    }
</code></pre>

<p>Spec and ASpec comes from the NSpecifications library on <a href=""https://github.com/jnicolau/NSpecifications"" rel=""nofollow noreferrer"">https://github.com/jnicolau/NSpecifications</a> :
<a href=""https://github.com/jnicolau/NSpecifications/blob/master/Nspecifications/ASpec.cs"" rel=""nofollow noreferrer"">https://github.com/jnicolau/NSpecifications/blob/master/Nspecifications/ASpec.cs</a></p>
",https://stackoverflow.com/questions/58393570/how-can-you-verify-a-method-with-a-specific-nspecification-parameter-in-c-unit,"['c#', 'unit-testing', 'moq', 'xunit']",425,True,2,1
Catch segfault from inside arm-none-eabi-gdb target sim?,"<p>I wish to execute automated unit tests of my embedded libraries using arm-none-eabi-gdb simulator. I have a problem, that invalid memory access causes nothing in the simulator, while it causes segmentation faults or hard fault exceptions in real-world.</p>

<p>I have a following small program saved as <code>ub.c</code>:</p>

<pre><code>int main() { *(volatile int*)(void*)0 = 42; }
</code></pre>

<p>I compile using:</p>

<pre><code>arm-none-eabi-gcc -specs=nosys.specs ub.c -o ub.elf
</code></pre>

<p>And then execute</p>

<pre><code>arm-none-eabi-gdb ub.elf
</code></pre>

<p>Inside gdb I execute commands:</p>

<pre><code>target sim
load
break exit
run
</code></pre>

<p>The store to NULL seems to completely ignored. You can even set a <code>break main</code> and with <code>si</code> step to execute the instruction <code>str   r2, [r3]</code> with <code>r3=0</code> and <code>r2=42</code>. Nothing happens. I wish on gdb simulator there would be some anything like ""exception/seg fault/branch to hard fault vector or anywhere"" that I can inspect/handle in gdb to automate unit testing. </p>

<p>Is there a way to enable the ""hard fault exception"" in gdb target simulator?<br>
Is there any way I can ""trap"" invalid memory access, unaligned memory access, similar in arm-none-eabi-gdb with simulator target?</p>

<p>Btw, I use Arch Linux 4.20.6 with arm-none-eabi-gcc 8.2.1. </p>
",https://stackoverflow.com/questions/55948687/catch-segfault-from-inside-arm-none-eabi-gdb-target-sim,"['gcc', 'arm', 'gdb']",135,False,2,0
Unit test IBackgroundJobClient.Schedule,"<p>I am using Hangfire to schedule some jobs. All my jobs have a schedule date, so I'm using Schedule static extension method </p>

<pre><code>public static string Schedule([NotNull] this IBackgroundJobClient client, [InstantHandle][NotNull] Expression&lt;Action&gt; methodCall, DateTimeOffset enqueueAt);
</code></pre>

<p>I want to unit test my methods, so that I can check that Hangfire is actually being triggered.</p>

<p>To do so, I've followed Hangfire's documentation on unit testing (<a href=""https://docs.hangfire.io/en/latest/background-methods/writing-unit-tests.html"" rel=""nofollow noreferrer"">https://docs.hangfire.io/en/latest/background-methods/writing-unit-tests.html</a>) which suggests mocking <code>IBackgroundJobClient</code> and verifying on the only public Create method it has: </p>

<pre><code>string Create([NotNull] Job job, [NotNull] IState state);
</code></pre>

<p>But I can see that for Schedule invocations, this is not being called, another overload that is not public is being called instead, so I get the following error:</p>

<pre><code>Message: Moq.MockException : 
Expected invocation on the mock at least once, but was never performed: x =&gt; x.Create(It.IsAny&lt;job&gt;(), It.IsAny&lt;enqueuedstate&gt;())
No setups configured.

Performed invocations: 
IBackgroundJobClient.Create(JobService.TaskFunction, ScheduledState)
</code></pre>

<p>Nevertheless, I've made an attempt with <code>Enqueue</code> method, and that seems to work with the mock. But I need to use <code>Schedule</code>. </p>

<p>Another option would be to assert on the overload it is actually calling</p>

<pre><code>public static string Create([NotNull] this IBackgroundJobClient client, [InstantHandle][NotNull] Expression&lt;Action&gt; methodCall, [NotNull] IState state);
</code></pre>

<p>But since it's an extension method, that's not a valid approach for Moq.</p>

<p><code>Message: System.NotSupportedException : Invalid verify on an extension method: x =&gt; x.Create(It.IsAny&lt;Expression&lt;Action&gt;&gt;(), It.IsAny&lt;EnqueuedState&gt;())</code></p>

<p>So how can I unit test Hangfire for <code>Schedule</code> method?</p>
",https://stackoverflow.com/questions/55618267/unit-test-ibackgroundjobclient-schedule,"['c#', 'unit-testing', 'moq', 'hangfire']",2291,True,2,1
SQLite AUTOINCREMENT non-primary key column,"<p>I have the following SQLite table:</p>

<pre><code>CREATE TABLE podcast_search (
        _id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 
        search TEXT NOT NULL UNIQUE
)
</code></pre>

<p>Whenever a user inserts/updates a row in the table, I want to sort that row at the end of the table. Thus, if I insert the following values:</p>

<pre><code>_id | search | sort
===================
  1 | foo    | 1
  2 | bar    | 2
  3 | quiz   | 3
</code></pre>

<p>And then later update the <code>1</code> row from <code>foo</code> to <code>foo2</code>, the values should look like:</p>

<pre><code>_id | search | sort
===================
  2 | bar    | 2
  3 | quiz   | 3
  1 | foo2   | 4
</code></pre>

<p>I've implemented this thusly:</p>

<pre><code>CREATE TABLE podcast_search (
        _id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 
        search TEXT NOT NULL UNIQUE, 
        update_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
CREATE TRIGGER update_date_update_trigger
    AFTER UPDATE ON podcast_search FOR EACH ROW
        BEGIN
            UPDATE podcast_search
                SET update_date = CURRENT_TIMESTAMP
                WHERE _id = OLD._id;
        END
</code></pre>

<p>However, my unit tests require a <code>1000ms</code> sleep between insert/update operations in order to reliably sort, and this amount of delay is very annoying for unit testing.</p>

<p>I thought I could implement a vector clock instead, but it seems that <code>AUTOINCREMENT</code> values only exist for primary key columns. Does SQLite offer any other <code>AUTOINCREMENT</code> or <code>AUTOINCREMENT</code>-like option?</p>

<p>I'm running this on Android P, but this should be a generic SQLite problem.</p>

<p><strong>UPDATE</strong></p>

<p>I'm now using an <code>sort INTEGER NOT NULL UNIQUE</code> column, and <code>SELECT</code>-ing the largest row in that column and manually incrementing it before an <code>INSERT/UPDATE</code>:</p>

<pre><code>CREATE TABLE podcast_search (
    _id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 
    search TEXT NOT NULL UNIQUE,
    sort INTEGER NOT NULL UNIQUE
)

SELECT sort from podcast_search ORDER BY sort DESC
</code></pre>

<p>either increment <code>sort</code> in application code, or set it to <code>0</code></p>

<p>Could I do this in a <code>TRIGGER</code> instead?</p>
",https://stackoverflow.com/questions/54731118/sqlite-autoincrement-non-primary-key-column,"['sqlite', 'auto-increment']",1967,True,2,1
Is this the correct approach to achieve concurrency?,"<p>I have created a small application which basically includes rest Apis for money transfer between accounts. For the simplicity I have used concurrent hashmap for datastore. Now the very basic concept to be implemented for this would be multi threading. </p>

<p>As I am not using any DB, I have created lock on the Account class itself using reentrant lock. Now when I am doing the transaction I am obtaining the lock on both the account objects i.e. sender and receiver and then passing it to a biconsumer.accept().</p>

<p>I am not sure if this is entirely correct (in terms of this app only.).
Also not sure how to do unit testing for this.</p>

<p>Account.java</p>

<pre><code>public class Account {

    private ReentrantLock lock = new ReentrantLock();
    private String accountNumber;
    private long accountBalance;

    public String getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }

    public long getAccountBalance() {
        return accountBalance;
    }

    public void setAccountBalance(long accountBalance) {
        this.accountBalance = accountBalance;
    }

    public void getLock() {
        this.accountLock.lock();
    }

    public void doUnlock() {
        this.accountLock.unlock();
    }
}
</code></pre>

<p>Transfer.java</p>

<pre><code>send(senderAccount, receiverAccount, (x, y) -&gt; {
                    senderAccount.setAccountBalance(senderAccount.getAccountBalance() - (transferAmount));
                    receiverAccount.setAccountBalance(toAccountDto.getAccountBalance() + transferAmount));
                });


public void send(Account senderAccount, Account receiverAccount,
            BiConsumer&lt;Account, Account&gt; action) {
        senderAccount.lock();
        try {
            receiverAccount.lock();
            try {
                biConsumer.accept(senderAccount, receiverAccount);
            } finally {
                receiverAccount.unlock();
            }
        } finally {
            senderAccount.unlock();
        }
    }
</code></pre>

<p>In terms of single thread this works just fine as expected.
But how can I unit test this to check if it works fine with 10000 threads.</p>

<p>Also is this account level locking a good practice (in terms of this app), or I could have done something else ?</p>
",https://stackoverflow.com/questions/56142442/is-this-the-correct-approach-to-achieve-concurrency,"['java', 'multithreading', 'junit', 'reentrantlock']",213,True,2,1
Jest unit test wont await axios response,"<p>I am unit testing my vue-electron project using jest. In a given test i fake a button click to set off a chain of events. Somewhere in that chain i do an axios request to a server, receiving data. However, the test does not await the result and simply goes on and than crashes because the results are not there yet.</p>

<p>First of all i made sure the parameters and the adress of the request where correct, which they were. After that i tried if 'axios' was defined in the component while i was testing is, which was also the case. Than i made sure that if that request was sent, the right response was receiver, which also was the case. And ofcourse i made my test async, hoping that it now would await the results, this was not the case. </p>

<p>Component:</p>

<pre><code>async functionInChain(){
const response = await axios({
      url: myUrl,
      method: 'POST',
      responseType: 'arraybuffer',
      params: {
        // bind params
      },
    })
    .then((resp: any) =&gt; {
        // this goes wrong
    })
}
</code></pre>

<p>test:</p>

<pre><code>describe('component.vue', async() =&gt; {
test('call runBot() and see if it reacts', async() =&gt; {
    wrapper.find('v-btn.button-i-use').trigger('click')
    /*later on i expect a value to be true, however it never is. 
By setting different ""checkpoints"" i found out things go wrong in the axios request.*/
  })
})
</code></pre>

<p>I do not get any errors on it, it just wont work</p>
",https://stackoverflow.com/questions/56241637/jest-unit-test-wont-await-axios-response,"['node.js', 'vue.js', 'electron', 'jestjs', 'axios']",514,True,2,1
How to avoid maven shade plugin from including transitive dependencies from &#39;test-jar&#39; types?,"<p>I am working on a multi-module Maven project which has intermodule dependencies. For example: One of the project's module, say <code>spark-module</code> has a dependency on another module (say <code>core-module</code>) from the same project. </p>

<p>The <code>core-module</code> has a dependency on <code>jackson-datatype-jsr310:2.8.11</code> and in the <code>spark-module</code>, I have added the test-jars from the Apache Spark project - <code>spark-sql_2.11:2.4.0</code>, <code>spark-core_2.11:2.4.0</code>, <code>spark-catalyst_2.11:2.4.0</code> for unit testing purpose. As you see, these Spark modules are all of version 2.4.0 which internally uses <code>jackson-databind:2.6.7.1</code>. Please refer the POM provided below:</p>

<p><strong>Parent</strong></p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0""
         xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
         xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;com.sample&lt;/groupId&gt;
    &lt;artifactId&gt;spark-test&lt;/artifactId&gt;
    &lt;packaging&gt;pom&lt;/packaging&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
    &lt;modules&gt;
        &lt;module&gt;core-module&lt;/module&gt;
        &lt;module&gt;spark-module&lt;/module&gt;
    &lt;/modules&gt;

&lt;/project&gt;
</code></pre>

<p><strong>core-module</strong></p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0""
         xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
         xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;parent&gt;
        &lt;artifactId&gt;spark-test&lt;/artifactId&gt;
        &lt;groupId&gt;com.sample&lt;/groupId&gt;
        &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
    &lt;/parent&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;artifactId&gt;core-module&lt;/artifactId&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.fasterxml.jackson.datatype&lt;/groupId&gt;
            &lt;artifactId&gt;jackson-datatype-jsr310&lt;/artifactId&gt;
            &lt;version&gt;2.8.11&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;build&gt;
        &lt;resources&gt;
            &lt;resource&gt;
                &lt;directory&gt;src/main/resources&lt;/directory&gt;
            &lt;/resource&gt;
        &lt;/resources&gt;
        &lt;testResources&gt;
            &lt;testResource&gt;
                &lt;directory&gt;src/test/resources&lt;/directory&gt;
                &lt;filtering&gt;true&lt;/filtering&gt;
            &lt;/testResource&gt;
        &lt;/testResources&gt;
    &lt;/build&gt;

&lt;/project&gt;
</code></pre>

<p><strong>spark-module</strong></p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;project xmlns=""http://maven.apache.org/POM/4.0.0""
         xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
         xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd""&gt;
    &lt;parent&gt;
        &lt;artifactId&gt;spark-test&lt;/artifactId&gt;
        &lt;groupId&gt;com.sample&lt;/groupId&gt;
        &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
    &lt;/parent&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;artifactId&gt;spark-module&lt;/artifactId&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.sample&lt;/groupId&gt;
            &lt;artifactId&gt;core-module&lt;/artifactId&gt;
            &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;
            &lt;artifactId&gt;spark-sql_2.11&lt;/artifactId&gt;
            &lt;version&gt;2.4.0&lt;/version&gt;
            &lt;scope&gt;provided&lt;/scope&gt;
            &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
                    &lt;artifactId&gt;*&lt;/artifactId&gt;
                &lt;/exclusion&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;com.fasterxml.jackson.module&lt;/groupId&gt;
                    &lt;artifactId&gt;*&lt;/artifactId&gt;
                &lt;/exclusion&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.javassist&lt;/groupId&gt;
                    &lt;artifactId&gt;*&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;
            &lt;artifactId&gt;spark-core_2.11&lt;/artifactId&gt;
            &lt;version&gt;2.4.0&lt;/version&gt;
            &lt;scope&gt;provided&lt;/scope&gt;
            &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
                    &lt;artifactId&gt;*&lt;/artifactId&gt;
                &lt;/exclusion&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;com.fasterxml.jackson.module&lt;/groupId&gt;
                    &lt;artifactId&gt;*&lt;/artifactId&gt;
                &lt;/exclusion&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.javassist&lt;/groupId&gt;
                    &lt;artifactId&gt;*&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;
            &lt;artifactId&gt;spark-hive_2.11&lt;/artifactId&gt;
            &lt;version&gt;2.4.0&lt;/version&gt;
            &lt;scope&gt;provided&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;!-- Test dependencies --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.scalatest&lt;/groupId&gt;
            &lt;artifactId&gt;scalatest_2.11&lt;/artifactId&gt;
            &lt;version&gt;3.0.6&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.holdenkarau&lt;/groupId&gt;
            &lt;artifactId&gt;spark-testing-base_2.11&lt;/artifactId&gt;
            &lt;version&gt;2.4.0_0.12.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;
            &lt;artifactId&gt;spark-sql_2.11&lt;/artifactId&gt;
            &lt;version&gt;2.4.0&lt;/version&gt;
            &lt;type&gt;test-jar&lt;/type&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;
            &lt;artifactId&gt;spark-core_2.11&lt;/artifactId&gt;
            &lt;version&gt;2.4.0&lt;/version&gt;
            &lt;type&gt;test-jar&lt;/type&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.spark&lt;/groupId&gt;
            &lt;artifactId&gt;spark-catalyst_2.11&lt;/artifactId&gt;
            &lt;version&gt;2.4.0&lt;/version&gt;
            &lt;type&gt;test-jar&lt;/type&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;net.alchim31.maven&lt;/groupId&gt;
                &lt;artifactId&gt;scala-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;3.2.2&lt;/version&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;compile&lt;/goal&gt;
                            &lt;goal&gt;testCompile&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.scalatest&lt;/groupId&gt;
                &lt;artifactId&gt;scalatest-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;2.0.0&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;reportsDirectory&gt;${project.build.directory}/surefire-reports&lt;/reportsDirectory&gt;
                    &lt;junitxml&gt;.&lt;/junitxml&gt;
                    &lt;filereports&gt;WDF TestSuite.txt&lt;/filereports&gt;
                &lt;/configuration&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;id&gt;test&lt;/id&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;test&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
                &lt;version&gt;3.1&lt;/version&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-shade-plugin&lt;/artifactId&gt;
                &lt;version&gt;3.0.0&lt;/version&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;phase&gt;package&lt;/phase&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;shade&lt;/goal&gt;
                        &lt;/goals&gt;
                        &lt;configuration&gt;
                            &lt;artifactSet&gt;
                                &lt;excludes&gt;
                                    &lt;exclude&gt;org.apache.spark:*&lt;/exclude&gt;
                                &lt;/excludes&gt;
                            &lt;/artifactSet&gt;
                        &lt;/configuration&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;

&lt;/project&gt;
</code></pre>

<p>Now when I build <code>spark-module</code>, when maven shade plugin kicks in, it includes the <code>jackson-databind:2.6.7.1</code> instead of 2.8.11 (I thought it would come from <code>core-module</code>). When I add the following exclusions to the <code>test-jar</code> dependencies, it properly bundles the 2.8.11 version JAR but that makes my tests fail since the dependencies are excluded:</p>

<pre><code>&lt;exclusions&gt;
    &lt;exclusion&gt;
        &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
        &lt;artifactId&gt;*&lt;/artifactId&gt;
    &lt;/exclusion&gt;
    &lt;exclusion&gt;
        &lt;groupId&gt;com.fasterxml.jackson.module&lt;/groupId&gt;
        &lt;artifactId&gt;*&lt;/artifactId&gt;
    &lt;/exclusion&gt;
    &lt;exclusion&gt;
        &lt;groupId&gt;org.javassist&lt;/groupId&gt;
        &lt;artifactId&gt;*&lt;/artifactId&gt;
    &lt;/exclusion&gt;
&lt;/exclusions&gt;
</code></pre>

<p>Maybe I'm doing something wrong with the way the dependencies are handled. So can you please help me understand what should be done here?</p>
",https://stackoverflow.com/questions/58797013/how-to-avoid-maven-shade-plugin-from-including-transitive-dependencies-from-tes,"['maven', 'apache-spark', 'maven-shade-plugin']",925,True,2,1
"For testing, can one force broken lock-free code to fail?","<p>[I now see that my question is a <a href=""https://stackoverflow.com/q/12159/1275653"">duplicate.</a> I will vote to close it.]</p>

<p>Can one reliably test lock-free code in C++? Is there a known technique?</p>

<p>Can one compose a proper unit test? In lock-free-programming, are proper unit tests even possible?</p>

<p>I see no obvious way to force <em>wrong</em> lock-free code to fail <em>reliably.</em> Apparently, I am missing a concept.</p>

<p>(See also <a href=""https://stackoverflow.com/q/45934481/1275653"">this related question.</a>)</p>

<p><strong>EXAMPLE</strong></p>

<p>Concurrency wants long examples, unfortunately. I have made the below example as short as I can. The example is correct as far as I know, but suppose that you broke it&mdash;say, by changing <code>memory_order_release</code> to <code>memory_order_relaxed</code>. Even when broken, the example still, spuriously succeeds on my machine. With <code>memory_order_relaxed</code>, the example should fail; but, for purpose of testing, I do not know how <em>to make</em> it fail.</p>

<p>Do you?</p>

<p>Unit testing seems doubtful when one is unable to compose a test to flunk bad code.</p>

<pre><code>#include &lt;atomic&gt;
#include &lt;thread&gt;
#include &lt;cstdlib&gt;
#include &lt;iostream&gt;

const int threshold     =  0x100;
const int large_integer = 0x1000;

// Gradually increase the integer to which q points until it reaches the
// threshold.  Then, release.
void inflate(std::atomic_bool *const p_atom, int *const q)
{
    while (*q &lt; threshold) ++*q;
    p_atom-&gt;store(true, std::memory_order_release);
}

int main()
{
    std::atomic_bool atom{false};
    int n{0};

    // Dispatch the inflator, letting it begin gradually, in the background, to
    // inflate the integer n.
    std::thread inflator(inflate, &amp;atom, &amp;n);

    // Waste some time....
    for (int i = large_integer; i; --i) {}

    // Spin until the inflator has released.
    {
        int no_of_tries = 0;
        while (!atom.load(std::memory_order_acquire)) ++no_of_tries;
        std::cout &lt;&lt; ""tried "" &lt;&lt; no_of_tries &lt;&lt; "" times"" &lt;&lt; std::endl;
    }

    // Verify that the integer n has reached the threshold.
    if (n == threshold) {
        std::cout &lt;&lt; ""succeeded"" &lt;&lt; std::endl;
    }
    else {
        std::cout &lt;&lt; ""failed"" &lt;&lt; std::endl;
        std::cerr &lt;&lt; ""error""  &lt;&lt; std::endl;
        std::exit(1);
    }

    inflator.join();
    return 0;
}
</code></pre>
",https://stackoverflow.com/questions/54337597/for-testing-can-one-force-broken-lock-free-code-to-fail,"['c++', 'unit-testing', 'concurrency', 'lock-free']",62,False,2,0
Mock Angular Router with Spectator,"<p>I am using <a href=""https://github.com/ngneat/spectator"" rel=""nofollow noreferrer"">Spectator</a> to write my Angular 8 tests and <a href=""https://jestjs.io/"" rel=""nofollow noreferrer"">Jest</a> to run them. I am new to frontend unit testing, so I may have overlooked something simple; any ideas are welcome.</p>

<p>I have the following method (in Typescript) that returns a boolean, based on whether the current URL matches a set of paths or not (excluding queryParams and fragments):</p>

<pre><code>// custom-breadcrumb.component.ts

private blacklistedPaths: string[] = [''];

constructor(private router: Router) {
}

hideBreadcrumb(): boolean {
    let primaryUrlSegmentGroup: UrlSegmentGroup = this.router.parseUrl(this.router.url).root.children['primary'];
    if(primaryUrlSegmentGroup == null){
        return true;
    }
    let urlPath = primaryUrlSegmentGroup.segments.map((segment: UrlSegment) =&gt; segment.path).join('/');
    return this.blacklistedPaths.some((path: string) =&gt; path === urlPath);
}
</code></pre>

<p>and</p>

<pre><code>// custom-breadcrumb.component.html

&lt;xng-breadcrumb [hidden]=""hideBreadcrumb()""&gt;
    &lt;ng-container *xngBreadcrumbItem=""let breadcrumb""&gt;
        ...
    &lt;/ng-container&gt;
&lt;/xng-breadcrumb&gt;
</code></pre>

<p>I now want to write tests with Spectator that will validate the boolean return value based on a couple of possible urls. In Java I would emulate the <code>Router</code> with a mock object and perform something along the lines of:</p>

<pre><code>when(mockObject.performMethod()).thenReturn(myReturnValue);
</code></pre>

<p>How do I create a mock for the <code>Router</code>?  And how do I define the return values for <code>this.router.parseUrl(this.router.url).root.children['primary']</code>?</p>

<p>This is what I currently have:</p>

<pre><code>// custom-breadcrumb.component.spec.ts

import {SpectatorRouting, createRoutingFactory} from '@ngneat/spectator/jest';

describe('CustomBreadcrumbComponent', () =&gt; {
    let spectator: SpectatorRouting&lt;CustomBreadcrumbComponent&gt;;
    const createComponent = createRoutingFactory({
        component: CustomBreadcrumbComponent,
        declarations: [
            MockComponent(BreadcrumbComponent),
            MockPipe(CapitalizePipe)
        ],
        routes: [{path: ''}]  // I don't think this works
    });

    beforeEach(() =&gt; spectator = createComponent());

    it('hideBreadcrumb - hide on homepage', () =&gt; {
        // TODO set url path to ''
        expect(spectator.component.hideBreadcrumb()).toBeTruthy();
    });

    it('hideBreadcrumb - show on a page other than homepage', () =&gt; {
        //TODO set url path to 'test' for example
        expect(spectator.component.hideBreadcrumb()).toBeFalsy();
    });
});
</code></pre>

<p>I know that <code>createRoutingFactory</code> supplies a <code>ActivatedRouteStub</code> out of the box, but I haven't been able to do anything meaningful with it.</p>

<p>PS: I added karma as a tag as it may have the same solution, but do correct me if I am wrong.</p>
",https://stackoverflow.com/questions/59220436/mock-angular-router-with-spectator,"['angular', 'jestjs', 'karma-jasmine', 'angular-spectator', 'ng-mocks']",3075,True,2,1
"Flask Test: preprocess_request(), dispatch_request()","<p>My Environment: <br></p>

<blockquote>
  <p>Python3.7 <br>
  Flask==1.0.2 <br>
  pytest==4.3.1</p>
</blockquote>

<p>I was looking for a method to retrieve both request object and response object  in pytest function. And then I met across this unit testing snippet.</p>

<p><a href=""http://flask.pocoo.org/snippets/58/"" rel=""nofollow noreferrer"">http://flask.pocoo.org/snippets/58/</a></p>

<p>and below is what I did.</p>

<pre><code>def test_busking(session, monkeypatch, report=Report()):

    with app.test_request_context('/busking/zones'):
        # call the before funcs
        rv = app.preprocess_request()
        if rv != None:
            response = app.make_response(rv)
        else:
            # do the main dispatch
            rv = app.dispatch_request()
            response = app.make_response(rv)

            # now do the after funcs
            response = app.process_response(response)

        assert flask.request
        assert response
</code></pre>

<p>It works well In my environment. I was able to get both objects. What my questions are...</p>

<ul>
<li><p>dispatch_request() is called when only <code>rv is None</code>. why not when rv is something else?</p></li>
<li><p>process_response() also called when <code>rv is None</code> why is that?</p></li>
<li><p>it seams like preprocess_request() calls <code>before_request_funcs</code> and rv is the return value of the last <code>before_request_function</code>... it looks like rv has nothing to do with dispatching request please but I know It has to be something... tell me what I'm wrong about.</p></li>
</ul>

<p>There are still tons of things I don't understand in preprocess_request(), make_response(), dispatch_request(), process_response(). I think rv and process_request() are playing great roles but I'm not sure.  I would be more than greatful if you also explain what is going on background.</p>
",https://stackoverflow.com/questions/56815553/flask-test-preprocess-request-dispatch-request,"['python-3.x', 'unit-testing', 'flask']",1581,False,2,1
"Should I verify that props were set after component mounts in my unit tests? (using Enzyme, Mocha, Chai)","<p>I've recently starting programming. I'm on a team who is programming in React and is using Enzyme, Mocha and Chai for unit testing. See package versions below.</p>

<p>My team insists that the unit test file for each component should have the following test:</p>

<pre><code>beforeEach(() =&gt; {
   component = mount(&lt;MyComponent /&gt;)
})

it('renders with correct properties', () =&gt; {
   component.setProps({
     height: 100,
     width: 500,
     placeholder: 'Some value here'
   })
   expect(component.prop('height')).to.equal(100)
   expect(component.prop('width')).to.equal(500)
   expect(component.prop('placeholder')).to.equal('Some value here')
})
</code></pre>

<p>That's the end of the test.  To me, this test looks like it's just testing that React sets the props.  I feel we can trust what React is doing and instead should be testing how we use React to render our component.  I'd rather test the <em>affects</em> of the prop values on other props, state, and how the component renders as a result of the props.  </p>

<p>But I'm new and my team thinks I'm wrong in my concern, so I thought I'd check around:  Is there value in the above test case that I'm missing?  Is it good practice?</p>

<p><strong>Related Questions</strong></p>

<ul>
<li><a href=""https://stackoverflow.com/questions/57062372/should-i-mount-using-beforeeach-and-set-props-for-each-test-or-mount-a-specifi"">Best practice on setting props in unit tests</a> (also my question)</li>
</ul>

<p><strong>Packages</strong></p>

<ul>
<li>""enzyme"": ""^3.3.0"",</li>
<li>""enzyme-adapter-react-16"": ""^1.1.1"",</li>
<li>""mocha"": ""^5.0.0"",</li>
<li>""chai"": ""3.5.0""</li>
</ul>
",https://stackoverflow.com/questions/57064483/should-i-verify-that-props-were-set-after-component-mounts-in-my-unit-tests-us,"['reactjs', 'unit-testing', 'mocha.js', 'enzyme', 'chai']",317,True,2,1
Is it possible to unit test this method,"<p>I am trying to get my head around unit testing and mocking. So as I have it, unit tests, test a single method with provided parameters expecting a specified outcome using <code>Assert</code>. Now almost all my methods that I implement communicate with the database in one way or another. And most of them have multiple responses depending on what happened within the method. Exceptions might be thrown as well but they are caught by the catch clause and handled gracefully.</p>

<p>I have been trying to write a unit test for the following method but I don't think I am getting the mocking right on it. Here is the method in question:</p>

<pre><code>    public override async Task&lt;RegistrationResponse&gt; RegisterEndpoint(RegistrationRequest request, ServerCallContext context)
    {
        try
        {
            //Check that IP address is valid, returned malformed if not a valid IP
            var isValidIp = System.Net.IPAddress.TryParse(request.IpAddress, out _);
            if (!isValidIp)
                return new RegistrationResponse { Result = RegistrationResponse.Types.Result.Malformed };

            //Check that the record doesn't exist in the DB already
            var doesExist = _context.Services.Any(x =&gt; x.IpAddress == request.IpAddress &amp;&amp; x.Type == request.Type);
            if (doesExist)
                return new RegistrationResponse { Result = RegistrationResponse.Types.Result.Duplicate };

            //Add the service to the database
            _context.Services.Add(new ServiceModel
            {
                IpAddress = request.IpAddress,
                Type = request.Type,
                LastAccessed = DateTime.Now
            });

            //Save the service to the database
            await _context.SaveChangesAsync();
        }
        catch (Exception ex)
        {
            //Log exception 
            await _logClient.LogException(ex, new object[]{ request });
            //Return failure result
            return new RegistrationResponse { Result = RegistrationResponse.Types.Result.Failure };
        }

        //Return successful result
        return new RegistrationResponse { Result = RegistrationResponse.Types.Result.Success };
    }
</code></pre>

<p>Would greatly appreciate if someone can maybe explain to me how to write a unit test for something like this; because the majority of the articles on the internet just use a basic calculator as an example and that doesn't help at all when it comes to <em>""complex""</em> method like this.</p>
",https://stackoverflow.com/questions/59102722/is-it-possible-to-unit-test-this-method,"['c#', 'unit-testing']",313,False,1,0
Angular Unit Testing - Mocking a REST service call,"<p>I'm writing unit tests for an Angular application to test frontend functionality and am trying to generate a way to mock a rest service call for the following scenario:</p>

<p>I have a class defined as follows:</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import {RestService} from ""../../../../../services/rest.service"";
import {ActivatedRoute, Router} from ""@angular/router"";

@Component({
  selector: 'app-example-class’,
  templateUrl: ‘./example-class.component.html',
  styleUrls: [‘./example-class.component.scss']
})
export class ExampleClass implements OnInit {

  myData: any = [];
  reloadInterval: any;
  constructor(private rest: RestService) {
    this.reloadInterval = setInterval(() =&gt; {
      this.getData();
    }, 10000);
  }

  ngOnInit() {
    this.getData();
  }

  ngOnDestroy(){
    clearInterval(this.reloadInterval);
  }

  getData() {
    this.rest.call(‘exampleClass’, this.rest.id).subscribe((data: {}) =&gt; {
      if (data['rows']) {
        this.myData = data['rows'].reduce((accumulator, currRow)=&gt; accumulator + currRow.value, 0);
      }
    });
  }
}
</code></pre>

<p>I want to specifically test my ""getData()"" method using Karma/Jasmine unit testing framework.  Here's what I've created:</p>

<pre><code>describe(‘ExampleClassComponent', () =&gt; {
  let component: ExampleClass;
  let fixture: ComponentFixture&lt;ExampleClass&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
      ],
      declarations: [ ExampleClass ]
    })
    .compileComponents();
  }));

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

  it('should create',
    inject(
      [HttpTestingController],
      (httpMock: HttpTestingController) =&gt; {
    expect(component).toBeTruthy();
  }));
});
</code></pre>

<p>This works.  The component gets created and the test passes.  However, when I try to do the following:</p>

<pre><code>it('should test number of elements', ()=&gt;{
    component.getData();
    expect(component.myData.length).toBe(1);
 });
</code></pre>

<p>This fails.  And it fails because it's trying to call the getData() method with a rest call to a service that's not running.  I want to somehow mock the rest call made in that function.  I've tried creating a MockRestService class in my test class as such:</p>

<pre><code>class MockRestService extends RestService {
  myData = [
    {myData: 1}
  ];

  call(endpoint: string, params?: Object, data?: any, queryString?: string, isCustomUri?: boolean): Observable&lt;any&gt; {
    return of(this.myData);
  }
}
</code></pre>

<p>and then modifying my test:</p>

<pre><code>  it('should test number of elements', ()=&gt;{
    let mockRestService = new MockRestService(null);
    component = new ExampleClass(mockRestService);
    component.getData();
    expect(component.myData.length).toBe(1);
  });
</code></pre>

<p>But this doesn't work.  Is it possible to mock the rest call made in getData for the purposes of testing, and if so how?  I really appreciate the help!</p>
",https://stackoverflow.com/questions/58984862/angular-unit-testing-mocking-a-rest-service-call,"['angular', 'unit-testing', 'karma-jasmine']",9222,True,1,1
Angular Unit Testing - Mocking a REST service call,"<p>I'm writing unit tests for an Angular application to test frontend functionality and am trying to generate a way to mock a rest service call for the following scenario:</p>

<p>I have a class defined as follows:</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import {RestService} from ""../../../../../services/rest.service"";
import {ActivatedRoute, Router} from ""@angular/router"";

@Component({
  selector: 'app-example-class’,
  templateUrl: ‘./example-class.component.html',
  styleUrls: [‘./example-class.component.scss']
})
export class ExampleClass implements OnInit {

  myData: any = [];
  reloadInterval: any;
  constructor(private rest: RestService) {
    this.reloadInterval = setInterval(() =&gt; {
      this.getData();
    }, 10000);
  }

  ngOnInit() {
    this.getData();
  }

  ngOnDestroy(){
    clearInterval(this.reloadInterval);
  }

  getData() {
    this.rest.call(‘exampleClass’, this.rest.id).subscribe((data: {}) =&gt; {
      if (data['rows']) {
        this.myData = data['rows'].reduce((accumulator, currRow)=&gt; accumulator + currRow.value, 0);
      }
    });
  }
}
</code></pre>

<p>I want to specifically test my ""getData()"" method using Karma/Jasmine unit testing framework.  Here's what I've created:</p>

<pre><code>describe(‘ExampleClassComponent', () =&gt; {
  let component: ExampleClass;
  let fixture: ComponentFixture&lt;ExampleClass&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
      ],
      declarations: [ ExampleClass ]
    })
    .compileComponents();
  }));

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

  it('should create',
    inject(
      [HttpTestingController],
      (httpMock: HttpTestingController) =&gt; {
    expect(component).toBeTruthy();
  }));
});
</code></pre>

<p>This works.  The component gets created and the test passes.  However, when I try to do the following:</p>

<pre><code>it('should test number of elements', ()=&gt;{
    component.getData();
    expect(component.myData.length).toBe(1);
 });
</code></pre>

<p>This fails.  And it fails because it's trying to call the getData() method with a rest call to a service that's not running.  I want to somehow mock the rest call made in that function.  I've tried creating a MockRestService class in my test class as such:</p>

<pre><code>class MockRestService extends RestService {
  myData = [
    {myData: 1}
  ];

  call(endpoint: string, params?: Object, data?: any, queryString?: string, isCustomUri?: boolean): Observable&lt;any&gt; {
    return of(this.myData);
  }
}
</code></pre>

<p>and then modifying my test:</p>

<pre><code>  it('should test number of elements', ()=&gt;{
    let mockRestService = new MockRestService(null);
    component = new ExampleClass(mockRestService);
    component.getData();
    expect(component.myData.length).toBe(1);
  });
</code></pre>

<p>But this doesn't work.  Is it possible to mock the rest call made in getData for the purposes of testing, and if so how?  I really appreciate the help!</p>
",https://stackoverflow.com/questions/58984862/angular-unit-testing-mocking-a-rest-service-call,"['angular', 'unit-testing', 'karma-jasmine']",9222,True,1,1
How to debug firestore.rules variables and functions?,"<p>I am having difficulty trying to diagnose a particular rule in my firestore.rules file.  See <a href=""https://stackoverflow.com/questions/58796385/firestore-rules-rule-not-evaluating-as-intended"">that question here</a> for context.</p>

<p>Is there a way to debug the firestore.rules file and/or functions?  I'm using unit testing and the emulators to test my rules, but I would really love to see exactly what values are being evaluated by the rules engine.</p>

<p>For instance, here is my firestore.rules file:</p>

<pre class=""lang-js prettyprint-override""><code>rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /organizations/{orgId} {
      allow read: if isAdmin();
      allow create, update: if isAdmin();

      match /classes/{classId} {
        allow read: if request.auth.uid != null;
        allow create, update: if isAdmin();

        match /students/{studentId} {
          allow read: if isAdmin() || belongsToCurrentClass();
          allow create, update: if isAdmin();
        }
      }
    }
  }
}

function isAdmin() {
  // removed for security
}

function belongsToCurrentClass() {
  // retuns true if the authenticated user is the teacher of the requested class
  return get(/databases/$(database)/documents/organizations/$(orgId)/classes/$(classId)).data.teacherUid == request.auth.uid;
}
</code></pre>

<p>What I'd love to do is set breakpoints or step through the code. When attempting CRUD operations on a organizations/{orgId}/classes/{classId}/students/{studentId} path I'd love to inspect exactly what values the orgId, classId, and studentId variables are holding, as well as the resource and request parameters.  I'd love to inspect exactly which document (if any) is returned by the get request in belongsToCurrentClass and what the return value is.</p>

<p>Does anyone know of any way to do this?  I think I'd answer my question referred to above in 10 seconds if I could just see the data being evaluated.</p>
",https://stackoverflow.com/questions/58796514/how-to-debug-firestore-rules-variables-and-functions,"['firebase', 'google-cloud-firestore', 'firebase-security']",5353,True,9,2
Is it possible to unit test this method,"<p>I am trying to get my head around unit testing and mocking. So as I have it, unit tests, test a single method with provided parameters expecting a specified outcome using <code>Assert</code>. Now almost all my methods that I implement communicate with the database in one way or another. And most of them have multiple responses depending on what happened within the method. Exceptions might be thrown as well but they are caught by the catch clause and handled gracefully.</p>

<p>I have been trying to write a unit test for the following method but I don't think I am getting the mocking right on it. Here is the method in question:</p>

<pre><code>    public override async Task&lt;RegistrationResponse&gt; RegisterEndpoint(RegistrationRequest request, ServerCallContext context)
    {
        try
        {
            //Check that IP address is valid, returned malformed if not a valid IP
            var isValidIp = System.Net.IPAddress.TryParse(request.IpAddress, out _);
            if (!isValidIp)
                return new RegistrationResponse { Result = RegistrationResponse.Types.Result.Malformed };

            //Check that the record doesn't exist in the DB already
            var doesExist = _context.Services.Any(x =&gt; x.IpAddress == request.IpAddress &amp;&amp; x.Type == request.Type);
            if (doesExist)
                return new RegistrationResponse { Result = RegistrationResponse.Types.Result.Duplicate };

            //Add the service to the database
            _context.Services.Add(new ServiceModel
            {
                IpAddress = request.IpAddress,
                Type = request.Type,
                LastAccessed = DateTime.Now
            });

            //Save the service to the database
            await _context.SaveChangesAsync();
        }
        catch (Exception ex)
        {
            //Log exception 
            await _logClient.LogException(ex, new object[]{ request });
            //Return failure result
            return new RegistrationResponse { Result = RegistrationResponse.Types.Result.Failure };
        }

        //Return successful result
        return new RegistrationResponse { Result = RegistrationResponse.Types.Result.Success };
    }
</code></pre>

<p>Would greatly appreciate if someone can maybe explain to me how to write a unit test for something like this; because the majority of the articles on the internet just use a basic calculator as an example and that doesn't help at all when it comes to <em>""complex""</em> method like this.</p>
",https://stackoverflow.com/questions/59102722/is-it-possible-to-unit-test-this-method,"['c#', 'unit-testing']",313,False,1,0
C++ How to do dependency injection on a derived class?,"<p>I have a base class B derived from an abstract class A. The idea of having abstract class A is to facilitate Dependency Injection and Mocking while unit testing. So A have no implementation. Almost like C# interface. All works fine. </p>

<p>Now I have a derived class D that is inherited from B. The problem now is D does not have an abstract class to facilitate DI or Mocking. Here is a little code that explains the problem:</p>

<pre><code>class A // Abstract
{
public:
  virtual String Identify() = 0;
};

class B : public A
{
public:
  String Identify() {return ""B""; }
};

class D : public B
{
public:
  String D_Work() {return ""D_Work""; }
};
</code></pre>

<p>So to use B, I do <code>A *b = new B();</code> which is fine. The using class does not know the type B. new() is done by a factory or the object is just passed in. </p>

<p>But to use D, I either need the actual type (which I am trying to get away) or use type A and cast to call methods like <code>A *d = new D(); ((D*)d)-&gt;D_Work())</code> (using c-style for simplicity) which again will require the user to know the type. Any thoughts on the design?</p>
",https://stackoverflow.com/questions/58734769/c-how-to-do-dependency-injection-on-a-derived-class,"['c++', 'dependency-injection']",456,True,1,2
How can I generate a fake coverage report for a Typescript/angularjs project with an artificial 0% coverage value?,"<p>I'm dealing with some legacy code that is being ported to newer frameworks. We're not going to bother to start unit testing the legacy code, because as we port it we also revise the business specification.</p>

<p>However, for the sake of statistical accuracy, I would like to include the 0% coverage that we have in our legacy code into our full coverage report (that includes other non-legacy modules using different languages and frameworks).</p>

<p>Given that this is an angularjs project and due to complications given by the architecture (usage of requirejs, global variable, being split into multiple apps) I have already given up setting an actual Karma test environment, my question is:</p>

<p><strong>what is the least painful way to generate a fake coverage report from the existing code that simply marks every line as not covered, yielding a 0% coverage report?</strong></p>

<p>I need something in a standard format (lcov?) that can be uploaded to coverage report websites like codacy/codecov/codeclimate etc.</p>
",https://stackoverflow.com/questions/56669466/how-can-i-generate-a-fake-coverage-report-for-a-typescript-angularjs-project-wit,"['angularjs', 'code-coverage', 'karma-coverage']",147,False,1,0
Configure two ports for springboot integration testing,"<p>Im pretty new to spring framework and my JAVA application(Say Project_A) running at <a href=""http://localhost:8080"" rel=""nofollow noreferrer"">http://localhost:8080</a>, does processing and forwards the processed content to <a href=""http://localhost:9090"" rel=""nofollow noreferrer"">http://localhost:9090</a> where another application(Say Project_B) is running. Project_B replies back to Project_A and then Project_A forwards the content outside . </p>

<p>Im now trying to write integration test for Project_A , so need two mocks, one at the request side and the other at Project_B side . For request, I can make use of MockMVC to simulate request and send . But for simulating the Project_B , Im thinking of creating a mock controller which receives requests from Project_A and send replies accordingly . So for that, I need to create another Controller running in different port . The default port in project_A is 8080 and in my new controller mock I need to use 9090. </p>

<p>Is there a way to use two different ports in one spring junit application ? Or any better way to achieve it with spring unit testing itself ?</p>
",https://stackoverflow.com/questions/54746122/configure-two-ports-for-springboot-integration-testing,"['spring', 'spring-boot', 'spring-mvc', 'integration-testing', 'spring-test-mvc']",1054,False,1,2
Setting member in HttpClientHandler results in &quot;This instance has already started one or more requests&quot; error,"<p>Here is my code:</p>

<pre><code>public class Uploader
{
    private readonly HttpMessageHandler m_httpMessageHandler;

    public Uploader(HttpMessageHandler httpMessageHandler)
    {
         m_httpMessageHandler = httpMessageHandler;
    }

    public async Task&lt;string&gt; Upload(string url, Dictionary&lt;string, string&gt; data)
    {
        HttpResponseMessage result;
        try
        {
            if (somecheck)
            {
                HttpClientHandler handler = (HttpClientHandler)m_httpMessageHandler;
                // error occurs here
                handler.ServerCertificateCustomValidationCallback = delegate { return true; };
            }

            var client = new HttpClient(m_httpMessageHandler);
            result = await client.PostAsync(url, new FormUrlEncodedContent(data));
            if (result.StatusCode != HttpStatusCode.OK)
            {
                return Strings.LabelPrinterNotConfiguredError;
            }
            else
            {
                return null; // Success!
            }
        }
        catch(Exception e) 
        {
            // do some stuff
        }
    }
}
</code></pre>

<p>In my <strong>Startup.cs</strong></p>

<pre><code>services.AddSingleton&lt;HttpMessageHandler, HttpClientHandler&gt;();
</code></pre>

<p>The reason why I have this is because I've created a mock <code>HttpClientHandler</code> used for unit testing the <code>HttpClient</code>. This way I can extend from the abstract class <code>HttpMessageHandler</code> for the mock implementation in my tests.</p>

<p>I am getting this error:</p>

<blockquote>
  <p>System.InvalidOperationException:
  This instance has already started one or more requests. Properties can
  only be modified before sending the first request.</p>
</blockquote>

<p>After reading through several other <a href=""https://stackoverflow.com/questions/42235677/httpclient-this-instance-has-already-started"">answers</a> on SO, I know that the issue is that the single <code>HttpClientHandler</code> that I have is somehow having its properties modified after starting which the runtime does not like. However, I still can't figure out why that is happening because it does not appear that I am overtly modifying <code>BaseAddress</code>, <code>Timeout</code>, or <code>MaxResponseContentBufferSize</code>.</p>

<p>The answers appear to be to modify the <code>HttpClientHandler</code> after creating it but if so, how do I set the <code>ServerCertificateCustomValidationCallback</code> member variable appropriately?</p>

<p>The follow-up question would be: how would I fix this error while also keeping the ability to mock/test <code>HttpClient</code>?</p>
",https://stackoverflow.com/questions/56604342/setting-member-in-httpclienthandler-results-in-this-instance-has-already-starte,"['c#', '.net', '.net-core', 'dotnet-httpclient']",356,False,1,0
Mocking connection to mySQL database in Node.js for unit-testing,"<p>I am trying to unit-test my Node.js application using Jest and have ran into the problem of trying to mock a mySQL database in memory. If I understand correctly unit-tests must be fast and not hit the database or file system, they also must also be Isolated/Independent.</p>

<p>While testing functions that hit the file system I have used <a href=""https://github.com/tschaub/mock-fs"" rel=""nofollow noreferrer"">mock-fs</a> to mock the fs model and run file read and writes in memory.</p>

<p>The problem I am having with unit-testing functions that hit the database. I am using the <a href=""https://www.npmjs.com/package/mysql"" rel=""nofollow noreferrer"">mySQL</a> module to communicate with a mySQL server. So my question is, is there a way to run a mySQL database in memory ?
I have seen information on using SQLite3 in memory, I have tired mocking the mySQL module and using a SQLite3 database ran in memory as a drop in replacement, however this causes problems because the SQL syntax is different between mySQL and SQLite3.</p>

<p>Any information would be greatly appreciated. </p>
",https://stackoverflow.com/questions/58380071/mocking-connection-to-mysql-database-in-node-js-for-unit-testing,"['mysql', 'node.js', 'sqlite', 'unit-testing', 'mocking']",1541,False,1,0
Using PHPUnit with PHP-DI,"<p>I'm using the PHP-DI library and it works great for my code by <a href=""https://github.com/PHP-DI/demo/tree/master/app"" rel=""nofollow noreferrer"">using a bootstrap and config file</a>, as recommended by the PHP-DI documentation.</p>

<p>Then, in my app, I'm getting the container and kicking things off by calling the bootstrap:</p>

<pre><code>$container = require __DIR__ . '/Container/bootstrap.php';
$main = $container-&gt;get( Main::class );
</code></pre>

<p>So now I'm trying to set up unit testing with PHPUnit.</p>

<p>I'd like to get ahold of the $container in each Test class so that I can inject all of the dependencies of each test by using $container->injectOn($this) <a href=""http://php-di.org/doc/inject-on-instance.html#why"" rel=""nofollow noreferrer"">as suggested in the PHP-DI documentation</a>.</p>

<p>I stumbled on this open issue [which is mostly over my head], but it is still open and doesn't seem to have any recommendations.</p>

<p><a href=""https://github.com/PHP-DI/PHP-DI/issues/125"" rel=""nofollow noreferrer"">https://github.com/PHP-DI/PHP-DI/issues/125</a></p>

<p>My only thoughts are that I could just call bootstrap in setUp() the same way as my main app?</p>

<pre><code>$container = require __DIR__ . '/Container/bootstrap.php';
</code></pre>

<p>Is this what I should be doing? Is there a more elegant or recommended way to do this?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/55694924/using-phpunit-with-php-di,"['php', 'unit-testing', 'dependency-injection', 'phpunit', 'php-di']",1481,True,1,1
Jest: mocking dependencies that are passed in to constructor,"<p>I'm stuck trying to mock a class that is passed in through constructor and all the examples I've encountered so far have initialized dependencies inside constructors.
From my understanding jest replaces such dependencies with its overridden constructor but because I'm passing in the dependencies myself I'm in need of a passable instance when initialising <code>UnderTest</code>.</p>

<p>For what it's worth I'm ideally looking for a Mockito-ish behaviour, something along the lines of.</p>

<pre><code>const mockedDependency = ???
const underTest = new UnderTest(mockedDependency)

...
Proceed to write tests for underTest

</code></pre>

<p>This is the code I'm trying to test. Please assume that <code>MockedDependency</code> has its own dependencies, passed in to constructor as well.</p>

<pre><code>export default class UnderTest {

  private mockedDependency : MockedDependency

  constructor(mockedDependency: MockedDependency) {
    this.mockedDependency = mockedDependency
  }

  public methodUnderTest(parameter: string) {
    const mockedResult = this.mockedDependency.returnSomething(parameter)
    return this.doSomethingElse(mockedResult)
  }

  public methodUnderTest2(parameter1: string, parameter2: string) {
    const mockedResult = this.mockedDependency.returnSomething2(parameter1, parameter2)
    return this.doSomethingElse(mockedResult)
  }

  private doSomethingElse(mockedResult: string) {
    return mockedResult
  }
}
</code></pre>

<p>How would you go about unit testing <code>UnderTest</code> class?
Bonus points for a way to set the result of <code>mockedDependency</code> methods either in each test or by input.</p>

<p><strong>Edit:</strong>
A possible solution to those who stumble upon the same issue:</p>

<p>It's possible to cast variable as the desired object and override the methods like so:</p>

<pre><code>const mockedDependency = {
  returnSomething(parameter: string) {
    return parameter    
  }
} as MockedDependency

const underTest = new UnderTest(mockedDependency)
</code></pre>

<p>It's far from perfect but will do for simpler cases.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/55966013/jest-mocking-dependencies-that-are-passed-in-to-constructor,"['node.js', 'typescript', 'unit-testing', 'jestjs', 'koa']",1751,True,1,1
How do I unit test for failing tests?,"<p>I am trying to get started with nosetests and TDD on my own. From what I understand the point of unit testing is to test as much functionality of a function as possible. So what I want to do is add invalid parameters to my function and verify that this can not be done. For example, I am writing a simple add function</p>

<pre><code>def addBowling(x, y):
    try:
        return x + y
    except TypeError:
        print('Exception occured: invalid types')
</code></pre>

<p>So for this function I want inputs like 'a' to raise an exception. In my nosetests I want to input 'a' like so. </p>

<pre><code>def testAddNumbers():
    assert addBowling(3, 4) == 7
    assert addBowling(5, 0) == 5
    assert addBowling('a', 0) == TypeError
</code></pre>

<p>I want to have a couple asserts that will pass and one assert that will fail. When I run this test it tells me that 1 test failed. I am not sure if I am correct in my understanding but I want this test to say it passed because this is correct functionality for my function. </p>

<p>Any guidance on how to get the results that I am looking for? </p>
",https://stackoverflow.com/questions/58107881/how-do-i-unit-test-for-failing-tests,"['python-3.x', 'unit-testing', 'tdd', 'nose']",29,True,1,1
How to get rid of trailing whitespaces,"<p>I'm attempting to finalize the ISC-style (Bind9/DHCP) configuration parser in pyparsing here (after searching the GitHub, Google, et. al. for so long).</p>

<p>ISC-style configuration file has the following quirky text attributes:</p>

<ul>
<li>All C/C++/Bash comment styles</li>
<li>include file support</li>
<li>semicolon terminates before keywords</li>
<li>semicolon may or may not be directly next to token pattern</li>
<li>multi-line support (semicolon may be several lines later)</li>
</ul>

<p>The closest coding style of ISC-style config syntax (also in pyparsing) which is NGINX, which I saw over <a href=""https://github.com/fatiherikli/nginxparser/blob/master/tests.py"" rel=""nofollow noreferrer"">there on GitHub</a>.  But that would mean ditching the auto-Whitespace handling of pyparsing, for I would like to keep that, if possible.</p>

<p>My already made PyParsing grammar syntax tree is now on shaky ground when I started performing input-fuzz unit testing.</p>

<pre><code>[['server', 'example.com']]
[['server', 'example.com ']]
[['server', 'example.com      ']]
[['server', 'example.com']]
[['server', 'example.com ']]
[['server', 'example.com     ']]
[['server', 'example.com    ']]
[['server', 'example.com      ']]
[['server', 'example.com                     ']]
['options', ['server', 'example.com     '], ['server2', 'example2.net   ']]
</code></pre>

<p>I have the snippet of grammar code:</p>

<pre class=""lang-py prettyprint-override""><code>lbrack = Literal(""{"").suppress()
rbrack = Literal(""}"").suppress()
period = Literal(""."")
semicolon = Literal("";"").suppress()

domain_name = Word(srange(""[0-9A-Za-z]""), min=1, max=63)
domain_name.setName(""domain"")
fqdn = originalTextFor(domain_name - \
                       originalTextFor(period - \
                                       domain_name) * (0, 16) - \
                       Optional(period))
fqdn.setName(""fully-qualified domain name"")
orig_fqdn = originalTextFor(fqdn).setName('FQDN')
options_server = Group(Keyword(""server"") - fqdn - semicolon)
options_server2 = Group(Keyword(""server2"") - fqdn - semicolon)
options_group = Optional(options_server) &amp; \
                      Optional(options_server2) \
</code></pre>

<p>I'm still not able to get rid of the trailing whitespaces.</p>

<p>Tried the following to no avail:</p>

<pre class=""lang-py prettyprint-override""><code>iwsp = Optional(Word(""[ \t]"")).suppress() # Ignore WhiteSPace
options_server = Group(Keyword(""server"") - fqdn - iwsp - semicolon)
</code></pre>

<p>What am I doing wrong?</p>

<p>A complete working Python snippet enclosed below:</p>

<pre class=""lang-py prettyprint-override""><code>#!/usr/bin/env python3

from pyparsing import Literal, Word, srange, \
    originalTextFor, Optional, ParseException, \
    OneOrMore, Keyword, ZeroOrMore, \
    ParseSyntaxException, Group

lbrack = Literal(""{"").suppress()
rbrack = Literal(""}"").suppress()
period = Literal(""."")
semicolon = Literal("";"").suppress()

domain_name = Word(srange(""[0-9A-Za-z]""), min=1, max=63)
domain_name.setName(""domain"")
fqdn = originalTextFor(domain_name - \
                       originalTextFor(period - \
                                       domain_name) * (0, 16) - \
                       Optional(period))
fqdn.setName(""fully-qualified domain name"")
orig_fqdn = originalTextFor(fqdn).setName('FQDN')
options_server = Group(Keyword(""server"") - fqdn - semicolon)
options_server2 = Group(Keyword(""server2"") - fqdn - semicolon)
options_group = Optional(options_server) &amp; \
                      Optional(options_server2) \
                      # | had a bunch of other options commented out
options_clause = Keyword(""options"") - \
                     lbrack - \
                     options_group - \
                     rbrack - \
                     semicolon
statement = options_clause # | had a bunch of other clauses commented out
isc_style_syntax = statement


def parse_me(parse_element, test_data):

    greeting = parse_element.parseString(test_data, parseAll=True)
    greeting.pprint(indent=4)


if __name__ == '__main__':
    parse_me(options_server, ""server example.com;"")
    parse_me(options_server, ""server example.com ;"")
    parse_me(options_server, ""server example.com\t;"")
    parse_me(options_server, ""server\texample.com;"")
    parse_me(options_server, ""server\texample.com ;"")
    parse_me(options_server, ""server\texample.com\t;"")
    parse_me(options_server, ""server     example.com    ;"")
    parse_me(options_server, ""server\t \texample.com \t ;"")
    parse_me(options_server, ""server\t\t\texample.com\t\t\t;"")
    parse_me(statement, ""options { server\t \texample.com \t;\n server2\t\t\t\t\t\t\t\t\t\t\t\t example2.net\t;\n}\n ;"") 
</code></pre>
",https://stackoverflow.com/questions/57225425/how-to-get-rid-of-trailing-whitespaces,['pyparsing'],95,True,1,1
"Issue with dotnet restore, NuGet and VS Code on Linux behind corporate proxy","<p>I'm having some troubles while creating some Unit Tests with .NET Core 2.1 + VS Code on Linux behind a corporate proxy. I'm fairly new to VS Code and .NET Core, although I have experience with .NET and Visual Studio. </p>

<p>I can successfully create a solution (<strong>dotnet new sln</strong>), Class Library (<strong>dotnet new classlib</strong>)/Console Application (<strong>dotnet new console</strong>) projects and properly link them together. However, when attempting to perform <em>Unit Testing</em> with:</p>

<pre><code>dotnet new xunit,
</code></pre>

<p>the <strong>dotnet restore</strong> operation fails. The output of the aforementioned command is the following:</p>

<pre><code>/usr/share/dotnet/sdk/2.1.301/NuGet.targets(114,5): error : Unable to load the service index for source https://api.nuget.org/v3/index.json. [/home/ryuzakyl/Desktop/CSharpWithVSCode/test/CSharpWithVSCode.Tests/CSharpWithVSCode.Tests.csproj]

/usr/share/dotnet/sdk/2.1.301/NuGet.targets(114,5): error : Response status code does not indicate success: 407 (Proxy Authentication Required ( Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.  )). [/home/ryuzakyl/Desktop/CSharpWithVSCode/test/CSharpWithVSCode.Tests/CSharpWithVSCode.Tests.csproj]
</code></pre>

<p>The error messages suggest that this could be related to some proxy configuration issues (HTTP 407 error issued), but I'm perfectly able to install VS Code extensions for C# (C#, Nuget Package Manager, Omnisharp, etc.) behind the corporate proxy.</p>

<p>I think the error might be related to the NuGet proxy configuration. I followed <a href=""https://stackoverflow.com/a/15463892/2766396"">these</a> instructions (on Linux the file I used was <em>~/.nuget/NuGet/NuGet.Config</em>), but none of the recommendations worked for me.</p>

<p>In case it helps:</p>

<pre><code>$ uname --all
Linux matrix 4.8.0-53-generic #56~16.04.1-Ubuntu SMP Tue May 16 01:18:56 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

$ dotnet --version
2.1.301

$ code --version
1.30.1
dea8705087adb1b5e5ae1d9123278e178656186a
x64
</code></pre>

<p>Thanks in advance ;).</p>
",https://stackoverflow.com/questions/54121549/issue-with-dotnet-restore-nuget-and-vs-code-on-linux-behind-corporate-proxy,"['linux', 'proxy', 'visual-studio-code', '.net-core', 'nuget']",4362,True,1,1
An interchangeable substitute to RxJava in the domain layer,"<p>A lot of articles and open source projects out there prefer making usecases return an Observable or one of it's variants, I currently go for that too, but I have doubts.
Although, I see the benefits of this in unit testing as the RxJava2 testing api is definitely rich, I suspect this is best way to go.</p>

<p>What if I wanted to refactor and use Coroutines instead for the sake of an example?.
The above approach will undoubtedly require changes in both domain and presentation layers (changes in both the affected area and the one using it).</p>

<p>On the other side, making usecases receive lambda params or callbacks in any shape, makes the presentation layer unaware of what the usecase is using to execute it's logic, but the thing is, with this approach I'll have to figure out how to test the usecases myself.</p>

<p>Is there an approach I'm not seeing that unties use cases from this burden?</p>
",https://stackoverflow.com/questions/54075937/an-interchangeable-substitute-to-rxjava-in-the-domain-layer,"['kotlin', 'rx-java', 'rx-java2', 'coroutine', 'clean-architecture']",124,False,0,0
codelite unittest++/UnitTest++.h: no such file or directory,"<p>I am trying to do unit testing with C++/Codelite. I have UnitTest++ plugin installed from codelite-plugins package (Ubuntu 18.04). I can also see this:</p>

<pre><code>$ ls -la /usr/include | grep Unit
drwxr-xr-x  3 root root   4096 Mar  2 11:47 UnitTest++

$ sudo dpkg -l | grep unittest++
ii  libunittest++-dev         2.0.0-2      amd64        unit testing framework for c++, static library and headers
ii  libunittest++2:amd64      2.0.0-2      amd64        unit testing framework for c++, runtime library
</code></pre>

<p>So I create a test project in Codelite and I add this: </p>

<pre><code>#include &lt;unittest++/UnitTest++.h&gt; // This line and main are auto-created

TEST(SanityTest) 
{
    CHECK_EQUAL(1, 1);
}

int main(int argc, char **argv)
{
    return UnitTest::RunAllTests();
}
</code></pre>

<p>Now I would expect test results after I press CTRL+F5. But when I do, I only get a popup window saying there are no tests: </p>

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

<p>I also noticed that when I go to <strong>Build > Build Project</strong> I get an error message:</p>

<blockquote>
  <p>fatal error: unittest++/UnitTest++.h: No such file or directory</p>
</blockquote>

<p>I also found <a href=""https://stackoverflow.com/questions/42657198/linker-errors-with-codelite-unittest-and-g-on-linux"">THIS ANSWER</a> and tried different variation of console commands as per answer/comments there, but I always get the same no such file or directory error. </p>

<p>Any idea what I am missing? </p>

<p><strong>EDIT:</strong></p>

<p>Build log as per Stephen's Newell request:</p>

<pre><code>/bin/sh -c '/usr/bin/make -j8 -e -f  Makefile'
----------Building project:[ Test - Debug ]----------
make[1]: Entering directory '/home/callmebob/Documents/workspace-codelite/cpp/Test'
/usr/bin/g++  -c  ""/home/callmebob/Documents/workspace-codelite/cpp/Test/main.cpp"" -g  -o Debug/main.cpp.o -I. -I/usr/include/unittest++
/home/callmebob/Documents/workspace-codelite/cpp/Test/main.cpp:1:10: fatal error: unittest++/UnitTest++.h: No such file or directory
 #include ""unittest++/UnitTest++.h""
          ^~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
Test.mk:95: recipe for target 'Debug/main.cpp.o' failed
make[1]: *** [Debug/main.cpp.o] Error 1
make[1]: Leaving directory '/home/callmebob/Documents/workspace-codelite/cpp/Test'
Makefile:4: recipe for target 'All' failed
make: *** [All] Error 2
====2 errors, 0 warnings====
</code></pre>

<p>Also if I right-click the project, go to <strong>Settings > Compiler</strong>, I can see: </p>

<blockquote>
  <p>Included Paths = /usr/include/unittest++</p>
</blockquote>
",https://stackoverflow.com/questions/55023862/codelite-unittest-unittest-h-no-such-file-or-directory,"['c++', 'unit-testing', 'codelite', 'unittest++']",1306,True,0,1
XML Deserialization - find specific occurrence within set maxOccurs,"<p>I'm trying to deserialize xml into a complex POCO, and the result of using xsd.exe to make my c# classes from the xsd made some properties string arrays.  That might work with my postgres db, but it doesn't work with a mocked dbcontext for unit testing.</p>

<p>An example XML might look like this:</p>

<p><code>&lt;Car&gt;
     &lt;CarWindow&gt;FrontLeft&lt;/CarWindow&gt;
     &lt;CarWindow&gt;BackLeft&lt;/CarWindow&gt;
     &lt;OtherFields&gt;&lt;/OtherFields&gt;
&lt;/Car&gt;</code></p>

<p>So what I want to do is change some of these string arrays, which have a low maxOccurs of 2-4 into dedicated columns.  That change will be useful in other ways for this project too.  So instead of <code>string[] CarWindow</code> I could have <code>string CarWindow1; string CarWindow2</code></p>

<p>What I'm missing is a way to specify in the XmlElement attribute a way to map the first, second, etc occurrence of a repeating element.  Something like <code>[XmlElement(Occurrence=1)]</code></p>

<p>I've looked at the XmlElementAttribute documentation and maybe I'm missing it, but I don't see a way to specifically map the nth occurrence of a repeating xml node to one property.  Thanks!</p>
",https://stackoverflow.com/questions/57856432/xml-deserialization-find-specific-occurrence-within-set-maxoccurs,"['c#', 'xml', 'serialization', 'deserialization']",25,False,0,0
Is there a way to use Azure DevOps Test Plan parameters for each test case as part of automate testing from pipeline?,"<p>One of my automated testing projects is looking to use parameters under Azure DevOps Test Plan as an input for each test case. After I did my research I cannot find anything that relates to it. All I found is how to use test cases with parameters manually but I need to use it for automation testing.</p>

<p>I checked ADO API documents from version 5.0, 5.1, and 6.0. There is no information talking about how to use parameters automatically. The closest one that I can find from ADO Documents is Result with Parameters. But that is after manual testing not before.</p>

<p>My unit testing code currently reading those test inputs from a .xml file. But I need to read those inputs from ADO->TestPlan->Parameters. I hope anyone can point me in a direction if it is possible to achieve this goal.</p>

<pre><code>    public static async void GetTestCase(string pat, int TestPlanID, int TestSuiteID, int TestCaseID)
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(""application/json""));

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(""Basic"",
                Convert.ToBase64String(
                    System.Text.ASCIIEncoding.ASCII.GetBytes(
                        string.Format(""{0}:{1}"", """", pat))));

            using (HttpResponseMessage response = client.GetAsync(""https://dev.azure.com/natescott/E2E-ATF/_apis/test/Plans/""+ TestPlanID +""/suites/""+ TestSuiteID + ""/testcases/""+ TestCaseID + ""?api-version=6.0-preview.3"").Result)
            {
                Console.WriteLine(""StatusCode: "" + response.StatusCode);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(""JSON: "" + responseBody);
            }
        }
    }
</code></pre>

<p>I hope I can replace that .xml with Azure DevOps->TestPlan->Parameters.</p>
",https://stackoverflow.com/questions/58422034/is-there-a-way-to-use-azure-devops-test-plan-parameters-for-each-test-case-as-pa,"['c#', 'powershell']",2498,False,0,3
How can I automate two-stage code generation in MSBuild?,"<p>I would like to automate building and running a code generator that outputs a DLL in the following two steps:</p>

<ol>
<li>The user writes regular classes in C++ and compiles them with a library-supplied <code>main.cpp</code> (sort of like how the Catch unit testing library works). The library's install path contains that <code>main.cpp</code> and I would prefer if users did not have to reference it directly (noisy).</li>
<li>The user then runs the resulting executable several times, once per ""configuration"", each of which emits an <code>.obj</code>. Finally, these <code>.obj</code> files are linked together to form the final <code>.dll</code>.</li>
</ol>

<p>At the command line, this might look like (roughly):</p>

<pre class=""lang-bash prettyprint-override""><code># this command might link to one set of dependencies
cl gen1.cpp gen2.cpp gen3.cpp %LIBROOT%\main.cpp /link [...] /out:generator.exe

# run the generator and get object files
generator.exe %CONFIG1% /out:config1.out
generator.exe %CONFIG2% /out:config2.out

# link the objects together with a potentially different set of dependencies
link config1.out config2.out [...] /DLL /out:project.dll
</code></pre>

<p>How can I automate this in MSBuild? Must I create a custom project type? Can I reuse some of (or most) of the existing C++ targets? Ideally, I would like to simply include a custom targets file, have the user specify necessary metadata in the properties, and let the build system figure out the rest.</p>
",https://stackoverflow.com/questions/54401737/how-can-i-automate-two-stage-code-generation-in-msbuild,"['c++', 'msbuild', 'msbuild-task']",77,False,0,0
unable to write a test spec for a controller&#39;s method,"<p>I am unit testing this method of my controller class. The method executes few asynchronous database queries and depending on the result, <code>Redirect</code>s the request. The success of previous database query determines if the next query needs to be done or not.</p>

<pre><code>def verifyUser(token:String) = Action.async {
     implicit request =&gt; {
       println(""verifyUser action called with token: "" + token) //TODOM - add proper handling and response

       val result:Future[Result] = for{tokenOption:Option[UserToken] &lt;- userTokenRepo.findOne(UserTokenKey(UUID.fromString(token)))  //generator 1 - get token from database
                                    userOption:Option[User] &lt;- if (tokenOption.isDefined) {println(s""received tokenOption ${tokenOption}"");userRepo.findOne(tokenOption.get.userKeys)} else {Future.successful(None)} //generator2. found token, look for corresponding user to which the token belongs
                                    modifiedUser:Option[User] &lt;- if (userOption.isDefined) {println(s""received userOption ${userOption}"");confirmSignupforUser(userOption.get)} else Future.successful(None) //generator 3. found user and token. Update profile
                                    deletedToken:Option[UserTokenKey] &lt;- if(modifiedUser.isDefined) {println(s""received modified ${modifiedUser}"");userTokenRepo.delete(UserTokenKey(UUID.fromString(token)))} else Future.successful(None)
       }
         yield { //check if we have user and token and modified user here. If any is missing, return error else success
           println(""db query results tokenOption: ""+tokenOption+"", userOption: ""+userOption+"" : modifiedUserOption: ""+modifiedUser+"", deletedToken: ""+deletedToken)
           if(tokenOption.isDefined &amp;&amp; userOption.isDefined &amp;&amp; modifiedUser.isDefined &amp;&amp; deletedToken.isDefined)
              Redirect(""http://localhost:9000/home""+"";signup=success"")//TODOM - pick from config
           else
             if(tokenOption.isEmpty)
             Redirect(""http://localhost:9000/home""+"";signup=error"")//TODOM - pick from config
           else if(userOption.isEmpty)
             Redirect(""http://localhost:9000/home""+"";signup=error"")//TODOM - pick from config
           else if(modifiedUser.isEmpty)
             Redirect(""http://localhost:9000/home""+"";signup=error"")//TODOM - pick from config
           else //this shouldn't happen. Unexpected
             Redirect(""http://localhost:9000/home""+"";signup=error"")//TODOM - pick from config
         }
       result.recover { case x =&gt; {
         println(""Future failed in validateUserSession. Recovering. Returning Internal Server Error"" + x)
        }
       }
       result //returning Future[Result]
     }
   }
</code></pre>

<p>The controller also has a method <code>confirmSignupforUser</code> which is called by <code>verifyUser</code> method in the for loop</p>

<p>To test the code, I have written the following spec</p>

<pre><code>""verify token method"" should {
    ""work "" in {
      val testEnv = new TestEnv(components.configuration)
      when(testEnv.mockUserTokenRepository.findOne(ArgumentMatchers.any[UserTokenKey])).thenReturn(
        Future{
          println(s""returning mocked token ${testEnv.userToken}"")
          Some(testEnv.userToken)}
      )

      when(testEnv.mockUserRepository.findOne(ArgumentMatchers.any[UserKeys])).thenReturn(Future{
        println(s""returning mocked user ${testEnv.user}"")
        Some(testEnv.user)
      })

      when(testEnv.controller.confirmSignupforUser(ArgumentMatchers.any[User])).thenReturn(
        Future{
          println(s""confirming mocked user ${testEnv.user}"")
          Some(testEnv.user)
        }
      )

      when(testEnv.mockUserTokenRepository.delete(ArgumentMatchers.any[UserTokenKey])).thenReturn(
        Future{
          println(s""returning mocked token key ${testEnv.userTokenKey}"")
          Some(testEnv.userTokenKey)
        }
      )


     val request = FakeRequest(""POST"", s""ws/users/signup/${testEnv.mockHelperMethods.getUniqueID()}"")
      println(""sending request"", request)

    val resultFuture:Future[Result] = testEnv.controller.verifyUser(testEnv.mockHelperMethods.getUniqueID().toString()).apply(request)
      val responseBody = contentAsString(resultFuture)
      println(s""received response ${responseBody}"")
      1 mustBe 1
    }
  }
</code></pre>

<p>My test is throwing a <code>null</code> pointer exception.</p>

<pre><code>created TestEnv with configuration...

    confirming user: null
    returning mocked user User(11111111-1111-1111-1111-111111111111,UserProfile(Some(InternalUserProfile(LoginInfo(credentials,test@test.com),1,true,Some(PasswordInfo(someHasher,somePassword,Some(someSalt))))),ExternalUserProfile(test@test.com,ln,fn,Some(somePassword))))
    returning mocked token UserToken(11111111-1111-1111-1111-111111111111,11111111-1111-1111-1111-111111111111,UserKeys(1,test@test.com,LoginInfo(credentials,test@test.com),fn,ln),2019-03-27T17:08:43.861Z,true)

    java.lang.NullPointerException was thrown.
    java.lang.NullPointerException
        at controllers.UserController.confirmSignupforUser(UserController.scala:442)
</code></pre>

<p>The piece of code which seem to cause the issue is</p>

<pre><code>def confirmSignupforUser(user:User):Future[Option[User]] = {
    println(""confirming user: ""+user)
  ...
}
</code></pre>

<p>The above code is being called from my spec it seems
    when(testEnv.controller.confirmSignupforUser(ArgumentMatchers.any[User])).thenReturn(
        Future{
          println(s""confirming mocked user ${testEnv.user}"")
          Some(testEnv.user)
        }
      )</p>

<p>I have few doubts.
question 1) I am not mocking <code>testEnv.controller</code>. Can I still use <code>when</code> in one of the methods of <code>testEnv.controller</code> (<code>testEnv.controller.confirmSignupforUser(ArgumentMatchers.any[User])</code>)?</p>

<p>Question 2) Am I correct that in the <code>for</code> loop, <code>userTokenRepo.findOne</code> should return mocked value <code>Some(testEnv.userToken)</code>. This should be then be used <code>userRepo.findOne(tokenOption.get.userKeys)</code> which should return mocked value <code>Some(testEnv.user)</code>. This should be used in <code>confirmSignupforUser(userOption.get)</code>? 
Question 3) Why is <code>confirmSignupforUser</code> getting a <code>null</code> value?</p>
",https://stackoverflow.com/questions/55383164/unable-to-write-a-test-spec-for-a-controllers-method,"['mockito', 'scalatest', 'playframework-2.6']",13,False,0,1
How to reinitialize a Singleton (KafkaProducer) during runtime?,"<p>I've a class which creates Kafka producers based on configs from a dynamic cahce. The configs were pretty much fixed, but now we are exploring the possibility of <em>re-initializing</em> the Kafka producer if the config has been changed at runtime.
The cahce is basically a HashMap which is refreshed periodically from a DB.</p>

<p>What I've done now is to check the Cache to before I send the message and if the value is changed call the init() method which has a double check lock.</p>

<pre><code>private volatile String config;
init(){
...
}

sendMessage(String message, String topic){
  if(config != Cahce.config())
  synchronized(){
    if(config != Cahce.config())
    init();
  }
}
</code></pre>

<p>I've tested this out in Dev environment it seems to work and unit testing was a pain(lot of mocks). I'm also currently modifying it so that the init() part is moved to a Factory.
<br/><br/>
I wanted to check if the implementation can be done any better ?
Also I see a Sonar warning on this line:</p>

<pre><code>private volatile String config;
</code></pre>

<p>This is what I've in mind so far, still not sure if I need an AbstractFactory:
<a href=""https://i.stack.imgur.com/43SB4.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/43SB4.jpg"" alt=""Kafka factory""></a>
The application uses Spring.</p>
",https://stackoverflow.com/questions/56636256/how-to-reinitialize-a-singleton-kafkaproducer-during-runtime,"['java', 'oop', 'design-patterns', 'apache-kafka', 'singleton']",551,False,0,0
Controlling defined values during unit testing,"<p>I would like to know if it's possible to change an included header with a set of defined values as preprocessor directives for another one during testing.</p>

<p>I have a set of values defined in a header</p>

<pre><code>//Accelconfig.h
#define sampling_rate 1 // It can be 1, 10 or 25

#ifndef accel_sample_rate
    #define accel_sample_rate 25 //default sampling 25Hz
#endif
#if accel_sample_rate == 1
    #define sampleRateBits LIS2DH12_BITS_ODR_1HZ
#elif accel_sample_rate == 10
    #define sampleRateBits LIS2DH12_BITS_ODR_10HZ
#elif accel_sample_rate == 25
    #define sampleRateBits LIS2DH12_BITS_ODR_25HZ
#else
    #define sampleRateBits LIS2DH12_BITS_ODR_25HZ //default if invalid parameter
#endif
</code></pre>

<p>That I use to do some calculations, like the dataset duration based on the number of samples and the sample duration. Currently, it's set to 1, but will be changed to other values later on.</p>

<p>I'm unit testing a function (with unity / ceedling) that does one of such calculations, and I would need to test a corner case that requires the value to be more than 1, but I don't want to change the value in the header and I would prefer to avoid <code>#ifdef TEST</code> clauses, as they don't provide much more control either. I was wondering if there's a way to change the header for another one <code>accel_config_test.h</code> that can have its values changed dynamically from the test.</p>
",https://stackoverflow.com/questions/57522756/controlling-defined-values-during-unit-testing,"['c', 'unit-testing', 'c-preprocessor']",1238,True,0,4
UUID and JPA2.0,"<p>We have a postgres database that suffers from indexes being slow on strings formatted as UUID:s. Slow compared to using UUID as datatype in the tables.</p>

<p>We would like to fix this and convert the strings to database native uuid but we are stuck with Jboss EAP6.4, eg JPA2.0, and to make things worse we have a bunch of database-tests against HSQLDB (to avoid setup of central databases for unit testing). </p>

<p>I have tried to google around but most solutions seems to fall back on non uuid type in the database (strings or binaries) or is about JPA2.2, not to mention that they are, well, old.</p>

<p>So, basically, is this a problem that can be solved within a reasonable effort or should I go back to ops and say what we need to upgrade Jboss to resent version of Jboss and Hibernate where this supposably isn't a problem? Is it a solved problem now?</p>
",https://stackoverflow.com/questions/54517533/uuid-and-jpa2-0,"['java', 'postgresql', 'hibernate', 'jpa', 'hsqldb']",73,False,0,0
PowerMockito.mockStatic() but still getting NPE when static method is called,"<p>NOTE - I've marked 3 <code>LINE</code> numbers which I discuss in my question, you may need to scroll to the right in the code snippets to see.</p>

<p>I'm really struggling unit testing a method with chained <code>Optional.map()</code>s.</p>

<pre><code>@Override
public void accept(Object message)
{
    extractSenderReference(message.toString())
        .map(t -&gt;
        {
            t.setTransactionStatus(""TAG1""); //  &lt;- LINE #1
            return t;
        })
        .map(StaticConverter::convert) //&lt; -LINE #2
        .ifPresent(Persist::persist);
}
</code></pre>

<p>Where <code>extractSenderReference()</code> returns an <code>Optional</code> of type <code>Obj</code> and is a private method.</p>

<p>And my test:</p>

<pre><code>@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassBeingTested.class, StaticConverter.class})

public class MyTest {

private ClassBeingTested updateProcessor = PowerMockito.spy(new ClassBeingTested());
private StatusDataObj statusDataObj = mock(StatusDataObj.class);

@Test
public void testSomething() throws Exception{
    Obj myObj = getObj();
    PowerMockito.mockStatic(StaticConverter.class);

    PowerMockito.doReturn(Optional.ofNullable(myObj)).when(updateProcessor, ""extractSenderReference"", anyString()); // &lt;- LINE #3
    when(StaticConverter.convert(myObj)).thenReturn(statusDataObj);
    updateProcessor.accept(""MESSAGE1"");
}

private Obj getObj(){
    Obj obj = new Obj();
    obj.setId(100L);
    return obj;
 }
}
</code></pre>

<p>At <code>LINE #1</code>, as marked in my <code>accept()</code> method, object <code>t</code> has been processed and has had its <code>transactionStatus</code> set successfully.  However at <code>LINE #2</code> I am getting a NPE when running the above test.</p>

<p>I've also tried <code>PowerMockito.spy(StaticConverter.class);</code> instead of <code>PowerMockito.mockStatic(StaticConverter.class);</code> as per <a href=""https://github.com/powermock/powermock/wiki/Mockito#mocking-static-method"" rel=""nofollow noreferrer"">https://github.com/powermock/powermock/wiki/Mockito#mocking-static-method</a> but I'm getting the same NPE.</p>

<p>My thinking was map is converting <code>t</code> to <code>StatusDataObj</code> type.  So when map calls <code>convert</code>, I'll stub and return my type.  However, originally I was expecting that <code>LINE #3</code> would effectively take care of the chained <code>map</code> calls on the <code>Optional</code> returned from <code>extractSenderReference()</code>, since I'm using a real object with values set, but there must be a null value somewhere else?</p>
",https://stackoverflow.com/questions/54422673/powermockito-mockstatic-but-still-getting-npe-when-static-method-is-called,"['java', 'unit-testing', 'mockito', 'option-type', 'powermockito']",1114,True,-2,3
Class Definition - Identifier is Undefined,"<p>I am working on a basic C++ program that sorts arrays using various sorting algorithms. My instructor has provided me with a unit testing class that calls my sorting class and calls different methods. When tries to create an instance of my sorting class in his tests, I get an error that says <code>identifier ""class name"" is undefined</code></p>

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

<p>I thought all I needed to do in order to fix this issue was to set up a default constructor in my sorting class, but that did not fix the issue. This is my <code>Sorts.hpp</code> that I have setup.</p>

<pre><code>#ifndef SORTS_HPP
#define SORTS_HPP

class Sorts
{
public:
    Sorts();
    void bubble(int array[], int size);
    void selection(int array[], int size);
    void quick(int array[], int size);
};

#endif
</code></pre>

<p>and  I also have the default constructor defined in the <code>Sorts.cpp</code> simply like this</p>

<pre><code>Sorts::Sorts()
{
}
</code></pre>

<p>and this is a section of the test file that is giving me the error.</p>

<pre><code>#include ""gtest.h""
#include ""Sorts.hpp""

#define SMALL 10
#define BIG 10000


TEST(SmallSort, Bubble)
{
  int* pArray = generateRandomArray(SMALL);

  printArray(pArray, SMALL);

  Sorts sorter; &lt;--- Error being thrown here

  sorter.bubble(pArray, SMALL);

  printArray(pArray, SMALL);
  checkArray(pArray, SMALL);
}
</code></pre>

<p>I tried to solve this issue by messing around with the default constructor and defining it in the <code>Sorts.hpp</code>, but that did not fix my problem (I didn't really think it would). Any ideas?</p>
",https://stackoverflow.com/questions/59120339/class-definition-identifier-is-undefined,"['c++', 'undefined', 'default-constructor']",377,False,0,0
getting cannot rollback - no transaction when using slqite for laravel testing,"<p>I'm trying to use in memory sqllite for my laravel testing, by putting this in my .env file:</p>

<pre><code>'sqlite_testing' =&gt; [
    'driver'   =&gt; 'sqlite',
    'database' =&gt; ':memory:',
    'prefix'   =&gt; '',
]
</code></pre>

<p>(it's in my .env.testing file, which is the same env specified in my phpunit.xml).</p>

<p>However I keep on getting this error (even if I so much as run this command):</p>

<pre><code>php artisan --env=testing  migrate
</code></pre>

<p>I get this error:</p>

<pre><code>SQLSTATE[HY000]: General error: 1 cannot rollback - no transaction is active (SQL: rollback)
</code></pre>

<p>I searched <a href=""https://forums.xamarin.com/discussion/comment/25957/#Comment_25957"" rel=""nofollow noreferrer"">online</a> and found that this may have to do with sqlite opening many connections at the same time and not closing them first. But I'm not sure how to address that problem with laravel. </p>

<h1>Note</h1>

<p>unlike all the hello world tutorials that talk about using sqlite, my situation is that I have an enterprise application that has hundreds of migration files, and I'm trying to introduce unit testing to the development workflow. I'm using <a href=""https://github.com/Behat/Behat"" rel=""nofollow noreferrer"">behat</a> for BDD and for some reason using <a href=""https://laravel.com/docs/5.5/database-testing#resetting-the-database-after-each-test"" rel=""nofollow noreferrer"">RefreshDatabase</a> makes it hang after running each scenario. So I'm trying to find a more lighter weight database to be able to do that. </p>
",https://stackoverflow.com/questions/57654233/getting-cannot-rollback-no-transaction-when-using-slqite-for-laravel-testing,"['laravel', 'sqlite', 'database-migration', 'bdd', 'behat']",209,False,0,0
I want to reuse part of providers list across multiple Angular Unit Tests,"<p>I am fairly new to Angular/Typescript. And since I am starting a new application I am also diving into the Unit testing of Components and Services. Most of my components are using DI for services. When testing these components I not only need to provide a mock service for say example my UserService but also provide classes for all the dependencies the UserService uses. I have got this working but I am reusing a list opf providers across multiple Unit Test files. As A programmer I do not like this and would like to reuse (part) of this list though say a constant. </p>

<p>The code below is what I use,. My issue is concerning the providers:[]. Most of these are needed for each spec.ts except for a few services. </p>

<pre><code>describe('HeaderMenuComponent', () =&gt; {
  let component: HeaderMenuComponent;
  let fixture: ComponentFixture&lt;HeaderMenuComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [HeaderMenuComponent],
      imports: [
        CookieModule.forRoot(),
        HttpClientModule,
        HttpModule,
        RouterTestingModule
      ],
      providers: [CookieService, CookieModule, CookieOptionsProvider, BaseService, AuthenticationService,
        { provide: XHRBackend, useClass: MockBackend },
        { provide: ConfigurationService, useClass: ConfigurationMockService },
        { provide: UserService, useClass: UserMockService },
        {
          // Here we request that configuration loading be done at app-
          // initialization time (prior to rendering)
          provide: APP_INITIALIZER,
          useFactory: (configService: ConfigurationService) =&gt;
            () =&gt; configService.loadConfigurationData(),
          deps: [ConfigurationService],
          multi: true
        },
        { provide: 'BASE_URL', useFactory: '', deps: [] }]
    })
      .compileComponents();
  }));
</code></pre>

<p>I would like the code to look something like, where DefaultProvidersList contains providers reused throughout multiple tests and Service 1 and 2 specific for current file.:</p>

<pre><code>providers: [DefaultProvidersList, Service1, Service2]
</code></pre>
",https://stackoverflow.com/questions/55946747/i-want-to-reuse-part-of-providers-list-across-multiple-angular-unit-tests,"['angular', 'typescript', 'unit-testing']",291,True,0,1
How to add a custom view from a xib to a UIScrollView?,"<p><strong>Problem</strong></p>

<p>I am trying to add a custom view from a xib into a UIScrollView.</p>

<p>I added a UIScrollView to an empty ViewController in my storyboard. I also added 4 constraints for leading, trailing, top, bottom to Safe Area and set them all Equal to 0.</p>

<p>Now in the code I want to add a custom view ""EquipmentInfoView"" to the existed UIScrollView</p>

<pre class=""lang-swift prettyprint-override""><code>class EquipmentInfoVC: UIViewController {
    @IBOutlet var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        equipmentInfoView = EquipmentInfoView.instantiate()
        scrollView.addSubview(equipmentInfoView)
    }
}
</code></pre>

<p>And it does not work as the ScrollView does not scroll. How should I do it instead?</p>

<p>Here is the custom view ""EquipmentInfoView""</p>

<pre class=""lang-swift prettyprint-override""><code>class EquipmentInfoView: UIView {

    @IBOutlet var nameTextView: UITextView!
    @IBOutlet var descriptionTextView: UITextView!
    @IBOutlet var equipmentImageView: UIImageView!

    static func instantiate() -&gt; EquipmentInfoView {
        let view: EquipmentInfoView = initFromNib()
        return view
    }
}
</code></pre>

<p><strong>Extra Notes</strong></p>

<p>I know this is not the normal way to create a custom view from xib. However, this way I dont have to set the File's Owner to ""EquipmentInfoView"", instead I set the View's Custom Class to ""EquipmentInfoView"".
(Setting File's Owner to ""EquipmentInfoView"" gives me EXC_BAD_ACCESS when I do unit testing)</p>

<p>For clarity, this is how I would add this view to a normal (non-scroll) view:</p>

<pre class=""lang-swift prettyprint-override""><code>equipmentInfoView = EquipmentInfoView.instantiate()
mainView.addSubview(equipmentInfoView)
equipmentInfoView.frame = mainView.bounds
equipmentInfoView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
</code></pre>
",https://stackoverflow.com/questions/56776280/how-to-add-a-custom-view-from-a-xib-to-a-uiscrollview,"['swift', 'uiscrollview', 'xib', 'nib']",400,False,0,1
"IOC / Injecting StreamReader, StreamWriter Dependencies","<p>I'm looking to learn how to correctly inject dependencies that come from the .NET Core library like StreamReader and FileStream. How do I inject these?</p>

<p>I have a class that reads in a file with a bunch of demographic census data, selects a random sampling of it, and then returns it as multiline string to its caller. It news up a FileStream to get access to a file's contents and then news up a StreamReader to read in the FileStream contents so I can manipulate the text. However, I'm looking to make this unit testable. If I needed to inject a class I created myself I'd generate an interface for the class to implement and pass that into the constructor, but this is a .NET Core type and there's no IFileStream, IStreamWriter, etc that I can inject. What would be the correct way to inject these so I can substitute in mocks during unit testing?</p>

<pre><code>namespace MyNS.Lib
 {
using System.IO;
using System.Text;
using PgpCore;

/// &lt;summary&gt;
/// A class for PGP encrypting strings.
/// &lt;/summary&gt;
public class EncryptUtility
{
    /// &lt;summary&gt;
    /// Initializes a new instance of the &lt;see cref=""EncryptUtility""/&gt; class.
    /// &lt;/summary&gt;
    /// &lt;param name=""sampler""&gt;The CensusSampler needed by the class.&lt;/param&gt;
    public EncryptUtility(CensusSampler sampler)
    {
        Sampler = sampler;
    }

    /// &lt;summary&gt;
    /// Encrypts a census file.
    /// &lt;/summary&gt;
    /// &lt;param name=""censusFilePath""&gt;The path to the census file.&lt;/param&gt;
    /// &lt;param name=""keyPath""&gt;The path to the public key file.&lt;/param&gt;
    /// &lt;returns&gt;Returns an encrypted census file.&lt;/returns&gt;
    public string EncryptCensus(string censusFilePath, string keyPath)
    {
        using (FileStream census = new FileStream(censusFilePath, FileMode.Open))
        {
            var censusSr = new StreamReader(census);
            var censusText = censusSr.ReadToEnd();
            return EncryptString(censusText, keyPath);
        }
    }
}
}
</code></pre>
",https://stackoverflow.com/questions/54471380/ioc-injecting-streamreader-streamwriter-dependencies,"['c#', 'inversion-of-control', 'streamreader', 'streamwriter']",862,True,0,1
Unittest&#39;s assertItemsEqual and unordered lists of unhashable objects,"<p>I have a container class I'm using to store items: 2 strings and a set. The
strings will be constant throughout the object's lifetime but the set will have
items added to it. Given this, I know the objects can't be hashed but the class
should (could?) provide <code>__eq__</code> so comparisons work on unit testing.</p>

<p>The problem I'm having is: most comparisons work, but it seems the lists have to
be sorted, otherwise the test fails, even though unittest documentation stating
that <code>assertItemsEqual</code> <em>""Test that sequence expected contains the same elements
as actual, regardless of their order. (...) It verifies if each element has the
same count in both sequences. It is the equivalent of
<code>assertEqual(sorted(expected), sorted(actual))</code> but it works with sequences of
unhashable objects as well.""</em>.</p>

<p>This is part of a bigger project, the code below reproduces the issue (can point to the code on github if needed)</p>

<p>File <code>my_class.py</code></p>

<pre class=""lang-py prettyprint-override""><code>class MyClass(object):
    # Because locations can change, the object can't be hashable
    __hash__ = None

    def __init__(self, library, name, locations=None):
        self.library = str(library)
        self.name = str(name)
        self._locations = set()

        for filename, line_number, column_number in locations or []:
            self.addItem(filename, line_number, column_number)

    def addItem(self, filename, line_number, column_number):
        self._locations.add(
            (str(filename),
             str(line_number),
             str(column_number) if column_number is not None else None))

    @property
    def __eq_key__(self):
        return self.library, self.name, tuple(sorted(self._locations))

    def __repr__(self):
        return '{}.{}(library={}, name={}, locations={})'.format(
            __name__, self.__class__.__name__, repr(self.library),
            repr(self.name), repr(list(self._locations)))

    def __eq__(self, other):
        """"""Overrides the default implementation""""""
        if isinstance(other, MyClass):
            return self.__eq_key__ == other.__eq_key__
        return NotImplemented
</code></pre>

<p>File <code>test_my_class.py</code></p>

<pre class=""lang-py prettyprint-override""><code>import unittest2
import six

from my_class import MyClass

reference = MyClass(library='library',
                    name='name',
                    locations=[('filename', 4, None),
                               ('filename', 7, None),])

class TestMyClass(unittest2.TestCase):

    # This works
    def test_equal(self):
        self.assertEqual(
            reference,
            MyClass(library='library', name='name',
                    locations=[('filename', 4, None),
                               ('filename', 7, None),]))

    # This works
    def test_not_equal(self):
        self.assertNotEqual(
            reference,
            MyClass(library='library', name='name'))

    # This works
    def test_ordered_list(self):
        self.assertItemsEqual(
            [MyClass(library='library', name='name'),
             MyClass(library='lib_0', name='name_0'),
             MyClass(library='lib_1', name='name_0'),
             MyClass(library='lib_0', name='name_1'),
             MyClass(library='lib_0', name='name_2'),
            ],
            [MyClass(library='library', name='name'),
             MyClass(library='lib_0', name='name_0'),
             MyClass(library='lib_1', name='name_0'),
             MyClass(library='lib_0', name='name_1'),
             MyClass(library='lib_0', name='name_2'),
            ])

    # Fails!
    def test_unordered_list(self):
        self.assertItemsEqual(
            [MyClass(library='library', name='name'),
             MyClass(library='lib_0', name='name_0'),
             MyClass(library='lib_1', name='name_0'),
             MyClass(library='lib_0', name='name_1'),
             MyClass(library='lib_0', name='name_2'),
            ],
            [MyClass(library='library', name='name'),
             MyClass(library='lib_0', name='name_2'),
             MyClass(library='lib_0', name='name_0'),
             MyClass(library='lib_1', name='name_0'),
             MyClass(library='lib_0', name='name_1'),
            ])

if six.PY3:
    TestMyClass.assertItemsEqual = TestMyClass.assertCountEqual

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

<p>Running on Python 3 (3.7 to be exact) it works, but Python 2.7 it doesn't:</p>

<pre><code>$ python2 test_my_class.py
...F
======================================================================
FAIL: test_unordered_list (__main__.TestMyClass)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""test_my_class.py"", line 55, in test_unordered_list
    MyClass(library='lib_0', name='name_1'),
AssertionError: Sequences differ: [my_c[100 chars]name_0', locations=[]), my_class.MyClass(libra[164 chars]=[])] != [my_c[100 chars]name_2', locations=[]), my_class.MyClass(libra[164 chars]=[])]

First differing element 0:
my_class.MyClass(library='library', name='name', locations=[])
my_class.MyClass(library='library', name='name', locations=[])

  [my_class.MyClass(library='library', name='name', locations=[]),
+  my_class.MyClass(library='lib_0', name='name_2', locations=[]),
   my_class.MyClass(library='lib_0', name='name_0', locations=[]),
   my_class.MyClass(library='lib_1', name='name_0', locations=[]),
-  my_class.MyClass(library='lib_0', name='name_1', locations=[]),
?                                                                ^

+  my_class.MyClass(library='lib_0', name='name_1', locations=[])]
?                                                                ^

-  my_class.MyClass(library='lib_0', name='name_2', locations=[])]

----------------------------------------------------------------------
Ran 4 tests in 0.001s

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

<p>Help greatly appreciated!</p>
",https://stackoverflow.com/questions/57169460/unittests-assertitemsequal-and-unordered-lists-of-unhashable-objects,"['python', 'python-2.7', 'python-unittest', 'python-3.7']",326,False,0,0
Testing Roslyn codeAction with confusing results,"<p>I have a CodeFix that gets applied ""randomly"" in Unit Testing. I have 46 unit tests for a single code fix and 20 fail. What is strange is that when I look at the Document I return in every case it is correct at the end of my CodeFix. but when I look at the end of ApplyFix sometime the document is correct and other times it is unchanged.</p>

<p>I have tried looking at the Document at the end of the CodeFix before I return it. After CodeAction.GetOperationsAsync is call my RegisterCodeFixesAsync is called and I see it register the fix. I then see my fix executed. Followed by the second line in ApplyFix</p>

<pre><code>   Private Shared Function ApplyFix(document As Document, codeAction As CodeAction) As Document
        Dim operations As ImmutableArray(Of CodeActionOperation) = codeAction.GetOperationsAsync(CancellationToken.None).Result
        Dim solution As Solution = operations.OfType(Of ApplyChangesOperation).Single.ChangedSolution
        Return solution.GetDocument(document.Id)
    End Function
</code></pre>

<p>The code below is always executed</p>

<pre class=""lang-vb prettyprint-override""><code>    context.RegisterCodeFix(CodeAction.Create(title, createChangedDocument:=Function(c As CancellationToken) AddAsClauseAsync(context.Document, DirectCast(declarationSyntax, VariableDeclaratorSyntax), c), equivalenceKey:=title), firstDiagnostic)
</code></pre>

<p>My fix gets called next and return the fixed document</p>

<pre><code>    Dim NewDocument As Document = _Document.WithSyntaxRoot(newRoot)
    Return NewDocument
</code></pre>

<p>In every case I expect that when I look at solution.GetDocument(document.Id) I would see my fix but that only happens in ~50% of the tests, the failing tests just return the original document unchanged.</p>
",https://stackoverflow.com/questions/55556704/testing-roslyn-codeaction-with-confusing-results,"['unit-testing', 'roslyn-code-analysis']",36,False,0,0
Mocking an abstract class with a virtual internally settable property in Foq,"<p>I have written an Azure durable function in F# and am trying to write unit tests, following the guidelines at <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>. I have attempted to use Foq to create a mock instance of the abstract class <code>DurableOrchestrationContextBase</code>, but that fails with the following error:</p>

<blockquote>
  <p>System.TypeLoadException : Method 'set_InstanceId' on type 'Mock.DurableOrchestrationContextBase1953fcc2-be15-41fc-850c-5a5813aace89' from assembly 'Foq.Dynamic, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is overriding a method that is not visible from that assembly.</p>
</blockquote>

<p>The error relates to this property:</p>

<pre class=""lang-cs prettyprint-override""><code>public virtual string InstanceId { get; internal set; }
</code></pre>

<p>Further investigation shows that Foq is able to mock non-virtual, non-abstract properties with internal setters on abstract C# classes, but can't cope with such properties if they are virtual.</p>

<p>Is there any way to mock such a class in an F# test? Rolling my own implementation would be awkward in this case, as <code>DurableOrchestrationContextBase</code> is a large class with many members that would need implementing.</p>
",https://stackoverflow.com/questions/55143187/mocking-an-abstract-class-with-a-virtual-internally-settable-property-in-foq,"['unit-testing', 'f#', 'foq']",153,False,0,1
Is boost::asio interfering with my serial port communication?,"<p><strong>Short version:</strong></p>

<ul>
<li>I had a code A, allowing me to read/write bytes over the serial port (UART), which passed unit testing</li>
<li>I wrote some code B, to read/write bytes over TCP/IP using boost asio (well, technically, standalone asio), which also passed unit testing</li>
<li>When I try to put A and B together, A starts receiving messages when none are sent</li>
<li>What I want to know is why, and what I can do about it</li>
</ul>

<hr>

<p><strong>More details about code A:</strong></p>

<p>Code A is mostly C code, using ioctl, fnctl, and unistd.</p>

<p>First I open the serial:</p>

<pre><code>// Flag explanation:
//  - O_RDWR
//     = read &amp; write
//     (O_RDONLY = read-only)
//     (O_WRONLY = write-only)
//  - O_NOCTTY
//     = if the path points to a terminal, that terminal will
//       not become the controlling terminal for the process
//  - O_NONBLOCK
//     = read/write requests are non-blocking, and return failure status instead of waiting
_filestream = ::open(""/dev/ttyS1"", O_RDWR | O_NOCTTY | O_NONBLOCK);
</code></pre>

<p>After checking that the serial was successfully opened, I configure the UART</p>

<pre><code>// Get options currently used by the USART
termios options;
tcgetattr(_filestream, &amp;options);

// Set control options
{
    // Set baudrate
    cfsetispeed(&amp;options, static_cast&lt;speed_t&gt;(baudrate));
    cfsetospeed(&amp;options, static_cast&lt;speed_t&gt;(baudrate));

    // Enable receiver (those flags must always be set)
    //  CLOCAL  = ignore modem status lines
    //  CREAD   = enable receiver
    options.c_cflag |= (CLOCAL | CREAD);

    // Set character size
    //  CSIZE   = bitmask for all sizes
    //  CS8     = specific flag for 8-bit
    options.c_cflag &amp;= ~static_cast&lt;unsigned int&gt;(CSIZE);
    options.c_cflag |= CS8;

    // Disable parity bit
    //  PARENB = parity enable flag
    options.c_cflag &amp;= ~static_cast&lt;unsigned int&gt;(PARENB);

    // Set number of stop bits
    //  CSTOPB = use 2 stop bits insteqd of 1
    options.c_cflag &amp;= ~static_cast&lt;unsigned int&gt;(CSTOPB);
}


// Set local options
{
    // Make sure to use raw input (pass character exactly as they are received)
    // and not canonical input (which is line-oriented)
    //  ICANON  = enable canonical input
    //  ECHO    = enable echoing input characters
    //  ECHOE   = make echo erases some characters
    //  ISIG    = enable some signals
    options.c_lflag &amp;= ~static_cast&lt;unsigned int&gt;(ICANON | ECHO | ECHOE | ISIG);
}


// Set input options
{
    // Enable software flow control
    //  IXON    = Enable software flow control (outgoing)
    //  IXOFF   = Enable software flow control (incoming)
    //  IXOFF   = Allow any character to start flow again
    options.c_iflag |= (IXON | IXOFF | IXANY);
}


// Set output options
{
    // Choose raw output
    //  OPOST = choose postprocess output
    options.c_oflag &amp;= ~static_cast&lt;unsigned int&gt;(OPOST);
}


// Set options to use for the USART
//  TCSANOW = change attributes immediately
tcsetattr(_filestream, TCSANOW, &amp;options);
</code></pre>

<p>To write stuff on the serial, I do this:</p>

<pre><code>int status = write(_filestream, &amp;byte_array, array_size);
</code></pre>

<p>and look at the status to check that everything went well.</p>

<p>To know how many bytes are available for reading, I do this:</p>

<pre><code>int nbAvailable = 0;
ioctl(_filestream, FIONREAD, &amp;nbAvailable);
</code></pre>

<p>To actually read those bytes, I do this:</p>

<pre><code>uint8_t c;
auto status = ::read(_filestream, &amp;c, 1);
</code></pre>

<p>and look at the status to check that everything went well.</p>

<p>When I'm done, I simply close the filestream:</p>

<pre><code>close(_filestream);
</code></pre>

<hr>

<p><strong>More details about code B:</strong></p>

<p>There's not much to say, first I do this:</p>

<pre><code>asio::io_context _ioContext;
asio::ip::tcp::resolver::query query(remoteIP, remotePort);
asio::ip::tcp::resolver resolver (_ioContext);

asio::error_code errCode;
asio::ip::tcp::resolver::results_type _endPoints = resolver.resolve(query, errCode);

if (errCode)
{
    std::cerr &lt;&lt; ""Cannot resolve IP/port for the connection"" &lt;&lt; std::endl;
        exit(0);
}
</code></pre>

<p>Then I connect like this</p>

<pre><code>asio::error_code errCode;
asio::connect(_socket, _endPoints, errCode);
if (!errCode)
{
        launch_thread();
}
</code></pre>

<p>The thread itself is a loop in which bytes are read using <code>_socket.read_some()</code> then moved to a mutex-protected array, or moved from another mutex-protected array then sent using <code>_socket.write_some()</code></p>

<hr>

<p><strong>What happens when I put the two codes together:</strong></p>

<p>The serial-port device is currently unplugged, I'm expecting <code>nbAvailable</code> to be 0 every time I check how many bytes are available from the serial port, but it isn't the case and many bytes are received when they should not be.</p>

<p>To the best I can tell, this seems to be the result of <code>asio</code> doing things to the serial I'm using. It's not that far-fetched, since <code>asio</code> also features serial-port i/o facilities in addition to their TCP/IP facilities, and all the evidence points to it:</p>

<ul>
<li>the problems only arise when the TCP/IP communication starts</li>
<li>commenting the _socket.write_some() calls removes the issue</li>
</ul>

<hr>

<p><strong>What I want to know:</strong></p>

<p>Why is <code>asio</code> interfering with my serial port communication, when I'm only using its TCP/IP facilities? Is there any way to solve this issue?</p>
",https://stackoverflow.com/questions/58489000/is-boostasio-interfering-with-my-serial-port-communication,"['c++', 'serial-port', 'boost-asio', 'embedded-linux']",461,False,0,0
PHP dependency injection with constructor arguments making testing difficult,"<p>I'm trying to get a handle on some dependency injection best practices. I am trying to test a service class that is using the <code>braintree/braintree_php</code> composer library. Suppose i have a <code>BraintreeService</code> class like this:</p>

<pre><code>namespace App\Service;

class BraintreeService
{
    /* @var Braintree_Gateway */
    private $gateway;

    public function __construct()
    {
        $this-&gt;gateway = new \Braintree_Gateway([
            'environment' =&gt; BRAINTREE_ENVIRONMENT,
            'merchantId' =&gt; BRAINTREE_MERCHANT_ID,
            'publicKey' =&gt; BRAINTREE_PUBLIC_KEY,
            'privateKey' =&gt; BRAINTREE_PRIVATE_KEY,
        ]);
    }

    /*
     * Generate a new client token from Braintree
     *
     * @return string $string
     */
    public function getClientToken() : string
    {
        return $this-&gt;gateway-&gt;clientToken()-&gt;generate();
    }
}
</code></pre>

<p>The usage of the class would then look like this:</p>

<pre><code>$btService = new \App\Service\BraintreeService();
$token = $btService-&gt;getClientToken();
</code></pre>

<p>The obvious problem is that this service class is tightly dependent upon <code>Braintree_Gateway</code>. Thus, making unit testing <code>BraintreeService</code> difficult. To make testing easier, I would like to move <code>Braintree_Gateway</code> to a constructor argument. This would allow me to mock the <code>Braintree_Gateway</code> class in my unit test.</p>

<p>However, as i understand it, if i do this then the code would look like this:</p>

<pre><code>namespace App\Service;

class BraintreeService
{
    /* @var Braintree_Gateway */
    private $gateway;

    public function __construct(Braintree_Gateway $gateway)
    {
        $this-&gt;gateway = $gateway;
    }

    /*
     * Generate a new client token from Braintree
     *
     * @return string $string
     */
    public function getClientToken() : string
    {
        return $this-&gt;gateway-&gt;clientToken()-&gt;generate();
    }
}
</code></pre>

<p>The usage of that class would then look like this:</p>

<pre><code>$btService = new \App\Service\BraintreeService(
    new \Braintree_Gateway([
        'environment' =&gt; BRAINTREE_ENVIRONMENT,
        'merchantId' =&gt; BRAINTREE_MERCHANT_ID,
        'publicKey' =&gt; BRAINTREE_PUBLIC_KEY,
        'privateKey' =&gt; BRAINTREE_PRIVATE_KEY,
    ])
);
$token = $btService-&gt;getClientToken();
</code></pre>

<p>I feel like this would get cumbersome if i use this service in multiple places throughout the code. I would love some advice on how better to handle the dependency while still being able to fully test my service class. Thanks!</p>
",https://stackoverflow.com/questions/56613774/php-dependency-injection-with-constructor-arguments-making-testing-difficult,"['php', 'dependency-injection', 'mocking', 'phpunit']",49,False,0,1
What should be the easiest way to unit test influxdb queries,"<p>I have a service that only make queries ( read / write ) to influxDB.</p>

<p>I want to unit test this, but I'm not sure how to do it, I've read a bunch of tutos talking about mocking. A lot deals with components like <a href=""https://github.com/DATA-DOG/go-sqlmock"" rel=""noreferrer"">go-sqlmock</a>. But as I am using influxDB, I could not use it. </p>

<p>I also find out other components I've tried to use like <a href=""https://github.com/golang/mock"" rel=""noreferrer"">goMock</a> or <a href=""https://github.com/stretchr/testify"" rel=""noreferrer"">testify</a> to be over-complicated.</p>

<p>What I think to do is to create a Repository Layer, an interface that should implement all the methods I need to run / test, and pass concrete classes with dependency injection.</p>

<p>I think it could work, but is it the easiest way to do it ? </p>

<p>I guess having Repositories everywhere, even for small services, just for them to be testable, seems to be over-engineered.</p>

<p>I can give you code if needed, but I think my question is a bit more theorical than practical. It is about the easiest way to mock a custom DB for unit testing.</p>
",https://stackoverflow.com/questions/59300417/what-should-be-the-easiest-way-to-unit-test-influxdb-queries,"['unit-testing', 'go', 'mocking']",2079,True,6,2
Indentifiable Protocol extension for SwiftUI list data,"<p>I was experimenting with SwiftUI and came across a problem while implementing the data model for one of my List. My plan was to create a protocol <code>CardProtocol</code> as the data protocol for the elements of my lists and then have a CoreData implementation of the protocol as well as a dummy one for unit testing and Canvas use. If you are using a data collection in SwiftUI <code>List</code> the single elements need to conform to the <code>Identifiable</code> protocol.  </p>

<p>The code looks like this:</p>

<pre><code>import SwiftUI
import Combine


final class CardsModel: BindableObject {
    var cards: [CardProtocol] = []
    let didChange = PassthroughSubject&lt;CardsModel, Never&gt;()
}

protocol CardProtocol: Identifiable {
    var id: Int { get set }
    var firstName: String? { get set }
    var lastName: String? { get set }
    var email: String? { get set }
    var phone: String? { get set }
}
</code></pre>

<p>This will not even compile as the <code>Identifiable</code> protocol has 2 associated types which needs to be specified if the protocol is to be used for a variable definition.</p>

<pre><code>/// A type that can be compared for identity equality.
public protocol Identifiable {

    /// A type of unique identifier that can be compared for equality.
    associatedtype ID : Hashable

    /// A unique identifier that can be compared for equality.
    var id: Self.ID { get }

    /// The type of value identified by `id`.
    associatedtype IdentifiedValue = Self

    /// The value identified by `id`.
    ///
    /// By default this returns `self`.
    var identifiedValue: Self.IdentifiedValue { get }
}
</code></pre>

<p>The exact error being <code>error: protocol 'CardProtocol' can only be used as a generic constraint because it has Self or associated type requirements</code>.
Now <code>ID</code> is not an issue and can be fixed, but <code>IdentifiedValue</code> it's by nature different in the CoreData and the dummy implementation.</p>

<p>The only reasonable solution that I found was to remove compliance to <code>Identifiable</code> from the protocol and reintroduce it later in the View using <code>cardsModel.cards.identified(by: \.id)</code>. Is there any better way out of this, that let me keep the Identifiable compliance at protocol level?</p>
",https://stackoverflow.com/questions/56552993/indentifiable-protocol-extension-for-swiftui-list-data,"['ios', 'swift', 'swiftui', 'combine']",1808,True,5,2
How to update React Component props during unit tests?,"<p>I am new to React Unit Testing and am stuck with this question.</p>

<p>I have a child component with an <code>onClick</code> callback to its parent. The parent will then update the child <code>props</code> based on the callback. The child has a custom style based on the props value.</p>

<p>Something like this:</p>

<pre><code>// Parent
const ParentComponent = () =&gt; {
    let isActive = false;
    const clickCallback = () =&gt; {
        isActive = true;
    }
    return &lt;ChildComponent handleClick={clickCallback} active={isActive} /&gt;
}

// Child
const ChildComponent = (props) =&gt; {
    return &lt;button onClick={props.handleClick} style={props.active} /&gt;
}
</code></pre>

<p>My question is: how can I test that behavior? I want to make sure that, on clicking the child component, my custom style will be updated.</p>

<p>I tried this approach, but it didn't work:</p>

<pre><code>let mockIsActive = false;
const mockCallback = () =&gt; {mockIsActive = true;}
ReactDOM.render(
    &lt;ChildComponent handleClick={mockCallback} active={mockIsActive} /&gt;, 
    container
);

const myChild = container.querySelector(""button"");
expect(myChild.getComputedStyle).toEqual(""my check here"");
myChild.dispatchEvent(new MouseEvent(""click"", {bubbles: true}));
expect(myChild.getComputedStyle).toEqual(""my new check here"");
</code></pre>

<p>I am assuming that I am updating the variable but that is not really connected to the component props?</p>

<p><strong>Extra information:</strong></p>

<ul>
<li>The behavior is working fine when I run the project (custom style changes)</li>
<li>I need to control the child props from the parent in my specific scenario</li>
<li>I currently have <code>react-test-renderer</code> and <code>react-dom/test-utils</code>, but I am fine with including external libraries if needed</li>
<li>The closest answer I found online was <a href=""https://stackoverflow.com/questions/30614454/how-to-test-a-prop-update-on-react-component"">this one here</a>, but I wasn't able to apply the solutions there in my project</li>
</ul>

<p>Thanks!</p>
",https://stackoverflow.com/questions/55386205/how-to-update-react-component-props-during-unit-tests,"['reactjs', 'unit-testing', 'parent-child']",3319,True,4,1
Python: Discover Unit Tests fails in VS Code,"<p>I followed <a href=""https://code.visualstudio.com/docs/python/unit-testing"" rel=""nofollow noreferrer"">this tutorial</a> to set up unit tests in VS Code for Python:</p>

<p>I have a problem in the section ""Test discovery"".
When I execute the command ""Python: Discover Unit Tests""
from the command palette in VS Code,
absolutely nothing happens.</p>

<p>As shown in the tutorial, I did enable the unit test framework,
and I created unit test files.
Using the commands for unit testing from the command palette does not work.
When I execute my unit test files manually from the command line, it works:</p>

<pre><code>python -m unittest test_my_code.py
</code></pre>

<p>That means that my code, and the code that tests it, are fine,
the problem is somewhere in the connection between the VS Code editor
and unit test, test framework.</p>

<p>Other issues are:</p>

<ul>
<li>when I open my project in VS Code, in the status bar it says ""Discovering Tests"", but it keeps going forever, nothing happens</li>
<li>when I right-click on a test file and I call command for running the unit tests, also nothing happens</li>
</ul>

<p>As requested, I also attach settings.json as image.</p>

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

<p>Thank you</p>
",https://stackoverflow.com/questions/54848619/python-discover-unit-tests-fails-in-vs-code,"['python', 'unit-testing', 'visual-studio-code', 'python-unittest']",1515,False,4,2
Analyzing c# project using travis and sonarcloud gives &quot;no lines of code&quot;,"<p>I've been struggling with this issue for a few days now and I can't seem to pinpoint what I'm doing wrong.</p>
<p>I've been trying to analyze a c# project that is build with <a href=""https://travis-ci.org"" rel=""nofollow noreferrer"">travis CI</a> and analyzed in <a href=""https://sonarcloud.io/"" rel=""nofollow noreferrer"">sonarcloud</a>.</p>
<p>I've set up travis (see: <a href=""https://travis-ci.org/ShiveringSquirrel/heroes-app-webapi"" rel=""nofollow noreferrer"">https://travis-ci.org/ShiveringSquirrel/heroes-app-webapi</a>) to build and it seems to work fine.</p>
<h2>Configuration</h2>
<p>See <a href=""https://github.com/ShiveringSquirrel/heroes-app-webapi/blob/master/.travis.yml"" rel=""nofollow noreferrer"">.travis.yml</a></p>
<pre><code>language: csharp
solution: heroes-app-webapi.sln
dist: trusty
sudo: required

mono:
  - latest

install:
  - nuget restore heroes-app-webapi.sln
  - nuget install NUnit.Console -Version 3.9.0 -OutputDirectory testrunner

addons:
  sonarcloud:
    organization: &quot;shiveringsquirrel-github&quot;
    token:
      secure: $SONAR_TOKEN

script:
  - msbuild /p:Configuration=Release /target:rebuild heroes-app-webapi.sln
  - mono ./testrunner/NUnit.ConsoleRunner.3.9.0/tools/nunit3-console.exe ./heroes-app-webapi.Tests/bin/Release/heroes-app-webapi.Tests.dll
  - sonar-scanner -Dsonar.projectVersion=1.$TRAVIS_BUILD_NUMBER

cache:
  directories:
    - '$HOME/.sonar/cache'

git:
  clone: true
  quiet: false
  depth: false
  submodules: true

# blocklist
branches:
  except:
  - legacy
  - experimental

# safelist
branches:
  only:
  - master
  - stable
</code></pre>
<p>See <a href=""https://github.com/ShiveringSquirrel/heroes-app-webapi/blob/master/sonar-project.properties"" rel=""nofollow noreferrer"">sonar-project.properties</a></p>
<pre><code>sonar.projectKey=ShiveringSquirrel_heroes-app-webapi
sonar.projectName=heroes-app-webapi
#sonar.projectVersion=1.0
sonar.projectDescription=The backend API for the Heroes test application

sonar.links.homepage=https://github.com/ShiveringSquirrel/heroes-app-webapi
sonar.links.ci=https://travis-ci.org/ShiveringSquirrel/heroes-app-webapi
sonar.links.scm=https://github.com/ShiveringSquirrel/heroes-app-webapi
sonar.links.issue=https://github.com/ShiveringSquirrel/heroes-app-webapi/issues

#sonar.sources=.
#sonar.sources=src/main
#sonar.tests=src/test
sonar.sources=heroes-app-webapi
sonar.tests=heroes-app-webapi.Tests

sonar.scm.provider=git
sonar.scm.forceReloadAll=true

sonar.dotnet.visualstudio.testProjectPattern=*.Test
sonar.language=cs
sonar.sourceEncoding=UTF-8
sonar.verbose=true
sonar.exclusions=**/*.xml
sonar.inclusions=**/*.cs

sonar.cs.nunit.reportsPaths=TestResult.xml
</code></pre>
<h2>Building</h2>
<p>The full build log for travis: <a href=""https://travis-ci.org/ShiveringSquirrel/heroes-app-webapi"" rel=""nofollow noreferrer"">See full build log</a></p>
<p>Some relevant snippets form the log:</p>
<pre><code>$ mono --version
Mono JIT compiler version 5.20.1.19 (tarball Thu Apr 11 09:05:42 UTC 2019)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
    TLS:           __thread
    SIGSEGV:       altstack
    Notifications: epoll
    Architecture:  amd64
    Disabled:      none
    Misc:          softdebug 
    Interpreter:   yes
    LLVM:          yes(600)
    Suspend:       hybrid
    GC:            sgen (concurrent by default)
$ msbuild /version
Microsoft (R) Build Engine version 16.0.0.0 for Mono
Copyright (C) Microsoft Corporation. All rights reserved.
</code></pre>
<p>Building with msbuild</p>
<pre><code>$ msbuild /p:Configuration=Release /target:rebuild heroes-app-webapi.sln
....
    302 Warning(s)
    0 Error(s)
Time Elapsed 00:00:06.94
The command &quot;msbuild /p:Configuration=Release /target:rebuild heroes-app-webapi.sln&quot; exited with 0.
</code></pre>
<p>Unit testing</p>
<pre><code>$ mono ./testrunner/NUnit.ConsoleRunner.3.9.0/tools/nunit3-console.exe ./heroes-app-webapi.Tests/bin/Release/heroes-app-webapi.Tests.dll
....
Test Run Summary
  Overall result: Passed
  Test Count: 25, Passed: 25, Failed: 0, Warnings: 0, Inconclusive: 0, Skipped: 0
  Start time: 2019-07-14 21:00:34Z
    End time: 2019-07-14 21:00:36Z
    Duration: 2.559 seconds
Results (nunit3) saved as TestResult.xml
The command &quot;mono ./testrunner/NUnit.ConsoleRunner.3.9.0/tools/nunit3-console.exe ./heroes-app-webapi.Tests/bin/Release/heroes-app-webapi.Tests.dll&quot; exited with 0.
</code></pre>
<p>Sonar-scanner</p>
<pre><code>$ sonar-scanner -Dsonar.projectVersion=1.$TRAVIS_BUILD_NUMBER
...
21:00:40.716 DEBUG: Plugins:
...
21:00:40.717 DEBUG:   * SonarC# 7.15.0.8572 (csharp)
...
21:00:46.518 DEBUG: 77 non excluded files in this Git repository
21:00:46.541 DEBUG: 'heroes-app-webapi/Global.asax.cs' indexed with language 'cs'
21:00:46.549 DEBUG: 'heroes-app-webapi/Attributes/JwtAuthenticationAttribute.cs' indexed with language 'cs'
...
21:00:46.802 INFO: 30 files indexed
21:00:46.803 INFO: 0 files ignored because of inclusion/exclusion patterns
21:00:46.804 INFO: 0 files ignored because of scm ignore settings
21:00:46.805 INFO: Quality profile for cs: Sonar way
21:00:46.806 INFO: ------------- Run sensors on module heroes-app-webapi
...
21:00:51.019 INFO: Sensor C# Properties [csharp]
21:00:51.021 WARN: No Roslyn issues report found for this project.
...
21:00:51.052 INFO: Sensor C# Unit Test Results Import [csharp]
21:00:51.054 INFO: Parsing the NUnit Test Results file /home/travis/build/ShiveringSquirrel/heroes-app-webapi/./TestResult.xml
...
21:00:51.713 INFO: SCM provider for this project is: git
21:00:51.715 INFO: 27 files to be analyzed
...
21:00:52.065 INFO: 27/27 files analyzed
21:00:52.068 INFO: Calculating CPD for 0 files
21:00:52.078 INFO: CPD calculation finished
21:00:52.235 INFO: Analysis report generated in 151ms, dir size=190 KB
21:00:52.288 INFO: Analysis report compressed in 51ms, zip size=56 KB
21:00:52.289 INFO: Analysis report generated in /home/travis/build/ShiveringSquirrel/heroes-app-webapi/.scannerwork/scanner-report
21:00:52.290 DEBUG: Upload report
21:00:52.630 DEBUG: POST 200 https://sonarcloud.io/api/ce/submit?organization=shiveringsquirrel-github&amp;projectKey=ShiveringSquirrel_heroes-app-webapi&amp;projectName=heroes-app-webapi | time=338ms
21:00:52.633 INFO: Analysis report uploaded in 343ms
21:00:52.637 INFO: ANALYSIS SUCCESSFUL, you can browse https://sonarcloud.io/dashboard?id=ShiveringSquirrel_heroes-app-webapi
21:00:52.637 INFO: Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report
21:00:52.639 INFO: More about the report processing at https://sonarcloud.io/api/ce/task?id=AWvySdH4BABcSdLoSktk
21:00:52.640 DEBUG: Report metadata written to /home/travis/build/ShiveringSquirrel/heroes-app-webapi/.scannerwork/report-task.txt
21:00:52.646 DEBUG: Post-jobs : 
21:00:52.650 INFO: Analysis total time: 11.885 s
21:00:52.652 INFO: ------------------------------------------------------------------------
21:00:52.656 INFO: EXECUTION SUCCESS
21:00:52.658 INFO: ------------------------------------------------------------------------
21:00:52.662 INFO: Total time: 15.232s
21:00:52.860 INFO: Final Memory: 34M/349M
21:00:52.860 INFO: ------------------------------------------------------------------------
21:00:52.860 DEBUG: Execution getVersion
21:00:52.860 DEBUG: Execution stop
The command &quot;sonar-scanner -Dsonar.projectVersion=1.$TRAVIS_BUILD_NUMBER&quot; exited with 0.
</code></pre>
<p>So to me it all looks pretty good, only in sonarcloud.io (<a href=""https://sonarcloud.io/dashboard?id=ShiveringSquirrel_heroes-app-webapi"" rel=""nofollow noreferrer"">https://sonarcloud.io/dashboard?id=ShiveringSquirrel_heroes-app-webapi</a>) I see nothing is analyzed.</p>
<p>Not even lines of code, it did update my build number and other settings. But no report or analysis. If I look at the background task:</p>
<pre><code>21:00:52.639 INFO: More about the report processing at https://sonarcloud.io/api/ce/task?id=AWvySdH4BABcSdLoSktk
</code></pre>
<p>It says &quot;success&quot;. The other thing I've tried to investigate is the one warning I have:</p>
<pre><code>21:00:51.021 WARN: No Roslyn issues report found for this project.
</code></pre>
<p>But it seems to me from the log that everything is analyzed properly...
Any ideas?</p>
",https://stackoverflow.com/questions/57036115/analyzing-c-project-using-travis-and-sonarcloud-gives-no-lines-of-code,"['c#', '.net', 'msbuild', 'travis-ci', 'sonarcloud']",1115,False,4,0
Call `new` on a variable cast to a type in TypeScript,"<p>I'm writing some unit tests and I want to test that my constructor fails with invalid arguments at runtime.  If the constructor is called with invalid arguments in a TS project, it fails at compile time, so I first must cast it to <code>any</code>.</p>

<p><code>my-class.ts</code></p>

<pre class=""lang-ts prettyprint-override""><code>export default class MyClass {
    constructor(public value: 1 | 2 | 3) {
        if (!this.value || 
            isNaN(this.value) || 
            this.value &lt; 1 || this.value &gt; 3 || 
            parseInt(this.value) !== this.value) {
            throw new Error(`Invalid value: '${this.value}'`);
        }
    }
}
</code></pre>

<p><code>my-class.test.ts</code></p>

<pre class=""lang-ts prettyprint-override""><code>test('MyClass validates its constructor arguments', () =&gt; {
    expect(() =&gt; new (MyClass as any)()).toThrowErrorMatchingSnapshot();
    expect(() =&gt; new (MyClass as any)('abc')).toThrowErrorMatchingSnapshot();
    expect(() =&gt; new (MyClass as any)(null)).toThrowErrorMatchingSnapshot();
    // ...
});
</code></pre>

<p>I would like to clean this up so I only make one cast, by setting a local variable.</p>

<pre class=""lang-ts prettyprint-override""><code>test('MyClass validates its constructor arguments', () =&gt; {
    // this type declaration isn't right
    const MC = MyClass as any as { new: (...args: any[]) =&gt; MyClass };

    expect(() =&gt; new MC()).toThrowErrorMatchingSnapshot();
    expect(() =&gt; new MC('abc')).toThrowErrorMatchingSnapshot();
    expect(() =&gt; new MC(null)).toThrowErrorMatchingSnapshot();
    // ...
});
</code></pre>

<p>I vaguely remember writing a generic that had an type parameter expecting a class, and I thought this was how I wrote it--an object with a function called <code>new</code>, but I now can't find where I found that on the web, and I don't even remember which project it was I wrote it in in the first place.</p>

<p>At any rate, with this code TypeScript yells at me:</p>

<blockquote>
  <p>Cannot use 'new' with an expression whose type lacks a call or construct signature.ts(2351)</p>
</blockquote>

<p>I also tried changing <code>{ new: ... }</code> to <code>{ constructor: ... }</code> with the same result.</p>

<p>I can leave <code>MC</code> as <code>any</code> which is fine for unit testing, but I'd like to know how to do this in the future.</p>
",https://stackoverflow.com/questions/56603493/call-new-on-a-variable-cast-to-a-type-in-typescript,"['typescript', 'jestjs']",466,True,3,2
Transactions with NestJS and TypeORM - decorators and unit tesing,"<p>My Question is around transaction management using nestjs and Typeorm, my  db is postgres.</p>

<ol>
<li><p>Should I use decorators like @Transaction and @TransactionManager while doing transaction management. I heard that they are going to be removed in new releases.
<a href=""https://github.com/typeorm/typeorm/issues/3251"" rel=""nofollow noreferrer"">https://github.com/typeorm/typeorm/issues/3251</a></p></li>
<li><p>As a best practise how do we handle a transaction that is inserting or updating multiple tables. I see the following question
<a href=""https://stackoverflow.com/questions/53680665/nestjs-typeorm-database-transaction"">nestjs / TypeOrm database transaction</a>
Is this the right away, can somebody give me a full example. Should I inject connection to my service class and get EntityManager from it and pass it around?</p></li>
<li><p>What would be the right way for unit testing such an insert on two tables.</p></li>
</ol>

<p>I am right now using Transaction decorators from TypeOrm.
All my create code is in a single class, I want to be able to move the code for creation of  every entity to be moved to the entity's own service class and expect the transaction rollback still works.</p>

<pre><code>@Transaction({ isolation: ""SERIALIZABLE"" })
    async createProfile(createProfileDTO: CreateProfileDTO, @TransactionManager() manager?: EntityManager){
...
const profileRepository = manager.getRepository(Profile);
let savedProfile = await profileRepository.save&lt;Profile&gt;(profile);

identifier.profile = savedProfile;
 const identifierRepository = manager.getRepository(Identifier);
 let savedIdentifier = identifierRepository.save(identifier);

}
</code></pre>

<p>Alternatively, if I use</p>

<pre><code> await this.connection.transaction(async transactionalEntityManager =&gt; {
            profile = await this.createUserProfile(createProfileDTO, transactionalEntityManager);
            identifiers = await this.identifierService.createIdentifier(profile, createProfileDTO
                , transactionalEntityManager);
});
</code></pre>

<p>What is the best way to unit test the above code? </p>
",https://stackoverflow.com/questions/57211909/transactions-with-nestjs-and-typeorm-decorators-and-unit-tesing,"['transactions', 'nestjs', 'typeorm']",8786,True,3,1
How to properly unit test a Django middleware,"<p>I have to write unit tests for several Django Middlewares (Django > 1.10 styled middlewares).</p>

<p>Project is an API, done with Django==2.2.3 and djangorestframework==3.9.4, I'm using standard Django unit testing module, and APIRequestFactory() and APIClient() test functions from Django REST framework to create mock requests for my tests.</p>

<p>Here is an example of one middleware I want to test:</p>

<pre><code>from . import models

class BrowserId():

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if hasattr(request, 'COOKIES') and 'mydomain.bid' in request.COOKIES:
            bid = request.COOKIES.get('mydomain.bid', None)
        else:
            bid = None

        request.bid = models.BrowserId(bid) if bid else models.BrowserId.random()

        response = self.get_response(request)

        response.set_cookie(
            conf.BID_COOKIE_KEY,
            value=request.bid,
            max_age=conf.COOKIE_MAX_AGE,
            domain=conf.BID_COOKIE_DOMAIN
        )

        return response
</code></pre>

<p>I want to test:</p>

<ul>
<li><p>That browser ID has successfully been added to the request</p></li>
<li><p>That cookie has successfully been set on the response</p></li>
</ul>

<p>So, to be more precise, part of the tests would vaguely have to look like this:</p>

<pre><code>from rest_framework.test import APIRequestFactory, APIClient, APITestCase
from my_api.auth import middlewares, models

class MiddlewaresTestCase(APITestCase):

    def test_fresh_browser_id_request(self):
        ??? SOME CODE TO PROCESS THE REQUEST BY THE MIDDLEWARE 
        assert hasattr(request, 'bid')
        assert len(request.bid) == 30

    def test_existing_browser_id_request(self):
        req = APIRequestFactory().get('/')
        mock_bid: str = 'abcd1234'
        req.COOKIES = {cookie_key: mock_bid}
        ??? SOME CODE TO PROCESS THE REQUEST BY THE MIDDLEWARE
        assert hasattr(req, 'bid')
        assert req.bid == mock_bid

    def test_browser_id_response(self):
        mock_bid: str = 'abc123'
        ??? SOME CODE TO PROCESS THE REQUEST BY THE MIDDLEWARE
        ??? SOME CODE TO PROCESS THE REPONSE BY THE MIDDLEWARE
        response = APIClient().get('/')
        assert res.cookies.get(cookie_key) is not None
        assert res.cookies.get(cookie_key).value == mock_bid
</code></pre>

<p>etc.</p>

<p>But, as one can see, I don't know exactly how to individually do that. More precisely:</p>

<ul>
<li><p>I don't know what to pass as a <code>get_response</code> function when initializing the middleware. I know it is supposed to be the processing view function, or the next middleware, but I don't know how to pass that and anyway I want to test it regardless of the rest;</p></li>
<li><p>I don't know how to test only the processed request and not the returned response.</p></li>
</ul>
",https://stackoverflow.com/questions/57766951/how-to-properly-unit-test-a-django-middleware,"['django', 'unit-testing', 'django-rest-framework', 'middleware']",2914,True,3,1
DynamoDB and Unit Testing .NET core,"<p>We are implementing DynamoDB data store. For our unit tests we have got that covered for Web.API, services, repository layers. However, I have not found any mocking frameworks/unit test for DynamoDB for .NET Core, only to implement the local DynamoDB (<a href=""https://aws.amazon.com/blogs/aws/amazon-dynamodb-libraries-mappers-and-mock-implementations-galore/"" rel=""nofollow noreferrer"">https://aws.amazon.com/blogs/aws/amazon-dynamodb-libraries-mappers-and-mock-implementations-galore/</a>) Amazon indicates that it's best to run the local instance (Dynamo Local), however, this is not ideal for us, since we have Azure dev-ops pipelines in place. This causes other issues,like deleting tables for each test run, making sure the local db instance is running etc.</p>

<p>I was thinking of extending the DynamoDBclient, DynamoContext etc and then use these to simulate, however, this seems like a lot of work and I am not sure if it is worthwhile. Can anyone suggest an easier alternative or have come across a framework, or implemented a good unit testing framework for DynamoDB for .NET Core. We really don't want to go down the path to use the local DynamoDB on our build server. </p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/55463654/dynamodb-and-unit-testing-net-core,"['unit-testing', '.net-core', 'mocking', 'amazon-dynamodb']",3060,False,3,0
Can&#39;t run server and tests without modifying imports,"<p>I'm building a website with the bottle framework. I am using nosetests for my unit testing. However there is a problem I can't solve on my own. </p>

<p>I can't seem to find a way that allows me to run the tests without breaking my server. When I run my tests, I have to do relative imports for them to work, but they don't work when I start the server.</p>

<p>This is my folder structure:</p>

<pre><code>├── service
│   ├── __init__.py
│   ├── application.py
│   ├── main.py
│   ├── response_header.py
│   ├── global_data_loader.py
│   ├── renderer
│   │   ├── __init__.py
│   │   ├── header.py
│   │   ├── ....
│   ├── tests
│   │   ├── test_application.py
│   │   ├── ....

</code></pre>

<p>Here is how I import so my server works:</p>

<pre class=""lang-py prettyprint-override""><code>application.py --
from response_header import ResponseHeader
from global_data_loader import GlobalDataLoader
from renderer import Application
</code></pre>

<p>However, when I run nosetests, I get this message: 
<code>ModuleNotFoundError: No module named 'response_header'</code></p>

<p>So when I want nosetests to work, I have to change the imports to look like this: </p>

<pre class=""lang-py prettyprint-override""><code>application.py --
from .response_header import ResponseHeader
from .global_data_loader import GlobalDataLoader
from .renderer import Application
</code></pre>

<p>Then my nosetests work, but when I want to start my server I get this message: </p>

<pre><code>from .response_header import ResponseHeader
ImportError: attempted relative import with no known parent package
</code></pre>

<p>I have tried using sys.path.append in my tests, and it works, but I need a solution that doesn't involve PYTHONPATH or using os/sys</p>

<p>edit: i fixed it by moving my main.py I use to start the server to the root folder, above my service and tests module. now it works fine</p>
",https://stackoverflow.com/questions/56355684/cant-run-server-and-tests-without-modifying-imports,"['python', 'python-unittest', 'bottle', 'nose']",30,False,2,0
How to demonstrate or qualitatively test a Java class before packaging?,"<p>My current project contains an interface and an implementation of a RandomTextGenerator type (such as might be used in an adventure game to generate original character or place names).  I am using Maven to compile and package the project and JUnit 5 for unit testing.  I'd like to structure this project properly in order to open-source it (if only just to learn the proper setup).</p>

<p>My JUnit tests do a lot, but they can't <em>qualitatively</em> test the big question: do the randomly-generated names come out sounding good?</p>

<p>How should I test this?  Options I'm considering:</p>

<ul>
<li>Add a new class with a static void main() that generates and prints a bunch of these names to System.out.</li>
<li>Add a JUnit test that does the above and then ends with assertTrue(true).</li>
<li>Build a new project <em>outside</em> of this package, which imports the package and does the above.</li>
</ul>

<p>I'd like to know what's the generally-accepted best practice, given my intent to open-source this project.  Would consumers of my package want to see these tests, or not, and where?</p>
",https://stackoverflow.com/questions/56796569/how-to-demonstrate-or-qualitatively-test-a-java-class-before-packaging,"['java', 'testing']",43,False,2,0
Unit testing around DateTime windows in NUnit &amp; Moq,"<p>I am following along with the TDD <a href=""https://github.com/wix/tdd-katas"" rel=""nofollow noreferrer"">Kata 'Greeter'</a>, wherein I have to create a class with a method which returns a different output depending on the time of day it was called. So I have this class Greeter</p>

<pre><code>public class Greeter : Greeter
{
    public DateTime time
    {
        get
        {
            return DateTime.Now;
        }
    }

    public Greeter() { }

    public string greet(string name)
    {
        string greeting = ""Hello "";

        name = name.Substring(0, 1).ToUpper() + name.Substring(1);

        if(name.Length &gt; 36)
        {
            name = name.Substring(0, 35);
        }

        if(time.Hour &gt;= 6 &amp;&amp; time.Hour &lt;= 12)
        {
            greeting = ""Good morning"";
        } else if (time.Hour &gt;= 18 &amp;&amp; time.Hour &lt;= 22)
        {
            greeting = ""Good evening"";
        } else if (time.Hour &gt;=22 || time.Hour &lt; 6)
        {
            greeting = ""Good night"";
        }

        return $""{greeting} {name}"";
   }

}
</code></pre>

<p><code>Greeter</code> implements <code>IGreeter</code></p>

<pre><code>    public interface IGreeter
    {
        DateTime time
        {
            get;
        }
        string greet(string name);
    }
</code></pre>

<p>Now on the unit testing side of things, I have to test given different times of day to see the response: <code>Good morning ~</code> in the AM, <code>Good evening ~</code> in the evening, <code>Good night ~</code> at night, and <code>Hello ~</code> in the default case. </p>

<p>So my question is, how do I design these unit tests with these time constraints in mind without too much modifying of the class? From what I've been told, changing the class just to enable unit tests is considered code smell. Is there a way I can achieve this using NUnit and Moq? The best solution I've seen so far is to DI a time provider in the constructor, but I'd rather not have to supply the generic time provider in every instantiation just to enable the tests. </p>

<p>Any guidance would be greatly appreciated.   </p>
",https://stackoverflow.com/questions/55938644/unit-testing-around-datetime-windows-in-nunit-moq,"['c#', '.net', 'nunit', 'moq']",395,True,2,2
Should I mock IO or not?,"<p>Say I have a simple file based database <code>Monad</code>. I would define it as shown below.</p>

<pre><code>newtype MyDbFileBased a = MyDbFileBased {
        unMyDbDbFileBased :: ExceptT MyDbFileBasedError (ReaderT MyDbFileBasedEnv IO) a
    } deriving (
        Functor
    ,   Applicative
    ,   Monad
    ,   MonadError MyDbFileBasedError
    ,   MonadReader MyDbFileBasedEnv
    ,   MonadIO
    )
</code></pre>

<p>I have read that the above pattern (will post a link to the blog when I find it) is not recommended and that I should replace <code>IO</code> with a generic <code>Monad</code> like so.</p>

<pre><code>import qualified Data.ByteString as B

newtype MyDbFileBased m a = MyDbFileBased {
        unMyDbFileBased :: ExceptT MyDbFileBasedError (ReaderT MyDbFileBasedEnv m) a
    } deriving (
        Functor
    ,   Applicative
    ,   Monad
    ,   MonadError MyDbFileBasedError
    ,   MonadReader MyDbFileBasedEnv
    )

class Monad m =&gt; MonadFileBasedIO m where 
    readBytes :: FilePath -&gt; m B.ByteString 
    writeBytes :: FilePath -&gt; B.ByteString -&gt; m () 
    ...

instance MonadFileBasedIO IO where 
    readBytes = B.readFile
    writeBytes = B.writeFile
</code></pre>

<p>This will supposedly make unit testing easier. The advise is to mock IO in testing with something like as follows.</p>

<pre><code>data MockFS = EmptyDir
            | SingleFile FilePath String 
            deriving (Show)

newtype MockFileBasedIO a = MockFileBasedIO {
        unMockFileBasedIO :: State MockFS a
    } deriving (
        Functor
    ,   Applicative
    ,   Monad 
    ,   MonadState MockFS
    )

instance MonadFileBasedIO MockFileBasedIO where 
    readBytes pathReq = do
        dir &lt;- get
        case dir of 
            EmptyDir                 -&gt; fail ""file not found""
            SingleFile path contents -&gt; if pathReq == path 
                                            then pure (BU.fromString contents) 
                                            else fail ""file not found""

    writeBytes path = put . SingleFile path . BU.toString 
</code></pre>

<p>All this looks good to me until now. But then I want to add things like <code>catch</code> and <code>liftIO</code> to functions within <code>MyDbFileBased</code> type. I thought of adding <code>catchMonadFileBasedIO</code> and <code>liftMonadFileBasedIO</code> functions to <code>MonadFileBasedIO</code> typeclass and set <code>catchMonadFileBasedIO = catch</code> and <code>liftMonadFileBasedIO = liftIO</code> for <code>IO</code> monad. But then it brings in dependency on <code>MonadIO</code> and <code>Exception</code> typeclasses and the compiler tells me to add these typeclasses to function signatures of <code>catchMonadFileBasedIO</code> and <code>liftMonadFileBasedIO</code>. Also I would need to derive <code>MonadIO</code> from <code>MyDbFileBased m</code>. Then what's the point of replacing <code>IO</code> with a generic <code>Monad</code> in the first place?</p>

<p>I don't understand if I should be mocking <code>IO</code> in cases such as these or not. How do I use <code>liftIO</code> and <code>catch</code> if we mock it? Should I not catch exceptions in this module and cascade them to application level? </p>
",https://stackoverflow.com/questions/57683593/should-i-mock-io-or-not,"['unit-testing', 'haskell', 'exception']",457,True,2,1
How to properly use DoThrow(),"<p>Just start unit-testing currently, so I have two questions regarding this error within this question, I hope its ok.</p>

<ol>
<li><p>I have a class that has one positive test and three negative tests and one of this negative case is using doThrow to simulate failed repository, but it also causes the positive test to fail, is there any way to fix this?</p></li>
<li><p>Ideally, do the negative case and positive case must be separated into two class?</p></li>
</ol>

<p>I already googled about this but can't find any reference or even the same problem as me, already ask on discord, while I do find some fix for it, by making new class JUST for the negative doThrow case, but i'm looking for additional opinion.</p>

<p>here is  the example of the negative case</p>

<pre><code>@Test(expected = DAOException.class)
    public void testFail() throws ObjectNotEncypted, ObjectNotFound {
        List&lt;Long&gt; ids = new ArrayList&lt;Long&gt;();
        ids.add(id);

        Mockito.when(tempRepo.tempfunction(var)).thenReturn(Optional.of(expectedvalue));
        Mockito.when(tempRepo.tempfunction(var)).thenReturn(expectedvalue);
        Mockito.when(tempRepo.tempfunction(var)).thenReturn(null);
        Mockito.when(tempRepo.tempfunction(var)).thenReturn(1);
        Mockito.when(tempRepo.tempfunction(var)).thenReturn(1);
        Mockito.doThrow(DAOException.class).when(tempRepo).tempfunctionthatshouldfail(var);

        service.dofunction(ids);
    }
</code></pre>

<p>-- ADDITIONAL CODE
heres how i construct the config and declare the variable</p>

<pre><code>@Configuration
    static class classConfig {
        @Bean
        public service accountService() {
            return new serviceImpl();
        }

        @Bean
        public TempRepo tempRepo () {
            return Mockito.mock(TempRepo.class);
        }
}

@Autowired
    private Service service;

    @Autowired
    private TempRepo tempRepo ;
</code></pre>

<p>The expected result is all test cases should run, but i got one error, and the trace only one line, its this <code>com.project.common.exception.DAOException</code>
and this is the positive case part of the code.</p>

<p>Thank you in advance</p>
",https://stackoverflow.com/questions/57405331/how-to-properly-use-dothrow,"['java', 'unit-testing', 'junit']",571,True,1,2
Jasmine Angular component is undefined,"<p><em>I am a bit new to Angular 7 and totally new to it's unit testing framework Jasmine</em></p>

<p>So i have been following the docs of Jasmine and also some tutorials. I have component called <code>TestTableComponent</code>. Now the component is a bit hard-coded. Anyways, i think the issue i'm facing hardly has anything to do with the component itself, so i am not including the component's code here.</p>

<p>I created a testing class, inside <code>test-table.component.spec.ts</code>. The code is as follows :</p>

<pre><code>// Required Imports have been made. Not including as unnecessary.

describe('TestTableComponent',  async() =&gt; 
{
let component: TestTableComponent;
let fixture: ComponentFixture&lt;TestTableComponent&gt;;
let de: DebugElement;


beforeEach(async(() =&gt; 
{
    TestBed.configureTestingModule({declarations:[TestTableComponent],
    imports: [ReactiveFormsModule]}).compileComponents();
}));
beforeEach(() =&gt;
{
    fixture = TestBed.createComponent(TestTableComponent);
    component = fixture.componentInstance;

    de = fixture.debugElement;
})


it('should check if data is returned by the API')
{

    const result = await component.GetEmployees;
    expect(result).toBeDefined();
}
});
</code></pre>

<p>The issue here is that, when i execute <code>ng test</code>, it seems to run the test based on this class. In the console of the browser, i get one error(for which, <code>Jasmine</code> says <code>1 component is pending</code>) as follows :</p>

<blockquote>
  <p>Cannot read property <code>GetEmployees</code> of undefined.</p>
</blockquote>

<p>Now, this clearly means that <code>TestTableComponent</code> is never initialized. I am just wondering why? Is <code>beforeEach</code> not being executed? If it is, then why is <code>component</code> undefined ?</p>

<p><strong>UPDATE : Including the component's code</strong></p>

<p><strong>Test-table.component.ts</strong></p>

<pre><code>import { AfterViewInit, Component, OnInit, ViewChild, Inject } from '@angular/core';
import { MatPaginator, MatSort, MatTable, MatTableDataSource, MatDialogRef, Sort, ShowOnDirtyErrorStateMatcher } from '@angular/material';
import { MatDialog } from '@angular/material/dialog';
import { TestTableItem } from './test-table-datasource';
import { HttpClient, HttpParams } from '@angular/common/http';
import { UpdateModalDialogComponent } from '../update-modal-dialog/update-modal-dialog.component';
import { MessagePopUpComponent } from '../message-pop-up/message-pop-up.component';
@Component({
selector: 'app-test-table',
templateUrl: './test-table.component.html',
styleUrls: ['./test-table.component.css']
})
export class TestTableComponent implements AfterViewInit, OnInit {
@ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
@ViewChild(MatSort, { static: false }) sort: MatSort;
@ViewChild(MatTable, { static: false }) table: MatTable&lt;TestTableItem&gt;;
private myCollection: TestTableItem[] = [];

dataSource = new MatTableDataSource(this.myCollection);// Observable&lt;TestTableItem&gt;;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['id', 'fname', 'salary', 'age', 'image', 'actions'];
constructor(private http: HttpClient, private dialog:MatDialog) { }


ngOnInit() {

   this.GetAllEmployees();
 }

async GetAllEmployees()
{
 this.dataSource = await this.GetEmployees();
}
public async GetEmployees()
{
 this.myCollection = await this.http.get&lt;TestTableItem[]&gt;('http://localhost:22371/api/employee/GetEmployees/').toPromise();
return new MatTableDataSource(this.myCollection);

}
</code></pre>

<p><strong><em>Please note that i am not including all the functions inside the class, as that would make this post unnecessarily big!</em></strong></p>
",https://stackoverflow.com/questions/57377129/jasmine-angular-component-is-undefined,"['javascript', 'angular', 'jasmine']",5725,True,1,2
How can I mock FileReader with jest?,"<p>I've been struggling over the past couple of weeks with unit testing a file upload react component with jest. Specifically, I'm trying to test whether or not the method <a href=""https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL"" rel=""nofollow noreferrer"">onReadAsDataUrl</a> is being called from FileReader in one of my methods. This is an example method I am testing:</p>

<pre><code>loadFinalImage = async (file) =&gt; {
  const reader = new FileReader();
  reader.onloadend = () =&gt; {
    this.setState({
      imagePreviewUrl: reader.result,
      validCard: true,
    });
  };
  await reader.readAsDataURL(file);
}
</code></pre>

<p>This is how I am attempting to mock FileReader and test whether or not onReadAsDataUrl has been called:</p>

<pre><code>it('is a valid image and reader.onReadAsDataUrl was called', () =&gt; {
    const file = new Blob(['a'.repeat(1)], { type: 'image/png' });
    wrapper = shallow(&lt;ImageUpload /&gt;).dive();
    const wrapperInstance = wrapper.instance();
    const mockReader = jest.fn();
    jest.spyOn('FileReader', () =&gt; jest.fn());
    FileReader.mockImplementation(() =&gt; { return mockReader });
    const onReadAsDataUrl = jest.spyOn(mockReader, 'readAsDataURL');
    wrapperInstance.loadFinalImage(file);
    expect(onReadAsDataUrl).toHaveBeenCalled();
  });
</code></pre>

<p>After I run: <code>yarn jest</code>, I get the following test failure: </p>

<blockquote>
  <p>Cannot spyOn on a primitive value; string given.</p>
</blockquote>

<p>I assume I am getting this error because I am not importing <code>FileReader</code>, but I am not exactly sure how I would import it or mock it because <code>FileReader</code> is an interface. Here is an image of the test failure:
<a href=""https://i.stack.imgur.com/OXdfw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/OXdfw.png"" alt=""enter image description here""></a></p>

<p>I am a bit of a noob with jest, reactjs, and web development, but would love to learn how to conquer this problem. Some resources I have looked at so far are: <a href=""https://github.com/Shopify/quilt/issues/303"" rel=""nofollow noreferrer"">Unresolved Shopify Mock of FileReader</a>, <a href=""https://stackoverflow.com/questions/52859389/mock-new-function-with-jest"">How to mock a new function in jest</a>, and <a href=""https://stackoverflow.com/questions/15212348/how-do-i-write-filereader-test-in-jasmine"">Mocking FileReader with jasmine</a>.</p>

<p>Any help would be greatly appreciated! Thank you in advance.</p>
",https://stackoverflow.com/questions/58331840/how-can-i-mock-filereader-with-jest,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'filereader']",5170,True,1,2
Mocking inbound Jax-RS Response with Entity,"<p>I am trying to unit test a class that uses Jersey 2 Client + Moxy to call a REST service. I want to mock the response, which contains a large JSON object. The code is structured in such a way that I can override/mock the following method:</p>

<pre><code>protected Response doPost(String path, Entity&lt;?&gt; entity) {
    Invocation.Builder invocationBuilder = getRestInvocationBuilder(path);
    Response response = invocationBuilder.post(entity);
    return response;
}
</code></pre>

<p>I would like to somehow inject some example JSON data (ideally from a file) into the Response at this point, prior to <code>readEntity()</code> being called, so that I can test that the JSON data is correctly unmarshalled into the target object.</p>

<p>Is there any way to do this? Note that this is for unit testing and therefore I'm not interested in running a local server or other integration testing techniques.</p>

<p>I'm aware similar questions have been asked, but many seem out of date or have incomplete solutions. The closest solution suggested is to mock the <code>readEntity()</code> method of the Response, this will not work for me because it would involve creating an object of the desired type to return, rather than creating one from the example JSON data.</p>
",https://stackoverflow.com/questions/58115808/mocking-inbound-jax-rs-response-with-entity,"['java', 'json', 'jersey-2.0', 'moxy']",432,False,1,0
Unable to mock HugSQL generated database functions with Midje,"<p>I'm having a problem mocking database access functions generated from HugSQL templates with the Conman helper library. These functions are defined at runtime like this:</p>

<p><code>(conman/bind-connection *db* file)</code></p>

<p>In my case, I'm unit testing this service function:</p>

<pre><code>(defn create-user [user]
  (do (-&gt; user
          (password-service/assoc-salt-and-hash)
          (dissoc :password)
          (assoc :is-admin false)
          (db/create-user!))
      (select-keys user [:firstname :lastname :email])))
</code></pre>

<p>In which the <code>db/create-user!</code> function is generated by Conman. However, when trying to mock out that function with this Midje test, I'm getting the following error message:</p>

<pre><code>(fact ""calls db function with created password fields and without plaintext password""
               (create-user user) =&gt; (select-keys user [:firstname :lastname :email])
               (provided
                 (password/assoc-salt-and-hash (as-checker (contains user))) =&gt; (merge user salt-and-hash)
                 (db/create-user! (as-checker (contains user-to-db))) =&gt; user-to-db))
</code></pre>

<pre><code>FAIL at (user.clj:24)
You never said #'create-user! would be called with these arguments:
    [{:firstname ""asd"", :lastname ""lol"", :email ""email@email.com"", :password-salt #object[""[B"" 0x5074bde0 ""[B@5074bde0""], :password-hash #object[""[B"" 0x60f8a634 ""[B@60f8a634""], :is-admin false}]

FAIL at (user.clj:25)
These calls were not made the right number of times:
    (db/create-user! (as-checker (contains user-to-db))) [expected at least once, actually never called]
nil
FAILURE: 2 checks failed.  (But 1 succeeded.)
[Completed at 20:27:05]
</code></pre>

<p>I'm referencing the dynamically created and mocked function exactly similarly from both the service and the test, but midje doesn't recognize it as being the same function. I also tried referencing the function via the var (<code>#'musician.user.db/create-user!</code>), and using the full path <code>musician.user.db/create-user!</code> from both the service and test, but neither of those worked either. The service code does work when tested from the REST API and the REPL, I just can't get this test set up.</p>

<p>It seems that the problem is that midje is unable to mock the function as it is not known before runtime. Is this merely a problem of referencing the function correctly, or it is just not possible to mock out these funtions with Midje?</p>
",https://stackoverflow.com/questions/54664661/unable-to-mock-hugsql-generated-database-functions-with-midje,"['clojure', 'midje', 'hugsql']",168,False,1,0
Mock datas on IMongoCollection Substitute,"<p>I’m still a beginner in C# and unit testing and I have a problem that I don’t know how to solve.
I've a Mongo Database and I just want to mock this database.
I’ll start by showing you my code before I explain my problem.</p>

<p>Here is my unit test class:</p>

<pre><code>private FollowManager _followManager;
private FollowsDao _followSubstitute;
private UsersDao _userSubstitute;
private IMongoDatabase _database;
private IMongoCollection&lt;Follow&gt; _followMongoCollection;
private IMongoCollection&lt;User&gt; _userMongoCollection;

[OneTimeSetUp]
public void OneTimeSetup()
{
    _database = Substitute.For&lt;IMongoDatabase&gt;();
    _followMongoCollection = Substitute.For&lt;IMongoCollection&lt;Follow&gt;&gt;();
    _userMongoCollection = Substitute.For&lt;IMongoCollection&lt;User&gt;&gt;();
    _followSubstitute = new FollowsDao(_database, _followMongoCollection);
    _userSubstitute = new UsersDao(_database, _userMongoCollection);
    _followManager = new FollowManager(_followSubstitute, _userSubstitute);
}

[TestCase(1, 2)]
[TestCase(3, 4)]
public void AssertThatBuildFollowReturnsValidFollow(int followerId, int followedId)
{
    UserFollow userFollow = new UserFollow {Follower = followerId, Followed = followedId};
    Follow follow = _followManager.BuildFollow(userFollow);

    Assert.IsNotNull(follow);
}
</code></pre>

<p>Here is my function that I want to test in my <code>FollowManager</code>:</p>

<pre><code>public Follow BuildFollow(UserFollow follow)
{
    User follower = _userDao.FindUserByNumber(follow.Follower).Result;
    User followed = _userDao.FindUserByNumber(follow.Followed).Result;
    Follow newFollow = new Follow { Follower = follower, Followed = followed, Date = DateTime.Now };

    InsertOrUpdateFollow(newFollow);

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

<p>The <code>FindUserByNumber</code> method will search in the database for a user that matches the id passed as a parameter:</p>

<pre><code>public async Task&lt;User&gt; FindUserByNumber(int number)
{
    List&lt;User&gt; result = await _collection.Find(user =&gt; user.Number == number &amp;&amp; user.Active).ToListAsync();

    return result.FirstOrDefault();
}
</code></pre>

<p>My problem is:
When I call <code>Follow follow = _followManager.BuildFollow(userFollow);</code> in my unit test, this line <code>InsertOrUpdateFollow(newFollow);</code> in my manager throw an error. It's normal because properties <code>Follower</code> and <code>Followed</code> are null because my database is mocked. </p>

<p>I have a JSON file that contains the list of users of the database and I want to be able to recover my users from this file and not from the database.</p>

<p>With this, I've my users in my JSON file:</p>

<pre><code>List&lt;User&gt; users = JsonConvert.DeserializeObject&lt;List&lt;User&gt;&gt;(File.ReadAllText(@""C:\users-list-api-result.json""));
</code></pre>

<p>So, my question is:
How can I test this function with JSON mocked file ?</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/56331730/mock-datas-on-imongocollection-substitute,"['c#', 'mongodb', 'nsubstitute']",586,False,1,0
How to test in Karma without require.context,"<p>So I spent a long time in React land, with Jest as my test runner/environment. 
Flash forward to new job, and we're unit testing an Angular 8 app w/ Karma.</p>

<p>Much to my dismay, I come to find the default config for Angular, and every single guide out there suggests something close to this line:</p>

<pre><code>const context = require.context('../src/app', true, /\.spec\.ts$/);
</code></pre>

<p>So when I update a file within my app, Angular CLI/Webpack have to rebuild whatever, and then it re-executes my entire f-ing test suite, which is thousands of tests, again.</p>

<p>I'm looking around and I see that Karma understands the concept of finding and watching files, but it seems as if that would never work given this approach.</p>

<p>Problem is we need to run this code to setup the environment:</p>

<pre><code>import 'zone.js/dist/zone';
import 'zone.js/dist/zone-testing';
import 'core-js/proposals/reflect-metadata';

import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

getTestBed().resetTestEnvironment();
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
</code></pre>

<p>Anybody have differential file watching / test running in Angular w/ Karma? If so, how it do???</p>

<p>Is there an easy way to run this setup code similar to Jest's <a href=""https://jestjs.io/docs/en/configuration#setupfilesafterenv-array"" rel=""nofollow noreferrer"">setupFilesAfterEnv</a>?</p>

<p>Relevant Karma config (I don't use NG CLI, test.ts has the content above):</p>

<pre><code>    frameworks: ['parallel', 'jasmine'],

    plugins: [
      require('ts-loader'),
      require('karma-jasmine'),
      require('karma-webpack'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-spec-reporter'),
      require('karma-parallel'),
    ],

    files: [{ pattern: './test/index.ts', watched: false }],

    preprocessors: {
      './test/index.ts': ['webpack'],
    },
    webpack: karmaConfig(),

    webpackMiddleware: {
      stats: 'errors-warnings',
    }
</code></pre>
",https://stackoverflow.com/questions/57683304/how-to-test-in-karma-without-require-context,"['angular', 'karma-jasmine', 'karma-runner', 'karma-webpack']",1656,True,1,1
Encrypt/Decrypt with AES-GCM using OpenSSL,"<p>I am writing an AES-GCM class for my application. The requirements constrain me to C++98 and static keys. I am having trouble unit testing the code I wrote. I am not able encrypt a test string and decrypt it back to its original form. What am I doing wrong here using OpenSSL EVP?</p>

<p>AES class, here are the juicy bits:</p>

<pre><code>/**
 * @brief ctor for aescipher class
 *
 * @params secret      secret cryptographic key
 * @params secret_len  array length of secret
 * @params iv          initialization vector (note, For a given key, the
 *                     IV MUST NOT repeat.)
 * @params iv_len      array length of iv
 */
aescipher::aescipher(const uint8_t* secret, size_t secret_len,
                     const uint8_t* iv, size_t iv_len)
:    mSecretSize(secret_len)
,    mSecret(new uint8_t[secret_len])
,    mIVSize(iv_len)
,    mIV(new uint8_t[iv_len])
{
    memcpy(mSecret, secret, mSecretSize);
    memcpy(mIV, iv, mIVSize);
}

aescipher::~aescipher()
{
    delete [] mSecret;
    mSecret = NULL;

    delete [] mIV;
    mIV = NULL;
}

/**
 * @brief generates a random 16-octet array suitable to use as an AES-GCM integrity check
 *
 * @param iv   unsigned 8-octet array for iv
 *
 * @returns    boolean - RAND_bytes() success
 */
/* static */ bool aescipher::generateIV(uint8_t iv[8])
{
    return (RAND_bytes(iv, 8) == 1);
}

/**
 * @brief encrypt data and aad using AES-GCM
 *
 * @param src      data to be encrypted
 * @param src_len  array length of src
 * @param aad      additional authenticated data included but not encrypted (optional/nullable)
 * @param aad_len  array length of aad
 * @param dst      destination data array for encrypted data
 * @param dst_len  array length of dst
 * @param tag      16 octet data array for Authentication Tag (Integrity Check Value per spec)
 *
 * @return         number of bytes written to dst
 */
size_t aescipher::encrypt(const uint8_t* src, size_t src_len,
                          const uint8_t *aad, size_t aad_size,
                          uint8_t* dst, size_t dst_len,
                          uint8_t tag[16])
{
    if (!src || !src_len || !dst || !dst_len) return 0;
    if (src_len &gt; dst_len) return 0;

    int cipher_len = 0;
    int len = 0;
    EVP_CIPHER_CTX* context = EVP_CIPHER_CTX_new();
    if (context == NULL) return 0;

    EVP_EncryptInit_ex(context, EVP_aes_128_gcm(), NULL, NULL, NULL);
    // set secret key and IV lengths
    EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_SET_IVLEN, mIVSize, NULL);
    EVP_CIPHER_CTX_set_key_length(context, (int)mSecretSize);
    // initialize secret key and IV
    EVP_EncryptInit_ex(context, NULL, NULL, mSecret, mIV);
    // Provide AAD if supplied
    if (aad &amp;&amp; aad_size) {
        if (!EVP_EncryptUpdate(context, NULL, &amp;len, aad, aad_size))
            goto AES_ERROR;
    }

    if (!EVP_EncryptUpdate(context, dst, &amp;len, src, src_len)) {
        goto AES_ERROR;
    }
    cipher_len = len;

    // There may be some final data left to encrypt if the input is
    // not an exact multiple of the block size.
    if (!EVP_EncryptFinal_ex(context, dst + len, &amp;len))
        goto AES_ERROR;
    //Normally ciphertext bytes may be written during finalization,
    // but this does not occur in GCM mode, so we make do manually.
    cipher_len += len;
    // Get the tag
    if (!EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_GET_TAG, 16, tag))
        goto AES_ERROR;

    EVP_CIPHER_CTX_free(context);
    return cipher_len;

AES_ERROR:
    EVP_CIPHER_CTX_free(context);
    return 0;
}

/**
 * @brief convenience encrypt() function omitting AAD params
 *
 * @param src      data to be encrypted
 * @param src_len  array length of src
 * @param dst      destination data array for encrypted data
 * @param dst_len  array length of dst
 * @param tag      16 octet data array for Authentication Tag (Integrity Check Value per spec)
 *
 * @return         number of bytes written to dst
 */
size_t aescipher::encrypt(const uint8_t* src, size_t src_len,
                          uint8_t* dst, size_t dst_len,
                          uint8_t tag[16])
{
    return encrypt(src, src_len, NULL, 0, dst, dst_len, tag);
}


/**
 * @brief decrypt AES-GCM encrypted data
 *
 * @param src      encrypted data array
 * @param src_len  array length of src
 * @param dst      destination array of decrypted data
 * @param dst_len  array length of dst
 * @param tag      16 octet data array for Authentication Tag (Integrity Check Value per spec)
 * @param aad      additional authenticated data received
 * @param aad_len  array length of aad
 *
 * @return         bytes written to dst
 */
size_t aescipher::decrypt(const uint8_t* src, size_t src_len,
                          uint8_t* dst, size_t dst_len,
                          uint8_t* aad, size_t aad_len,
                          uint8_t tag[16])
{
    if (!src || !src_len || !dst || !dst_len) return 0;
    if (src_len &gt; dst_len) return 0;

    int output_len = 0;
    int temp_len = 0;

    EVP_CIPHER_CTX* context = EVP_CIPHER_CTX_new();
    if (context == NULL) return 0;

    EVP_DecryptInit_ex(context, EVP_aes_128_gcm(), NULL, NULL, NULL);

    // set secret key and IV lengths
    EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_SET_IVLEN, mIVSize, NULL);
    EVP_CIPHER_CTX_set_key_length(context, (int)mSecretSize);
    // initialize secret key and IV
    EVP_DecryptInit_ex(context, NULL, NULL, mSecret, mIV);

    // Provide AAD if supplied
    if (!EVP_DecryptUpdate(context, NULL, &amp;temp_len, aad, aad_len)) {
        goto AES_ERROR;
    }
    if (!EVP_DecryptUpdate(context, dst, &amp;temp_len, src, src_len)) {
        goto AES_ERROR;
    }
    output_len = temp_len;

    // Set expected tag value.
    if(!EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_SET_TAG, 16, tag)) {
        goto AES_ERROR;
    }
    // Finalise the decryption. A positive return value indicates success,
    // anything else is a failure - the plaintext is not trustworthy.
    if (EVP_DecryptFinal_ex(context, dst + temp_len, &amp;temp_len) &lt;= 0){
        goto AES_ERROR;
    }
    output_len += temp_len;

    EVP_CIPHER_CTX_free(context);
    return output_len;

AES_ERROR:
    EVP_CIPHER_CTX_free(context);
    return 0;
}
</code></pre>

<p>Now, for the unit test.</p>

<p>FYI, I am not generating an IV for the unit test because I have Base64 encoded the encrypted data to store in the unit test source, therefore, I need to use a static IV with it. I just need to test the class. Don't worry, generating a unique IV will happen at a higher level. There is no AAD at this point in the tests.</p>

<p><code>Base64</code> and all undefined classes are unit tested and functional, so their definitions are irrelevant to the question. </p>

<p>Secret key I'm using is:</p>

<pre><code>const unsigned char *secret = reinterpret_cast&lt;const unsigned char*&gt;(""Open** Sesame**"");
</code></pre>

<p>Encrypt test (passes tests, but <code>encrypted_data</code> may actually be invalid data!):</p>

<pre><code>const unsigned char *msg = reinterpret_cast&lt;const unsigned char*&gt;(
      ""Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe."");
std::string encrypted_msg(
""WFcN70vG6REhBj6ccvXpvoF3UzeMOahuKpBulwyAxMG6Xx9ttt4WQtwvTbi27RvnHd3NxaJ2CvfzOgZAFxMfU/t8hc9smLBryNPTWXSVvG7+HF+hrGP9dwVaDX36MYdsiZV+7BdJnJ6EIGhTBnmWWtReheC5Ju/ledYymChmqQ=="");
const size_t msg_len = 127;
size_t ciphertext_len = 256;
unsigned char ciphertext[ciphertext_len];
memset(ciphertext, 0, sizeof(ciphertext));

uint8_t iv[8], tag[16];
memset(iv, 1, sizeof(iv));
aescipher cipher(secret, secretlen, iv, sizeof(iv));
size_t bytes = cipher.encrypt(msg, msg_len, ciphertext, ciphertext_len, tag);

unsigned char encrypted_data[ciphertext_len];
(void)Base64::decode(encrypted_msg.c_str(), encrypted_msg.length(), encrypted_data, ciphertext_len);

TK_assertTrue(memcmp(ciphertext, encrypted_data, bytes) == 0);
TK_assertTrue(bytes == msg_len);
</code></pre>

<p>Decrypt test (does not pass):</p>

<pre><code>std::string decrypted_msg(
    ""Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe."");
std::string encoded_msg(
    ""WFcN70vG6REhBj6ccvXpvoF3UzeMOahuKpBulwyAxMG6Xx9ttt4WQtwvTbi27RvnHd3NxaJ2CvfzOgZAFxMfU/t8hc9smLBryNPTWXSVvG7+HF+hrGP9dwVaDX36MYdsiZV+7BdJnJ6EIGhTBnmWWtReheC5Ju/ledYymChmqQ=="");
std::string gcm_tag(""hDlT5X7CGPwoPmVZSP2ezQ=="");
const size_t msg_len = 127;
uint8_t iv[8], tag[16], enc_msg[msg_len], msg[msg_len], aad[msg_len];

// decode encrypted data
Base64::decode(encoded_msg.c_str(), encoded_msg.length(), enc_msg, msg_len);
Base64::decode(gcm_tag.c_str(), gcm_tag.length(), tag, sizeof(tag));

memset(iv, 1, sizeof(iv));
aescipher cipher(secret, secretlen, iv, sizeof(iv));
size_t bytes = cipher.decrypt(enc_msg, msg_len, msg, msg_len, aad, msg_len, tag);
TK_assertTrue(bytes == msg_len);
TK_assertTrue(strncmp(reinterpret_cast&lt;const char*&gt;(msg), decrypted_msg.c_str(), bytes) == 0);
</code></pre>

<p>Note, on the decrypt unit test, <code>aescipher::decrypt</code> fails in <code>EVP_DecryptFinal_ex(context, dst + temp_len, &amp;temp_len)</code>.</p>
",https://stackoverflow.com/questions/54000689/encrypt-decrypt-with-aes-gcm-using-openssl,"['c++', 'openssl', 'aes', 'c++98', 'aes-gcm']",3594,False,1,0
Best way to unit test data analysis with database calls,"<p>I have a bunch of classes that all look somewhat like this:</p>

<pre><code>
class FakeAnalysis(Analysis):

    def __init__(self, dbi, metric: str, constraints: dict) -&gt; None:
        super().__init__(dbi)
        self.metric = metric
        self.constraints = constraints.copy()

    def load_data(self) -&gt; pd.DataFrame:

        data = self.dbi.select_data(
            {""val""}, {""period""}, **self.constraints
        )

        return data

    def run(self) -&gt; namedtuple:
        """"""Do some form of dataframe transformation""""""""
        data = self.load_data()
        df = data.pivot_table(columns='period',values='val',index='product_tag')
        return namedtuple(""res"", ['df'])(**{""df"": df})
</code></pre>

<p>They all take in a metric, constraints and a database interface class (dbi) as <code>__init__</code> arguments. They all load the data necessary by fetching the data through the dbi and then do some sort of data transformation on the resulting dataframe before returning it as a namedtuple containing the transformed data and any other byproducts (i.e. could be multiple dataframes).</p>

<p>The question is: what is the best way to unit test such code? The errors are usually the result of a combination of constraints resulting in unexpected data that the code does not know how to deal with. Should I just test each class with randomly generated constraints and see if it crashes? Or should I create a mock database interface which returns fixed data for a few different constraints and ensure the class returns the results expected for just these constraints? The latter doesn't seem of much use to me although it would be more along the lines of unit testing best practice... 
Any better ideas?</p>
",https://stackoverflow.com/questions/59486659/best-way-to-unit-test-data-analysis-with-database-calls,"['python', 'python-3.x', 'unit-testing', 'mocking', 'python-unittest']",65,True,1,1
Stubbing function to return something acceptable for .promise(),"<p>I'm running tests and I'm stubbing a function that calls the AWS sqs.deleteMessage function.  .promise() is called on the call to this function.  Every time I run my tests with the coverage I notice that it jumps to the catch block thus an error must be occurring on my .promise() call.</p>

<p>I've tried stubbing the function to resolve the promise but that doesn't seem to work.  I've tried returning data as well and still have the same issue.</p>

<p>Below is an example of the code I'm trying to test. It never reaches the logger.info() line</p>

<p>fooObj.js</p>

<pre><code>const foo = async (req) =&gt; {
  try{
    let res = await bar.deleteMessage(handle).promise();
    logger.info(""Sqs result message "" + JSON.stringify(res));
  } catch(error){
   #catch block code
  }
}
</code></pre>

<p>Below is the code for bar.deleteMessage()
bar.js</p>

<pre><code>const aws = require('aws-sdk');
const sqs = new aws.SQS();

deleteMessage = function(handle){
  return sqs.deleteMessage({
    ReceiptHandle: handle 
   });
}
</code></pre>

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

<pre><code>const fooObj = require('foo')
const barObj = require('bar')
jest.mock('bar')

describe('foo test', ()=&gt;{
  test('a test' , ()=&gt;{
    barObj.deleteMessage.mockImplementation(()=&gt;{
      return Promise.resolve({status:200})
    });

    return fooObj.foo(req).then(data=&gt;{
      #Expect statements here
    })
  }
}
</code></pre>

<p>So I would like the logger.info line to be reached in coverage but I assume the issue has to do with how I'm stubbing the bar.deleteMessage function.  I could use the aws-sdk-mock but I feel like I'm violating unit testing principles by mocking the sqs call that is in another file and the proper way to do it would simply be to properly stub the bar.deletemessage() function</p>
",https://stackoverflow.com/questions/55346261/stubbing-function-to-return-something-acceptable-for-promise,"['javascript', 'amazon-web-services', 'jestjs']",109,True,1,1
How to add instrumented test and unit test source sets to existing Android Studio project,"<p>When I create a new Gradle project, I get two additional directories in addition to the main app directory, one for unit testing, and one for instrumented testing e.g.</p>

<pre><code>java
  com.example.myapplication
  com.example.myapplication (androidTest) &lt;--- instrumented testing
  com.example.myapplication (test) &lt;---- unit testing
</code></pre>

<p>I guess these two directories basically contain the source sets which Android Studio will use Gradle to build and launch the tests with to a device. </p>

<p>However, I am working with a project which is lacking these two directories. I only have the app source directory.</p>

<p>All tutorials only show how to create tests assuming the two testing directories have been auto generated by Android Studio.</p>

<p>I need to know how to create these source set directories, but its all just magic to me, and I have no idea how to do it.</p>

<p>I guess in the worst case scenario, I can just create a new project, and port my code to it, but I hate doing that, because it's not really a solution, just a lame work-around.</p>

<p>I'm using the Android Gradle plugin, so I think I'm close, but no tomato. Any advice? </p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/56498802/how-to-add-instrumented-test-and-unit-test-source-sets-to-existing-android-studi,"['android', 'android-studio', 'gradle']",2461,True,1,2
Perplexing unit test code execution order when using ScalaCheck / ScalaTest clauses,"<p>I am facing the following perplexing behaviour when unit testing classes with variables. </p>

<p>For the sake of a simple example, let's assume I have the following class:</p>

<pre><code>// Case classes are not an alternative in my use case.
final class C(var i: Int = 0) {
  def add(that: C): Unit = {
    i += that.i
  }

  override def toString: String = {
    s""C($i)""
  }
}
</code></pre>

<p>For which I concocted the below trivial and seemingly harmless unit test:</p>

<pre><code>import org.junit.runner.RunWith
import org.scalacheck.Gen
import org.scalatest.junit.JUnitRunner
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{MustMatchers, WordSpec}

@RunWith(classOf[JUnitRunner])
class CUnitTest extends WordSpec with MustMatchers with GeneratorDrivenPropertyChecks {
  private val c: C = new C()

  forAll (Gen.choose(1, 100).map(new C(_))) { x =&gt;
    s""Adding $x to $c"" must {
      val expectedI = c.i + x.i

      c.add(x)

      s""result in its .i property becoming $expectedI"" in {
        c.i mustBe expectedI
      }
    }
  }
}
</code></pre>

<p>Where all test cases except the last fail:</p>

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

<p>For example, the first three test cases fail with the below results:</p>

<pre><code>org.scalatest.exceptions.TestFailedException: 414 was not equal to 68
org.scalatest.exceptions.TestFailedException: 414 was not equal to 89
org.scalatest.exceptions.TestFailedException: 414 was not equal to 151
</code></pre>

<p>Now, playing around the unit test and moving the <code>c.add(x)</code> part inside the <code>in</code> clause:</p>

<pre><code>import org.junit.runner.RunWith
import org.scalacheck.Gen
import org.scalatest.junit.JUnitRunner
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{MustMatchers, WordSpec}

@RunWith(classOf[JUnitRunner])
class CUnitTest extends WordSpec with MustMatchers with GeneratorDrivenPropertyChecks {
  private val c: C = new C()

  forAll (Gen.choose(1, 100).map(new C(_))) { x =&gt;
    s""Adding $x to $c"" must {
      val expectedI = c.i + x.i

      s""result in its .i property becoming $expectedI"" in {
        c.add(x)

        c.i mustBe expectedI
      }
    }
  }
}
</code></pre>

<p>And all test cases except the first fail:</p>

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

<p>For example, the second and the third test cases fail with the following messages:</p>

<pre><code>org.scalatest.exceptions.TestFailedException: 46 was not equal to 44
org.scalatest.exceptions.TestFailedException: 114 was not equal to 68
</code></pre>

<p>In addition, <code>c.i</code> doesn't seem to increase at all in the test case description as I intended and expected it to be. </p>

<p>Clearly, the order of execution inside ScalaTest clauses are not top-down. Something happens earlier or later than in the order it's written, or perhaps doesn't happen at all depending on which clause it is inside, yet I can't wrap my head around it. </p>

<p>What's going on and why? 
Furthermore, how could I achieve the desired behaviour (<code>c.i</code> increasing, all test cases passing)?</p>
",https://stackoverflow.com/questions/57730899/perplexing-unit-test-code-execution-order-when-using-scalacheck-scalatest-clau,"['scala', 'variables', 'scalatest', 'scalacheck', 'order-of-execution']",211,True,1,1
Why am I getting a &quot;Failed: Cannot read property &#39;subscribe&#39; of undefined&quot; while running tests?,"<p>I am relatively new to testing in Angular2+ and am setting up my files for testing. Since building the project, I've written a lot of code and am now trying to test parts of it. However, lots of those tests are now broken so I am now trying to delete the unneeded default tests or fix the ones that are useful. </p>

<p>This particular test won't run because it fails before it hits the It() testing method. I'm not sure what I'm missing, any help would be appreciated.</p>

<p>I am receiving this error:</p>

<pre><code>Failed: Cannot read property 'subscribe' of undefined
TypeError: Cannot read property 'subscribe' of undefined
    at AppComponent../src/app/app.component.ts.AppComponent.setupLanguageTranslation (src/app/app.component.ts:48:26)
    at AppComponent../src/app/app.component.ts.AppComponent.ngOnInit (src/app/app.component.ts:32:14)
    at checkAndUpdateDirectiveInline (node_modules/@angular/core/fesm5/core.js:22089:1)
    at checkAndUpdateNodeInline (node_modules/@angular/core/fesm5/core.js:23353:1)
    at checkAndUpdateNode (node_modules/@angular/core/fesm5/core.js:23315:1)
    at debugCheckAndUpdateNode (node_modules/@angular/core/fesm5/core.js:23949:1)
    at debugCheckDirectivesFn (node_modules/@angular/core/fesm5/core.js:23909:1)
    at Object.eval [as updateDirectives] (ng:///DynamicTestModule/AppComponent_Host.ngfactory.js:9:9)
    at Object.debugUpdateDirectives [as updateDirectives] (node_modules/@angular/core/fesm5/core.js:23901:1)
    at checkAndUpdateView (node_modules/@angular/core/fesm5/core.js:23297:1)
</code></pre>

<p>I've tried a variety of articles with similar issues including, but not limited to:</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/40142300/cannot-read-property-subscribe-of-undefined-after-running-npm-test-angular-2"">Cannot read property &#39;subscribe&#39; of undefined after running npm test (Angular 2 unit testing)</a></li>
<li><a href=""https://www.reddit.com/r/Angular2/comments/87w8su/what_am_im_doing_wrong_with_observables_and/"" rel=""nofollow noreferrer"">https://www.reddit.com/r/Angular2/comments/87w8su/what_am_im_doing_wrong_with_observables_and/</a></li>
<li><a href=""https://stackoverflow.com/questions/47942482/karma-typeerror-cannot-read-property-subscribe-of-undefined?rq=1"">karma TypeError &quot;Cannot read property &#39;subscribe&#39; of undefined&quot;</a></li>
</ul>

<p>App.component.ts</p>

<pre><code>export class AppComponent implements OnInit, OnDestroy {
    title = 'planox';
    showError = false;
    errorMessage = '';
    translatedText: string;

    constructor(private _translate: TranslateService,
                private utils: Utils) {}

    ngOnInit(): void {
        this.setupLanguageTranslation();
    }

    ngOnDestroy(): void {
        this._translate.onLangChanged.unsubscribe();
    }

    setupLanguageTranslation() {
        this.subscribeToLangChanged();
        // set language
        this._translate.setDefaultLang('en'); // set English as default
        this._translate.enableFallback(true); // enable fallback

        // set current language
        this.selectLang('en');

        this.utils.error.subscribe(response =&gt; {
            this.errorMessage = response;
            this.showError = true;
            setTimeout( () =&gt; {
                this.showError = false;
            }, 2000);
        });
    }

    selectLang(lang: string) {
        // set default;
        this._translate.use(lang);
    }

    subscribeToLangChanged() {
        // refresh text
        this.refreshText();
        return this._translate.onLangChanged.value;
    }

    refreshText() {
        // refresh translation when language change
        this.translatedText = this._translate.instant('hello world');
    }

}
</code></pre>

<p>app.component.spec.ts</p>

<pre><code>import {TestBed, async, ComponentFixture, inject} from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import {TranslateService} from './translate/translate.service';
import Utils from './shared/utils';
import {MockTranslateService} from './mocks/mockTranslateService';
import {MockUtils} from './mocks/mockUtils';
import {TRANSLATIONS} from './translate/translation';


describe('AppComponent', () =&gt; {
    let fixture: ComponentFixture&lt;AppComponent&gt;;

    beforeEach(async(() =&gt; {
        const mockTranslate = new MockTranslateService(TRANSLATIONS);
        TestBed.configureTestingModule({
            imports: [
                RouterTestingModule
            ],
            declarations: [
                AppComponent
            ],
            providers: [
                {provide: TranslateService, useValue: mockTranslate},
                {provide: Utils, useValue: MockUtils},
            ]
        });

        fixture = TestBed.createComponent(AppComponent);
        fixture.detectChanges();
    }));

    it('should create the app', () =&gt; {
        fixture = TestBed.createComponent(AppComponent);
        const app = fixture.debugElement.componentInstance;
        expect(app).toBeTruthy();
    });
});
</code></pre>

<p>Utils.ts:</p>

<pre><code>import {Subject, throwError} from 'rxjs';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {Role} from '../classes/role/role.enum';

export enum KEY_CODE {
    ENTER = 13,
    RIGHT_ARROW = 39,
    LEFT_ARROW = 37
}

@Injectable({
    providedIn: 'root'
})
export default class Utils {
    error: Subject&lt;string&gt; = new Subject&lt;string&gt;();

    constructor(private router: Router) {}

    handleError(service: string, error: Response | any, customMessage?: string) {
        const err = service + '::handleError' + '=  ' + error;
        this.error.next(customMessage);
        return throwError(error);
    }

    encodeBase64(value: any) {
        return btoa(JSON.stringify(value));
    }

    decodeBase64(value: any) {
        return atob(value);
    }

    navigateToDefaultPage(usersRole: Role) {
        if (usersRole === Role.Employee) {
            this.router.navigate(['/dashboardNavigation', {outlets: {dashNav: ['productionDashboard']}}]);
        } else if (usersRole === Role.Client) {
            this.router.navigate(['/clientDashboard']);
        } else if (usersRole === Role.OfficeAdmin) {
            this.router.navigate(['/dashboardNavigation', {outlets: {dashNav: ['enterpriseDashboard']}}]);
        } else {
            this.router.navigate(['/auth']);
        }
    }

    validateEmail(inputText: string) {
        const mailFormat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        if (inputText.match(mailFormat)) {
            return true;
        } else {
            return false;
        }
    }
}
</code></pre>

<p>mockUtils.ts</p>

<pre><code>import Utils from ""../shared/utils"";
import {Subject} from ""rxjs"";

export class MockUtils extends Utils {
    error = new Subject&lt;string&gt;();
}
</code></pre>

<p>Basically I need help setting up the structure of the testing page so that I can start writing useful tests.</p>

<p>I can provide any additional code you may need to help, wasn't sure what all would be needed for this.</p>
",https://stackoverflow.com/questions/55958449/why-am-i-getting-a-failed-cannot-read-property-subscribe-of-undefined-while,"['angular', 'observable', 'karma-jasmine']",4479,True,1,1
Azure YAML Get variable from a job run in a previous stage,"<p>I am creating YAML pipeline in Azure DevOps that consists of two stages. </p>

<p>The first stage (Prerequisites) is responsible for reading the git commit and creates a comma separated variable containing the list of services that has been affected by the commit.</p>

<p>The second stage (Build) is responsible for building and unit testing the project. This Stage consists of many <code>templates</code>, one for each Service. In the template script, the job will check if the relevant Service in in the variable created in the previous stage. If the job finds the Service it will continue to build and test the service. However if it cannot find the service, it will skip that job. </p>

<p><strong>Run.yml:</strong></p>

<pre><code>stages:
- stage: Prerequisites
  jobs:
  - job: SetBuildQueue
    steps:
    - task: powershell@2
      name: SetBuildQueue
      displayName: 'Set.Build.Queue'
      inputs:
        targetType: inline
        script: |
            ## ... PowerShell script to get changes - working as expected
            Write-Host ""Build Queue Auto: $global:buildQueueVariable""
            Write-Host ""##vso[task.setvariable variable=buildQueue;isOutput=true]$global:buildQueueVariable""

- stage: Build
  jobs:
  - job: StageInitialization

  - template: Build.yml
    parameters:
      projectName: Service001
      projectLocation: src/Service001

  - template: Build.yml
    parameters:
      projectName: Service002
      projectLocation: src/Service002
</code></pre>

<p><strong>Build.yml:</strong></p>

<pre><code>parameters:
  projectName: ''
  projectLocation: ''

jobs:
- job:
  displayName: '${{ parameters.projectName }} - Build'
  dependsOn: SetBuildQueue
  continueOnError: true
  condition: and(succeeded(), contains(dependencies.SetBuildQueue.outputs['SetBuildQueue.buildQueue'], '${{ parameters.projectName }}'))
  steps:
  - task: NuGetToolInstaller@1
    displayName: 'Install Nuget'
</code></pre>

<p><strong>Issue:</strong></p>

<p>When the first stages runs it will create a variable called <code>buildQueue</code> which is populated as seen in the console output of the PowerShell script task:</p>

<pre><code>Service001 Changed
Build Queue Auto: Service001;
</code></pre>

<p>However when it gets to stage two and it tries to run the build template, when it checks the conditions it returns the following output:</p>

<pre><code>Started: Today at 12:05 PM
Duration: 16m 7s
Evaluating: and(succeeded(), contains(dependencies['SetBuildQueue']['outputs']['SetBuildQueue.buildQueue'], 'STARS.API.Customer.Assessment'))
Expanded: and(True, contains(Null, 'service001'))
Result: False
</code></pre>

<p>So my question is how do I set the <code>dependsOn</code> and <code>condition</code> to get the information from the previous stage? </p>
",https://stackoverflow.com/questions/58625330/azure-yaml-get-variable-from-a-job-run-in-a-previous-stage,"['azure-devops', 'dependencies', 'yaml', 'azure-pipelines']",2343,True,1,2
Why does karma not find my karma.conf.js file when I run my Jasmine tests from Visual Studio?,"<p>After having used C# unit tests for years, I am writing and running Javascript unit tests for the first time using Visual Studio 2019.  I'm following along with this guide: <a href=""https://jimblizzard.wordpress.com/2018/01/20/unit-testing-your-javascript-code/"" rel=""nofollow noreferrer"">https://jimblizzard.wordpress.com/2018/01/20/unit-testing-your-javascript-code/</a></p>

<p>So far, I have everything working, but when I launch the tests from the ""Test Explorer"" window in Visual Studio, I get errors indicating that the objects created in my Javascript files are undefined.</p>

<p>I get this error in spite of the fact that when I run my tests from the command line with <code>karma start</code>, the tests pass.</p>

<p>I've noticed that even if the karma.conf.js file is syntactically malformed, I get the same error.  I would have expected to get a syntax error, so that suggests that karma is not reading my karma.conf.js file, which is in the root folder of my ASP.net project.</p>

<p>What could I be doing wrong that when karma launches from the command line, the tests pass, but when it launches from the Visual Studio Test Explorer, I get errors and it appears that my karma.conf.js file is ignored?</p>
",https://stackoverflow.com/questions/57046560/why-does-karma-not-find-my-karma-conf-js-file-when-i-run-my-jasmine-tests-from-v,"['jasmine', 'karma-jasmine', 'visual-studio-2019']",228,True,1,1
setting up unit testing arduino code in eclipse,"<p>Before retiring, I successfully introduced unit testing in Eclipse for an embedded arm cross compiled target to my team, based on the book Test-Driven Development for Embedded C by James W. Grenning</p>

<p>Now I'm wanting to do the same for my own Arduino projects, but I've hit a bit of a snag</p>

<p>I have the Eclipse Arduino plugin working on a sample project (the target project) - the functions &amp; classes to be unit tested are in a separate folder in this project (called 'application')</p>

<p>I have the CppUTest unit test libraries installed in a separate testing project
I've included the 'application' folder from the target project in this testing project</p>

<p>Now, This testing project can't immediately resolve the  include file in the target files, and if I manually include this header file into the testing project, it references other include files, and I start to disappear down a rabbit hole trying to satisfy other header file references</p>

<p>I've initially worked around this by removing  from the target functions and classes, and the only changes needed so far has been to change Arduino type defs like 'byte' to standard C 'unsigned char' - these then copile fine in both projects ad the tests run and pass</p>

<p>But I don't particularly like having to change the type defs, and would like to be able to include , and keep the code in the usual Arduino 'style'</p>

<p>So, the question is - is there a better way to do this?</p>

<p>I did think that I should be able to add the CppUTest libraries to an Arduino Eclipse project, as a test project, but there doesn't seem to be the option to add library &amp; include paths to an Arduino project like you can with a c/c++ project, and I don't see an easy way to add all the necessary Arduino header files to a standard C++ project, especially as I believe some of the headers are dependant on the Arduino platform chosen, which of course isn't supported in a standard C++ project</p>

<p>It would be nice to have a generic solution to this so that I could create other test projects with different unit testing frameworks, as my former colleagues have moved onto the Cxx unit test framework, and there are others (like google) i'd like to try</p>

<p>Looking forward to your suggestions</p>
",https://stackoverflow.com/questions/58068968/setting-up-unit-testing-arduino-code-in-eclipse,"['eclipse', 'unit-testing', 'arduino', 'tdd', 'cpputest']",62,False,1,0
nUnit / moq - why does my mock always return false?,"<p>I'm new to unit testing with nUnit and Moq and have run into an issue seting behaviours for a method in a dbprovider.</p>

<p>I'm tryin to test a validation method that invokes an Exists method in ICoDbProvider. When false, the method throws an excpetion, and it is working nice. When true, the method should go ahead until the <code>return true;</code> statement at the end of the method.</p>

<p><strong>This is the method tested:</strong></p>

<pre><code>private bool ValidateReciboCajaModel(ReciboCajaModel model)
{
        if (model == null)
            throw new ArgumentException(""El modelo ha llegado nulo"");

        if (string.IsNullOrWhiteSpace(model.AccionARealizar))
            throw new ArgumentException(""No se ha definido una Acción a realizar"");

        if (!_accionARealizarService.Exists(new AccionARealizarEntity(model)))
            throw new ArgumentException(@""No es una """"acción a realizar"""" válida"");


        if (string.IsNullOrWhiteSpace(model.CentroCostos))
            throw new ArgumentException(""No se ha definido ningún centro de costos"");

        if (!_centroCostosService.Exists(new CentroCostosEntity(model)))
            throw new Exception(""No es un centro de costos válido"");

        if (String.IsNullOrWhiteSpace(model.CuentaIngresoDinero))
            throw new Exception(""No es una cuenta de Ingreso válida"");

        if (!_terceroService.Exists(new TerceroEntity(model)))
            throw new Exception(""No es un tercero registrado"");

        if (String.IsNullOrWhiteSpace(model.Tercero))
            throw new Exception(""No es un tercero válido"");

        if (!_tipoReciboCajaService.Exists(new TipoReciboCajaEntity(model)))
            throw new Exception(""No es un recibo de caja registrado"");

        if (String.IsNullOrWhiteSpace(model.TipoReciboCaja))
            throw new Exception(""No es un recibo de caja válido"");

        if (!(0 &lt; model.ValorPagado &amp;&amp; model.ValorPagado &lt;= 999999999999d))
            throw new Exception(""El valor pagado no es válido"");

        return true;

}
</code></pre>

<p>The test was originally generated by Intellitest, and it generated a scaffolding for private method testing. </p>

<p><strong>The test method looks like this.</strong></p>

<pre><code>    [Test]
    [PexGeneratedBy(typeof(ReciboCajaBizTest))]
    [PexRaisedException(typeof(TargetInvocationException))]
    public void ValidateReciboCajaModel_ValidModel()
    {
        bool b;
        TargetInvocationException receivedException = new TargetInvocationException(null);

        ReciboCajaModel s1 = new ReciboCajaModel();
        var accionARealizarService = new Mock&lt;ICoDbProvider&gt;();
        var centroCostosService = new Mock&lt;ICoDbProvider&gt;();
        var terceroService = new Mock&lt;ICoDbProvider&gt;();
        var tipoReciboCajaService = new Mock&lt;ICoDbProvider&gt;();

        s1.TipoReciboCaja = ""RC0"";
        s1.Numero = 0;
        s1.Tercero = ""tercero existente"";
        s1.AccionARealizar = ""some action"";
        s1.FechaElaboracion = default(DateTime);
        s1.CentroCostos = ""cc1"";
        s1.CuentaIngresoDinero = ""Débito"";
        s1.ValorPagado = 1000000d;

        accionARealizarService.Setup(m =&gt; m.Exists(new AccionARealizarEntity(s1))).Returns(true);
        centroCostosService.Setup(m =&gt; m.Exists(new CentroCostosEntity(s1))).Returns(true);
        terceroService.Setup(m =&gt; m.Exists(new TerceroEntity(s1))).Returns(true);
        tipoReciboCajaService.Setup(m =&gt; m.Exists(new TipoReciboCajaEntity(s1))).Returns(true);

        ReciboCajaBiz s0 = new ReciboCajaBiz(null, accionARealizarService.Object, centroCostosService.Object,terceroService.Object,tipoReciboCajaService.Object);

        b = this.ValidateReciboCajaModel(s0, s1);

        Assert.AreEqual(true, b);
    }
</code></pre>

<p>This is the case everything in the Model is right and the method should return a valid flag.</p>

<p>I have this weird behaviour while debugging. Right after seting Mocks behaviour I called in Watch window the method, and it return false, as shown in the picture</p>

<p><a href=""https://i.stack.imgur.com/4VtCF.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4VtCF.png"" alt=""debug shows the behaviour is not working as set""></a></p>

<p>I also have a method that tests the accionARealizar object does not exists, and it returns false as set. But I doubt it is working correctly.</p>

<p><strong>Update</strong></p>

<p>As requested in comments below, this is ReciboCajaModel</p>

<pre><code>public class ReciboCajaModel
{
    [Required]
    [EnumDataType(enumType: typeof(TipoReciboCaja))]
    public string TipoReciboCaja { get; set; }
    [Required]
    public int Numero { get; set; }
    [Required]
    public string Tercero { get; set; }
    [Required]
    public string AccionARealizar { get; set; }
    [Required]
    public DateTime FechaElaboracion { get; set; }
    [Required]
    public string CentroCostos { get; set; }
    /// &lt;summary&gt;
    /// este campo no sólo enlaza la cuenta donde se hace el abono o accion a realizar, sino también la forma de pago
    /// &lt;/summary&gt;
    [Required]
    public string CuentaIngresoDinero { get; set; }
    [Required]
    [Range(0, 999999999999)]
    public double ValorPagado { get; set; }
}
</code></pre>

<p>and ReciboCajaBiz constructors and private members</p>

<pre><code>    private ICoDbProvider _reciboCajaService;
    private ICoDbProvider _accionARealizarService;
    private ICoDbProvider _centroCostosService;
    private ICoDbProvider _terceroService;
    private ICoDbProvider _tipoReciboCajaService;

    public ReciboCajaBiz()
    {
        _reciboCajaService = new ReciboCajaService();
        _accionARealizarService = new AccionARealizarService();
    }

    public ReciboCajaBiz(ICoDbProvider reciboCajaService = null, ICoDbProvider accionARealizarService = null, ICoDbProvider centroCostosService = null, ICoDbProvider terceroService = null, ICoDbProvider tipoReciboCajaService = null)
    {
        _reciboCajaService = reciboCajaService == null ? new ReciboCajaService() : reciboCajaService;
        _accionARealizarService = accionARealizarService == null ? new AccionARealizarService() : accionARealizarService;
        _centroCostosService = centroCostosService == null ? new CentroCostosService() : centroCostosService;
        _terceroService = terceroService == null ? new TerceroService() : terceroService;
        _tipoReciboCajaService = tipoReciboCajaService == null ? new TipoReciboCajaService() : terceroService;
    }
</code></pre>
",https://stackoverflow.com/questions/54875460/nunit-moq-why-does-my-mock-always-return-false,"['c#', '.net', 'unit-testing', 'nunit', 'moq']",1938,True,0,2
How to do Unit testing using Junit4?,"<p>I had created a JWTCreateImpl class given below to generate a jwt token using generatToken() method and respond a jwt string using loginUser() method. loginUser() method takes email and password as a parameter coming from frontend. This email is compare with email exist in database and if email is not present the errorResponse will become ""email not exist"" similarly do for password doesn't match. And lastly if email and password exist for a particular id then extracting the result from database and pass only uuid of user to generate a token and response will be jwt string. I want to perform unit testing for this class using Junit4, how can I write the test case using Junit4 for this?</p>

<p>JWTCreateImpl class Implements JWTCreate Interface which Contains abstract Methods loginUser(UserInfoJWT userInfoJWT) and generateToken(UUID uuid) and one String JWT_TOKEN_KEY which is used in generateToken() method mainly use with HMAC256 Algorithm. UserInfoJWT is a POJO class Which contains email and password of user.</p>

<p>ResponseJWT is a POJO class  which contains UserToken and errorResponse.</p>

<pre><code>import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.knoldus.magad.jwt.api.JWTCreate;
import com.knoldus.magad.jwt.model.ResponseJWT;
import com.knoldus.magad.jwt.model.UserInfoJWT;
import com.knoldus.magad.dao.model.UserInfo;
import com.knoldus.magad.user.api.UserInfoProcessingAPI;

import org.apache.log4j.Logger;


import java.io.UnsupportedEncodingException;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class JWTCreateImpl implements JWTCreate {
private static final Logger LOGGER = Logger.getLogger(JWTCreateImpl.class);
private UserInfo existingUser;
private ResponseJWT response;
private  UserInfoProcessingAPI userInfoProcessingAPI;
private static final String NO_USER_EMAIL = ""Email doesn't exists.."";
private static  final String LOGIN_UNSUCCESSFUL = ""Wrong Password"";


@Override
public CompletableFuture&lt;String&gt;loginUser(final UserInfoJWT userInfoJWT) {
    return userInfoProcessingAPI.getUserInfo(userInfoJWT.getUserEmail()).thenApply(result -&gt; {
        existingUser = result.orElse(null);
        if (existingUser == null) {
            response = ResponseJWT.builder().errorResponse(NO_USER_EMAIL).build();
        } else {
            final String dataBasePassword = existingUser.getUserPassword();
            if (userInfoJWT.getUserPassword().equals(dataBasePassword)) {
                response = ResponseJWT.builder().userToken(generateToken(existingUser.getUuid())).build();
            } else {
                response = ResponseJWT.builder().errorResponse(LOGIN_UNSUCCESSFUL).build();
            }
        }
        return response.toString();
    });
}
@Override
public String generateToken(final UUID uuid) {
    try {
        final Algorithm algorithm = Algorithm.HMAC256(JWT_TOKEN_KEY);
        final Date expirationDate = Date.from(ZonedDateTime.now().plusHours(24).toInstant());
        final Date issuedAt = Date.from(ZonedDateTime.now().toInstant());
        final String id = String.valueOf(uuid);
        final String issuer = ""MagADAuth"";
        return JWT.create()
                .withIssuedAt(issuedAt) // Issue date.
                .withExpiresAt(expirationDate) // Expiration date.
                .withClaim(""userId"", id)
                .withIssuer(issuer) // Issuer of the token.
                .sign(algorithm); // And the signing algorithm.
    } catch (UnsupportedEncodingException | JWTCreationException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
</code></pre>
",https://stackoverflow.com/questions/57335875/how-to-do-unit-testing-using-junit4,"['java', 'jwt', 'junit4']",191,True,0,1
How to find the difference of two dataframes,"<p>I am working on some Unit Testing Spark code which should be able to generate the difference between two dataframes(raw bucket and curated bucket). Both dataframes(buckets) are the same and we want to execute this code to capture the possible changes after we copy files from raw to curated. . I am aware that I can use <code>except</code> function as follow: </p>

<pre><code>val difference =CuratedDataFrame.union(RawDataFrame).except(CuratedDataFrame.intersect(RawDataFrame))

+-----------+-------+-------------+---------+---------------+
|record     |pid    |feetype      |freq     |default        |
+-----------+-------+-------------+---------+---------------+
|          1|     45|          FAC|        Y|              T| 
|          1|     45|          FAC|        Y|            TTY| 
|          1|     47|          FAC|        R|              M| 
|          1|     99|          FAC|        R|              M|
+-----------+-------+-------------+---------+---------------+
</code></pre>

<p>The except function is returning the entire row but my desired output is as follow :</p>

<pre><code>+-----------+-------+-------------+---------+---------------+
|record     |pid    |feetype      |freq     |default        |
+-----------+-------+-------------+---------+---------------+
|       null|[47,99]|         null|     null|         null  |
|       null|   null|         null|     null|       [T, TTY]|
+----------+-----------+-------+-------------+---------+-----
</code></pre>

<p>It means if there is a change in column then it should appear if there is no change then it should be hidden or Null.</p>

<p>For doing this I am using the following approach :</p>

<pre><code> val mapDiffs=(name: String) =&gt; when($""l.$name"" === $""r.$name"", null )
      .otherwise(array($""l.$name"", $""r.$name"")).as(name)
    val result = difference.as(""l"")
        .join(RawDataFrame.as(""r""), $""l.primaryKey"" === $""r.primaryKey"",""inner"")
        .select($""l.primaryKey"" :: cols.map(mapDiffs): _*)
</code></pre>

<p>The above approach requires primary key to be able to join both dataframes and compare them row by row. None of the dataframes have primary key so I had to combine some of the columns to specify a primary key :</p>

<pre><code>+-----------+-------+-------------+---------+---------------+----------+
|record     |pid    |feetype      |freq     |default        |primaryKey|
+-----------+-------+-------------+---------+---------------+----------+
|          1|     40|          FAC|        A|              N|    FAC40A|
|          1|     45|          FAC|        Y|              T|    FAC45Y|
|          1|     47|          FAC|        R|              M|    FAC47R|
+-----------+-------+-------------+---------+---------------+----------+
</code></pre>

<p>The problem is that if any changes happen in the target bucket, the primary key will be consequently changed so comparing both dataframes would be impossible. </p>
",https://stackoverflow.com/questions/54515723/how-to-find-the-difference-of-two-dataframes,"['scala', 'apache-spark']",110,False,0,0
Both DocTest and Catch 2 not running unit test,"<p>I'm starting a new win32 C++ project using Visual Studio 2019 (v. 16.0.4) and Resharper (v. 2019.1.1) and can't get either the Catch2 or Doctest unit testing framework to run a test.  I prefer Doctest and used that first and when that didn't work, I tried Catch2 and had the same result.  Both frameworks find the test, but give the status ""Inconclusive Test not run"".  The Catch2 warning states: ""2019.05.19 08:47:46.447    WARN Element CatchTest Test was left pending after its run completion.
"".  All the code below is for Catch2:</p>

<p><strong>Engine.h</strong></p>

<pre><code>#pragma once

#include ""pch.h"";
#include &lt;SDKDDKVer.h&gt;;

int  wWinMain( dv* ghInst, dv* ghPrevInst, dv* gupCmdLine, dsd gsdCmdShowFlag);

int test();
</code></pre>

<p><strong>Engine.cpp</strong></p>

<pre><code>#include ""pch.h""
//#include ""..\DocTest_2_2_2.h""
#include ""..\Catch_2_7_2.h""
#include ""Engine.h""


int wWinMain( dv* ghInst, dv* ghPrevInst, dv* gupCmdLine, dsd gsdCmdShowFlag) {
  return 0;
  };


int test() { return 3; }

TEST_CASE(""CatchTest Test"") {

  REQUIRE(test() == 3);
}
</code></pre>

<p><strong>DocTest.cpp</strong> (Using Catch2 code, DocTest code is commented out)</p>

<pre><code>#include ""pch.h""

//#define DOCTEST_CONFIG_IMPLEMENT
//#include ""..\DocTest_2_2_2.h""

#define CATCH_CONFIG_MAIN
#include ""..\Catch_2_7_2.h""
</code></pre>

<p>I found that there was an issue like this on conversations about prior versions of Visual Studio and Resharper but I'm using the latest versions and still have a problem.</p>

<p>In Resharper options, I have ""Enable Catch support"" selected under ""C++ Tests"" and also have ""Enable MSTest support"" selected under ""MsTest"".  I have the x64 architecture selected for both the unit tests and on all project configuration settings.</p>

<p>Any help with this is appreciated.  Thank you.</p>
",https://stackoverflow.com/questions/56208583/both-doctest-and-catch-2-not-running-unit-test,"['c++', 'unit-testing', 'resharper', 'doctest', 'catch2']",816,True,0,1
Mono 5.20.1.19 crash and runtime and class libraries out of sync warnings,"<p>Built Mono 5.20.1.19 master on Linux from GitHub. ""make check"" showed every unit testing passed. Then I used this mono to build my project. But when I run unit testings of my project, mono crashed in couple cases. These cases are related to cominterop and BSTR marshaling. I noticed a warning states:
Your mono runtime and class libraries are out of sync.
The out of sync library is: MyInterop.dll</p>

<p>When you update one from git you need to update, compile and install
the other too. Do not report this as a bug unless you're sure you have updated correctly: you probably have a broken mono install.
If you see other errors or faults after this message they are probably related and you need to fix your mono install first.</p>

<p>Apparently every library of my project was build with mono 5.20.1.19. If you use mono 4.8, there is no such out of sync issue and the unit testings are good. Why there is such warning and is it to the crash of mono?</p>
",https://stackoverflow.com/questions/57275275/mono-5-20-1-19-crash-and-runtime-and-class-libraries-out-of-sync-warnings,"['linux', 'mono', 'com-interop']",281,False,0,0
"CakePHP IntegrationTestTrait, Testing File Upload","<p>I have been stuck on this for days! I am trying to test an a Controller function that reads a file uploaded in $_FILES and sets a variable containing error/success messages. </p>

<p>I know that CakePHP IntegrationTestTrait does not actually dispatch an HTTP request, however, I found a thread of someone claiming they could bypass it: </p>

<p>I have tried implementing the following solution I have found here: 
<a href=""https://discourse.cakephp.org/t/unit-testing-of-file-uploads-solved/5241"" rel=""nofollow noreferrer"">https://discourse.cakephp.org/t/unit-testing-of-file-uploads-solved/5241</a></p>

<p><strong>But the problem still persist.</strong> </p>

<pre><code>Controller/StudentsController.php

public function import() {
        if ($this-&gt;request-&gt;is('post')) {
                .
                .
                . 

                $import = $this-&gt;Students-&gt;import($this-&gt;request-&gt;getData('CsvFile.tmp_name'));

                if (! empty($import['errors'])) {
                   $this-&gt;Flash-&gt;error($error);
                } else {
                    $this-&gt;set('import', $import);
                }
       }
}
</code></pre>

<p>Here is my Test case using IntegrationTestTrait. </p>

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

        // Append a bad file (wrong type) by spoofing PHP's files array
        $_FILES = [
            'CsvFile' =&gt; [
                'name'     =&gt; 'student-import-test-1.csv',
                'type'     =&gt; 'text/csv',
                'tmp_name' =&gt; 'tests/Fixture/csv/',
                'error'    =&gt; 0,
                'size'     =&gt; 258
            ]
        ];

        $data = [
            'CsvFile.name'     =&gt; 'student-import-test-1.csv',
            'CsvFile.type'     =&gt; 'text/csv',
            'CsvFile.tmp_name' =&gt; 'tests/Fixture/csv/',
            'CsvFile.error'    =&gt; 0,
            'CsvFile.size'     =&gt; 258
        ];

        $this-&gt;post('/students/import', $data);

        $this-&gt;assertResponseOk();
        $this-&gt;assertFlashElement('Flash/error');

        $_FILES = [];
    }
</code></pre>

<p>The <code>$this-&gt;assertResponseOk()</code> fails because, <code>Failed asserting that 302 is between 200 and 204.
</code>
However, the <code>$this-&gt;assertFlashElement('Flash/error')</code> is a success. </p>

<p>I am new to Testing on CakePHP. I am stuck on debugging this issue. There are a couple things I believe may be making this </p>

<p>The <code>tmp_name</code> / file may not be accessible. I have tried changing the <code>tmp_name</code> to an incorrect path and I receive a ""PSD cannot read stream"" error. However, when I change the <code>name</code> to an incorrect filename, there seems to be not difference in output.</p>

<p>Does anyone know how I can debug this further? </p>
",https://stackoverflow.com/questions/58242580/cakephp-integrationtesttrait-testing-file-upload,"['cakephp', 'upload', 'integration-testing', 'cakephp-3.x']",495,True,0,1
Stub not getting called inside .then(),"<p>I am working on unit testing an Express application. I am trying to mock up my external dependencies (Express, database, etc) and am close to a break through. 
However, I am having issues with stubs not being called from within a <code>.then()</code> inside my business logic.</p>

<p>A couple of the methods I am attempting to test are the following:</p>

<pre><code>/**
 * Ping
 * A simple endpoint to poke for testing.
 * @arg {*} request - Incoming request
 * @arg {*} response - Outgoing response
 * @arg {*} next - Next route in series
 */
ping: (request, response, next) =&gt; {
    let elapsed = Date.now() - request.start;
    response.status(200).json({
        request_started: new Date(request.start).toISOString(),
        request_duration: `${elapsed} milliseconds`
    });
},
/**
 * Registration
 * Allows for registration of a user name and password.
 * @arg {*} request - Incoming request
 * @arg {*} response - Outgoing response
 * @arg {*} next - Next route in series
 */
register: (request, response, next) =&gt; {
    let username = request.body.username;
    let password = request.body.password;
    this.model.registerUser(username, password).then(ret =&gt; {
        if (ret) {
            response.status(201).send(""Created"");
        } else {
            response.status(400).send(""Error processing registration request. Please try again."");
        }
    }).catch(err =&gt; {
        response.status(400).send(""Error processing registration request. Please try again."");
    });
}
</code></pre>

<p>The model in <code>register</code> returns a <code>Promise</code> that wraps a call to a database and replies based on the outcome. I have a mock of this setup as follows:</p>

<pre><code>mockModel: {
    registerUser: sinon.stub().callsFake(function(user, pass) {
        if (typeof user !== 'undefined') {
            return Promise.resolve(pass === 'pass');
        }
    }),
    getUser: sinon.stub().callsFake(function(user, pass) {
        if (typeof user !== 'undefined' &amp;&amp; pass === 'pass') {
            return Promise.resolve({id: 9999});
        } else {
            return Promise.resolve(false);
        }
    })
}
</code></pre>

<p>I also have the <code>response</code> object mocked so I can pass it in and determine if it is called correctly:</p>

<pre><code>mockRes: () =&gt; {
    return {
        status: sinon.stub().returnsThis(),
        send: sinon.stub(),
        json: sinon.stub()
    };
}
</code></pre>

<p>The problem arises when I get to the tests:</p>

<pre><code>describe('Register() method', function() {
    this.beforeEach(function() {
        req = mockReq(0, {}, {username: 'user', password: 'pass'});
        res = mockRes();
        base.BaseRoutes(router, null, base.methods, mockModel);
    });

    it('Returns a 201 Created message upon success', function() {
        base.methods.register(req, res);
        chai.expect(res.status).to.have.been.calledWith(201);
        chai.expect(res.send).to.have.been.calledWith('Created');
    });
});
</code></pre>

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

<pre><code>1) Base Methods
       Register() method
         Returns a 201 Created message upon success:
     AssertionError: expected stub to have been called with arguments 201
      at Context.&lt;anonymous&gt; (test\spec.js:50:50)
</code></pre>

<p>Stepping through with a debugger shows that the method is getting called, yet I'm getting this failure.</p>

<p>Other tests in the same suite that leverage the same mocked request/response work correctly but they don't use <code>Promise</code> calls (example: ping() method)</p>

<p>I suspect that it has something to so with scoping, but I'm not sure where things are going wrong.</p>
",https://stackoverflow.com/questions/57500991/stub-not-getting-called-inside-then,"['node.js', 'unit-testing', 'mocha.js', 'sinon', 'sinon-chai']",719,True,0,1
"Internal security checks, how to reach 100 % code coverage?","<p>I have a lot of classes similar to the following one:</p>
<pre><code>public class Foo
{
    private readonly Ba _ba;
    
    private Foo(Ba ba)
    {
        if (ba is null) throw new ArgumentNullException(ba);
        
        _ba = ba;
    }
}
</code></pre>
<p>In other classes' internals, I call this constructor of <code>Foo</code>, but as this would be unintended, in each constructor call <code>ba</code> is not <code>null</code>.</p>
<p>I wrote a lot of test methods for the consisting framework, but I am unable to reach the 100 % of code coverage as the exception in the above code snippet is newer thrown.</p>
<p>I see the following alternatives:</p>
<ul>
<li><strong>Remove the null check:</strong> This would work for the current project implementation, but whenever I might add an accidental call <code>Foo(null)</code>, debugging will be more difficult.</li>
<li><strong>Decorate the constructor with <a href=""https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.excludefromcodecoverageattribute?view=netstandard-2.0"" rel=""nofollow noreferrer""><code>[ExcludeFromCodeCoverage]</code></a>:</strong> This would work for the current <code>Foo(Ba)</code> implementation, but whenever I might change the implementation, new code paths in the constructor could develope and accidentally be missed to test.</li>
</ul>
<p>How would you solve the dilemma?</p>
<hr />
<h1>Notes</h1>
<p>The code example is written in C#, but the question might address a general unit testing/exception handling problem.</p>
<p>C# 8 might solve this problem by <a href=""https://learn.microsoft.com/de-de/dotnet/csharp/tutorials/nullable-reference-types"" rel=""nofollow noreferrer"">introducing non-nullable reference types</a>, but I am searching for a good solution until it has been released stable.</p>
",https://stackoverflow.com/questions/55562538/internal-security-checks-how-to-reach-100-code-coverage,"['c#', 'unit-testing', 'testing', 'exception', 'code-coverage']",64,True,0,1
Laravel - PHPUnit multi step testing,"<p>I'm kind of new to the world of unit testing. I want my tests to be as clear, clean and abstracted out as possible. I've got the following class - </p>

<pre><code>class PasswordResetTest extends GraphQLTest
{

private static $user;
private $authEndpoint = '/graphql/auth';

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

    if (!self::$user instanceof User) {
        self::$user = factory(User::class)-&gt;create(
            ['password' =&gt; Hash::make('password')]
        );
    }
}

/**
 * Check our default password was set successfully
 *
 * @test
 */
public function assertDefaultPassword()
{
    // get our user
    $user = User::where('email', self::$user-&gt;email)-&gt;get();

    // check our password is 'password'
    $this-&gt;assertTrue(
        Hash::check('password', self::$user-&gt;fresh()-&gt;password),
        'Unexpected password'
    );
}

/**
 * Perform a password reset via GraphQL
 *
 * @test
 */
public function requestPasswordResetEmail()
{
    // setup our mail faker
    Mail::fake();

    // make sure nothing has been sent
    Mail::assertNothingSent();

    // set our endpoint
    $this-&gt;setGraphQLEndpoint($this-&gt;authEndpoint);
    $mutation = 'mutation forgotPassword ($email: String) {
        forgotPassword (email: $email)
    }';

    // make our request
    $result = $this-&gt;graphQLRequest($mutation, ['email' =&gt; self::$user-&gt;email]);

    // assert our response
    $result-&gt;assertJson(['data' =&gt; ['forgotPassword' =&gt; true]]);

    // check our reset was sent...
    Mail::assertSent(
        PasswordResetMail::class,
        function (PasswordResetMail $mail) use (&amp;$reset) {
            $reset = $mail-&gt;reset;
            return $mail-&gt;hasTo(self::$user-&gt;email);
        }
    );

    return $reset;
}

/**
 * If our email was sent, now perform our reset...
 *
 * @depends requestPasswordResetEmail
 * @test
 */
public function performPasswordReset(PasswordReset $reset)
{

    // set our endpoint and create mutation
    $this-&gt;setGraphQLEndpoint($this-&gt;authEndpoint);
    $mutation = 'mutation resetPassword ($reset: inputResetPassword!) {
        resetPassword (reset: $reset)                     
    }';

    $result = $this-&gt;graphQLRequest($mutation, [
        'reset' =&gt; [
            'token' =&gt; $reset-&gt;token,
            'password' =&gt; 'newPassword',
            'password_confirmation' =&gt; 'newPassword',
        ]
    ]);

    $result-&gt;assertGraphQLNoErrors();
    $result-&gt;assertJson(['data' =&gt; ['resetPassword' =&gt; true]]);
}
</code></pre>

<p>So I want to run my tests in multiple chunks - </p>

<ul>
<li>Check the password was actually set against the user</li>
<li>Request password reset and assert an email was sent</li>
<li>Perform the password reset and assert our password has been updated</li>
</ul>

<p>I could run all of these tests within one method but I'd rather split them up into separate tests for readability and testability but I'm running into a couple of problems - </p>

<ul>
<li><code>setUp()</code> method gets executed for every test, not the whole class of tests so every test I have a new user, not what I want</li>
<li>If I use <code>DatabaseTransactions</code> - which is what I would ideally like to use, that also resets the database every test so subsequent tests would fail</li>
</ul>

<p>Is there any way to achieve what I'm trying to do or do I have to write it as one big test?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/54145359/laravel-phpunit-multi-step-testing,"['laravel', 'laravel-5.7', 'phpunit']",469,False,0,1
How to decrease tests running time with Jest?,"<p>I'm running 60 E2E tests with Jest and Puppeteer on an EC2 Jenkins slave. Tests' times ranging between 7-90 seconds, averaged at 24 seconds - meaning total time when running sequentially ~24-25 min.
When running <code>jest -w 10</code> it runs 10 tests in parallel but every test takes longer and the time is resembles <code>jest --runInBand</code> both finish at about 24-26 min.</p>

<p>I read <a href=""https://stackoverflow.com/questions/43864793/why-does-jest-runinband-speed-up-tests/44506948"">this</a> and related links, and so changed the machine I'm running on to <code>r5ad.12xlarge</code> (48 cores, 384 GB!) because of the assumption of limited resources and still no effect on the total running time. More attempts I made:</p>

<ul>
<li>Tried with and without <code>--ci --detectOpenHandles</code>, still nothing.</li>
<li><code>NODE_OPTIONS=--max_old_space_size=4096</code> didn't change it either.</li>
<li>Ran with default, 2, 3, 9, 15... workers.</li>
<li>Checked heap usage with <code>node --expose-gc ./node_modules/.bin/jest --runInBand --logHeapUsage</code> and saw some leak - heap usage gradually increased from ~100MB to 1100MB</li>
<li>Tried running locally on the machine (without Jenkins restrictions on resources if any...)</li>
</ul>

<p>My question is if I'm missing something (a flag, Jenkins agent policy)? Maybe I should try a different test runner for the purpose of E2E because jest is aimed more at unit testing?</p>
",https://stackoverflow.com/questions/58728531/how-to-decrease-tests-running-time-with-jest,"['jenkins', 'continuous-integration', 'jestjs', 'puppeteer', 'e2e-testing']",664,False,0,1
"Undefined property when unit testing my discord.js bot (the test itself is passed, but it is followed by an error)","<p>I am trying to set up unit testing for my discord.js bot, but when running <code>npm test</code> in the terminal, while the test is being passed, still gives an error.</p>

<p>This is an image of the test being passed followed by the error:
<a href=""https://i.imgur.com/m2EOuxc.png"" rel=""nofollow noreferrer"">https://i.imgur.com/m2EOuxc.png</a></p>

<p>I need to fix this error in testing, while still having the bot being able to function.</p>

<p>I have tried to completely remove the line referenced in the error (and the lines that had something to do with that specific line)</p>

<pre><code>  jsfiles.forEach((f, i) =&gt; {
    let props = require(`./cmds/${f}`)
    bot.commands.set(props.help.name, props)
  })
</code></pre>

<p>Removing this resolved the testing issue, but resulted in the bot not functioning correctly (it did not load the commands; meaning, the bot couldn't be interacted with), which is not the goal here.</p>

<p>I've also checked, that each of the files in the folder <code>cmds</code> ends with</p>

<pre><code>module.exports.help = {
  name: '&lt;name of the command I use for each command&gt;'
} 
</code></pre>

<p>This is the part of my <code>bot.js</code> file that contains the problem. </p>

<pre><code>// Loads the commands for the bot:
fs.readdir('./cmds/', (err, files) =&gt; {
  if (err) console.error(err)

  let jsfiles = files.filter(f =&gt; f.split('.').pop() === 'js')
  if (jsfiles.length &lt;= 0) {
    console.log('No commands to load!')
    return
  }

  if (testingSettings) {
    console.log(`Loading ${jsfiles.length} commands!`)
  }

  // This is the problem referenced above: 
  // ----------------------------------------------------------------------
  jsfiles.forEach((f, i) =&gt; {
    let props = require(`./cmds/${f}`)
    bot.commands.set(props.help.name, props)
  })
  // ----------------------------------------------------------------------

})
</code></pre>

<p>This is all of my code in the <code>bot.test.js</code> file</p>

<pre><code>const { 
  // Functions
  checkingTesting,

  // Variables
  testingSettings,
} = require('./bot')


test('checking to see if testing-mode is on', () =&gt; {
  expect(checkingTesting(testingSettings, 'token')).toBe(process.env['token']);
});
</code></pre>

<p>If it is needed. This is the function, variable and exporting method that is used to connect <code>bot.js</code> to <code>bot.test.js</code>:</p>

<p>Variable (in <code>bot.js</code> file)</p>

<pre><code>const testingSettings = false
</code></pre>

<p>Function (in <code>bot.js</code> file)</p>

<pre><code>function checkingTesting (testingSettings, name) {
  if (testingSettings) {
    return testSettings[name]
  } else if (!testingSettings) {
    return process.env[name]
  }  
}
</code></pre>

<p>Exporting (in <code>bot.js</code> file)</p>

<pre><code>module.exports = {
  // Exporting functions
  checkingTesting: checkingTesting,


  // Exporting variables
  testingSettings: testingSettings,
}

</code></pre>
",https://stackoverflow.com/questions/56578580/undefined-property-when-unit-testing-my-discord-js-bot-the-test-itself-is-passe,"['node.js', 'unit-testing', 'jestjs', 'bots', 'discord.js']",831,True,0,2
What are some of the rules of thumb to split a test into multiple tests?,"<p>Okay, so I have this piece of code:</p>

<pre><code>public TbMtUserDTO RecoverUser(long userId, UpdateTbMtUserDTO updatedData)
{
    TbMtUser user = _usersRepository.FindUserById(userId);
    if (user == null || 
       (updatedData.IdRecSet == ""Password"" &amp;&amp; String.IsNullOrEmpty(updatedData.DsUpdatedPassword)))
    {
        return null;
    }

    switch (updatedData.IdRecSet)
    {
        case ""Username"":
            return _mapper.Map&lt;TbMtUserDTO&gt;(user);
        case ""Password"":
            user.DsPassword = PasswordHasher.Hash(updatedData.DsUpdatedPassword);
            _usersRepository.SaveChanges();
            return _mapper.Map&lt;TbMtUserDTO&gt;(user);
    }
    throw new InvalidOperationException(
        String.Format(RECOVER_USER_ERROR, updatedData.IdRecSet));
}
</code></pre>

<p>And while I was writing the test cases for that chunk of code, when I had to write the test for one of the ""Password"" case, this is what I did:</p>

<pre><code>    [Fact]
    public void UpdatesPasswordSuccessfully()
    {
        string oldPassword = _user.DsPassword;
        UpdateTbMtUserDTO updateTbMtUserDto = new UpdateTbMtUserDTO()
        {
            IdRecSet = ""Password"",
            DsUpdatedPassword = ""new_password""
        };
        _usersRepositoryMock
            .Setup(x =&gt; x.FindUserById(It.IsAny&lt;long&gt;()))
            .Returns(_user);
        _mapperMock
            .Setup(x =&gt; x.Map&lt;TbMtUserDTO&gt;(It.IsAny&lt;TbMtUser&gt;()))
            .Returns(new TbMtUserDTO());
        TbMtUserDTO userDto = _usersService.RecoverUser(_user.CdUser, updateTbMtUserDto);
        _usersRepositoryMock.Verify(x =&gt; x.SaveChanges(), Times.Once);
        Assert.NotNull(userDto);
        Assert.True(oldPassword != _user.DsPassword);
    }
</code></pre>

<p>As you can see, there are three asserts at the bottom of that test. I first check if <code>SaveChanges</code> was called, and then I verify that the method actually returned something, hence the <code>NotNull</code> assertion and that it actually modifies the password (the <code>True</code> assertion).</p>

<p>But I kind of feel that's not the right way to do it. But in my head those tests are related, but I'm unsure if I should split them into three different tests. The thing is that I must arrange the same pieces together for the three cases, which to be honest, I don't think it's a good idea either.</p>

<p>What do you guys think? I've been implementing unit-testing for a couple of months now so what are some of your rules of thumb in scenarios like these? </p>
",https://stackoverflow.com/questions/54390279/what-are-some-of-the-rules-of-thumb-to-split-a-test-into-multiple-tests,"['unit-testing', 'testing', 'automated-tests']",39,True,0,2
How do I integrate a local Qt project with Google Test?,"<p>I'm trying to integrate Google Test into my Qt project. I have basic <code>(EXPECT_EQ(1, 1))</code> tests running with Google Test, but am confused how I can integrate my Qt project (which uses <code>qmake</code>) into the test's CMake build.</p>

<p>Google Test is currently added using the recommended <code>CMakeLists.txt</code> from their <a href=""https://github.com/google/googletest/blob/master/googletest/README.md"" rel=""nofollow noreferrer"">README</a>. I would like to add my local src and build to the test build. My src is located (relative to the test folder) <code>../src/</code> and I've built the src into (relative to the test folder) <code>build/project-build/</code> but I believe it won't integrate because the project has <code>.pro</code>'s. The error when I try to integrate it as a subdirectory:</p>

<pre><code>CMake Error at CMakeLists.txt:31 (add_subdirectory):
  The source directory

    /home/project/src

  does not contain a CMakeLists.txt file.
</code></pre>

<p>This is how I am adding it as a subdirectory and project to my <code>CMakeLists.txt</code>:</p>

<pre><code>add_subdirectory(${CMAKE_CURRENT_BINARY_DIR}/../../src
                 ${CMAKE_CURRENT_BINARY_DIR}/project-build
                 EXCLUDE_FROM_ALL)
</code></pre>

<p>In a separate <code>CMakeLists.txt.in</code> (similar to how google test does it):</p>

<pre><code>include(ExternalProject)
ExternalProject_Add(project
  GIT_REPOSITORY    ""${CMAKE_CURRENT_BINARY_DIR}/../..""
  GIT_TAG           master
  SOURCE_DIR        ""${CMAKE_CURRENT_BINARY_DIR}/../../src""
  BINARY_DIR        ""${CMAKE_CURRENT_BINARY_DIR}/project-build""
  CONFIGURE_COMMAND """"
  BUILD_COMMAND     """"
  INSTALL_COMMAND   """"
  TEST_COMMAND      """"
)
</code></pre>

<p>Also, please let me know if this is a difficult way to test a project. I was hoping to use google test, but if this doesn't work will probably use Qt Test. I am fairly new to C++ and new to C++ unit testing (am familiar with Java and JUnit). Would appreciate any help, thank you!</p>
",https://stackoverflow.com/questions/58412369/how-do-i-integrate-a-local-qt-project-with-google-test,"['qt', 'cmake', 'googletest', 'qmake']",1566,True,0,1
Alternatives to the Pipes and Filters pattern,"<p>Modifying and tying to test the 7th filter out of a chain of 11 filters proves to be painful to test. I have to do an integration test from Filter#1 to Filter #11 to make sure Filter#7 works properly.</p>

<p>Each filter passes along the same object reference and they work on it.
So for me, I have no idea what kind of state this object would be in when I receive it in the 7th filter that I'm modifying. </p>

<p>There isn't much documentation. So I don't really know what state I'm getting.</p>

<p>Are there any other ways to replace the Pipes and Filters pattern in general?
I'm looking for a good way suitable for unit testing.</p>

<p><a href=""https://learn.microsoft.com/en-us/azure/architecture/patterns/pipes-and-filters"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/azure/architecture/patterns/pipes-and-filters</a></p>

<p>The way this programme that I'm working on is arranged seems like each filter relies on the output of the previous filter. And the filters are added in a specific order. The filters cannot be rearranged in a different order.</p>
",https://stackoverflow.com/questions/54351119/alternatives-to-the-pipes-and-filters-pattern,"['design-patterns', 'pipes-filters']",374,False,0,1
How to limit a Spring @Configuration class to instantiating only alternate services?,"<p>I have a project which is expanding quickly and now has over a hundred components. For unit testing, I have a <code>@Configuration</code> class to substitute stubbed classes, such as a database service with limited functionality:</p>

<pre><code>@Configuration
public class SpringDevTestConfiguration {

    @Bean
    @Profile(""unittest"")
    public DatabaseService databaseService() {
        // this one is needed for the test
        return new TestDatabaseServiceImpl();
    }

    @Bean
    @Profile(""unittest"")
    public RobotControlService robotControlService() {
        // Why should I do this on every service?
        return new RobotControlServiceImpl();
    }

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

<p>The vast majority of components don't need test alternatives, so we want the default one that exists and is picked up at runtime. But whenever a new component is added to the system, we have to add it to all of the <code>@Configuration</code> classes, or we get the ""<code>NoSuchBeanDefinitionException</code>: No qualifying bean of type..."" exception. That's a lot of boilerplate code to return Impl classes, and prevents us from making implementation classes package-protected (because the configuration class needs to be able to instantiate them).</p>

<p>I have tried adding <code>@ComponentScan</code> to the class, but that results in <code>BeanDefinitionOverrideException</code>. If I allow bean overrides with:</p>

<pre><code>spring.main.allow-bean-definition-overriding=true
</code></pre>

<p>... then I get <code>NoUniqueBeanDefinitionException</code> because of the multiple database service implementations.</p>

<p>I'm sure I must be missing something. How can I have short, simple <code>@Configuration</code> class that only instantiates the test implementations I need for the test, then allows the other services to be discovered automatically without explicitly creating them?</p>
",https://stackoverflow.com/questions/55501988/how-to-limit-a-spring-configuration-class-to-instantiating-only-alternate-servi,"['java', 'spring']",127,False,0,0
Unit tests for R functions that are not exported,"<p>I am quite new to unit testing, and I would like to implement some simple unit tests for the functions of an R package. The problem is that most functions of this R package are currently <em>not</em> exported, so that most of unit tests will concern R functions that are not mentioned in the <code>NAMESPACE</code> file.
This concerns the following R package : <a href=""https://gitlab.com/f.santos/anthropmmd/tree/devel"" rel=""nofollow noreferrer"">https://gitlab.com/f.santos/anthropmmd/tree/devel</a></p>

<p>I am using <code>testthat</code>, and when I try to test an R function that is not exported (for example, the most simple function in the package, <code>max3</code>), I get the following error message:</p>

<pre><code>&gt; setwd('............./AnthropMMD/')
&gt; library(devtools)
&gt; devtools::load_all()
Loading AnthropMMD
Registered S3 methods overwritten by 'ggplot2':
  method         from 
  [.quosures     rlang
  c.quosures     rlang
  print.quosures rlang
Registered S3 methods overwritten by 'car':
  method                          from
  influence.merMod                lme4
  cooks.distance.influence.merMod lme4
  dfbeta.influence.merMod         lme4
  dfbetas.influence.merMod        lme4

Attaching package: ‘testthat’

The following objects are masked from ‘package:devtools’:

    setup, test_file


&gt; test()
Loading AnthropMMD
Testing AnthropMMD
✔ |  OK F W S | Context
✖ |   0 1     | max3
────────────────────────────────────────────────────────────────────────────────
test-max3.R:5: error: max3 gives correct answer
could not find function max3
</code></pre>

<p>I found <a href=""https://github.com/r-lib/covr/issues/301"" rel=""nofollow noreferrer"">on this thread</a> that using <code>devtools::load_all()</code> before running the tests should fix the problem, but it did not work for me, and I guess I should have missed something.</p>

<p>What is the correct and complete set up one should follow to be able to test non-exported functions in an R package?</p>

<p>Thanks!</p>

<p>(NB: as I am not an Rstudio user, please do not make me any ""Rstudio-specific"" answer ;))</p>
",https://stackoverflow.com/questions/56473977/unit-tests-for-r-functions-that-are-not-exported,"['r', 'unit-testing', 'testthat']",412,False,0,0
OSDev: Why my memory allocation function suddenly stops working in the AHCI initialization function?,"<p>After my kernel calls the AHCIInit() function inside of the ArchInit() function, I get a page fault in one of the MemAllocate() calls, and this only happens in real machines, as I tried replicating it on VirtualBox, VMWare and QEMU.</p>

<p>I tried debugging the code, unit testing the memory allocator and removing everything from the kernel, with the exception from the memory manager and the AHCI driver itself, the only thing that I discovered is that something is corrupting the allocation blocks, making the MemAllocate() page fault.</p>

<p>The whole kernel source is at <a href=""https://github.com/CHOSTeam/CHicago-Kernel"" rel=""nofollow noreferrer"">https://github.com/CHOSTeam/CHicago-Kernel</a>, but the main files where the problem probably occours are:<br>
<a href=""https://github.com/CHOSTeam/CHicago-Kernel/blob/master/mm/alloc.c"" rel=""nofollow noreferrer"">https://github.com/CHOSTeam/CHicago-Kernel/blob/master/mm/alloc.c</a><br>
<a href=""https://github.com/CHOSTeam/CHicago-Kernel/blob/master/arch/x86/io/ahci.c"" rel=""nofollow noreferrer"">https://github.com/CHOSTeam/CHicago-Kernel/blob/master/arch/x86/io/ahci.c</a></p>

<p>I expected the AHCIInit() to detect and initialize all the AHCI devices and the boot to continues until it reaches the session manager or the kernel shell, but in real computers it page faults before even initializing the scheduler (so no, the problem isn't my scheduler).</p>
",https://stackoverflow.com/questions/55671191/osdev-why-my-memory-allocation-function-suddenly-stops-working-in-the-ahci-init,"['c', 'osdev', 'kernel-mode']",338,True,0,1
My Jacoco report is showing very little code coverage,"<p>I am trying to get an idea of how much code coverage I have with some unit tests in Scala and with the source code in Java(tests and code are in different packages). When I run the Jacoco report, it is showing only 4 percent code coverage.</p>

<p>When I go take a look at the report, it shows 0 percent for a lot of files that I have created tests for. What I suspect is that the unit tests are not being included in the report, maybe since all of the test class files are in the target/test-classes directory.
I have tried including the <code>includeTests</code> tag but that didn't have any effect.</p>

<p>Here is how the plugin looks like in the pom:</p>

<pre><code>&lt;plugin&gt;
                    &lt;groupId&gt;org.jacoco&lt;/groupId&gt;
                    &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;
                    &lt;version&gt;${jacoco-maven-plugin.version}&lt;/version&gt;
                    &lt;configuration&gt;
                        &lt;includeTests&gt;true&lt;/includeTests&gt;
                        &lt;!--&lt;includes&gt;
                            &lt;include&gt;**/test-classes/**&lt;/include&gt;
                        &lt;/includes&gt;--&gt;
                        &lt;excludes&gt;
                            &lt;exclude&gt;**/dto/**&lt;/exclude&gt;
                            &lt;exclude&gt;**/exceptions/**&lt;/exclude&gt;
                        &lt;/excludes&gt;
                    &lt;/configuration&gt;
                    &lt;executions&gt;
                        &lt;execution&gt;
                            &lt;goals&gt;
                                &lt;goal&gt;prepare-agent&lt;/goal&gt;
                            &lt;/goals&gt;
                        &lt;/execution&gt;
                        &lt;execution&gt;
                            &lt;id&gt;report&lt;/id&gt;
                            &lt;phase&gt;prepare-package&lt;/phase&gt;
                            &lt;goals&gt;
                                &lt;goal&gt;report&lt;/goal&gt;
                            &lt;/goals&gt;
                        &lt;/execution&gt;
                    &lt;/executions&gt;
                &lt;/plugin&gt;
</code></pre>

<p>Right now I have commentted out the <code>include</code> tag becasue if I include it, the test compiles with 0 classes. How else can I can include the target/test-classes directory?</p>

<p>Sorry if this is a simple fix, I'm very new with unit testing and Jacoco. Thanks!</p>
",https://stackoverflow.com/questions/57463971/my-jacoco-report-is-showing-very-little-code-coverage,"['java', 'scala', 'jacoco']",501,False,0,1
Use field of union in intialiser of another variable,"<p>I am building records for unit testing a software module. Record data is serialised before sending it to the UUT.</p>

<p>The records contain bitfields, so I would like to build serialised records using these same bitfields at compile-time (to prevent having to account for little- and big-endian issues and where the bits in bitfield go) and use a union to access the (serialised) data. I have to calculate a checksum over the record, so I need the bitfields as bytes to do so.</p>

<p>My attempt so far is:</p>

<pre><code>/* defines for 64 bit valid record */
#define REC3_ID        EEID_ARRAY_FIRST
#define REC3_SIZE      1
#define REC3_INDEX     248
#define REC3_SI0       MAKE_SIZE_INDEX0(REC3_SIZE,REC3_INDEX)
#define REC3_SI1       MAKE_SIZE_INDEX1(REC3_SIZE,REC3_INDEX)
#define REC3_VALUE0    0xf2
#define REC3_VALUE1    0x4f
#define REC3_VALUE2    0xb8
#define REC3_VALUE3    0xa0
#define REC3_DATA      \
    MAKE_CHKSUM7(REC3_ID,REC3_SI0,REC3_SI1,REC3_VALUE0,REC3_VALUE1,REC3_VALUE2,REC3_VALUE3),\
    REC3_ID,REC3_SI0,REC3_SI1,REC3_VALUE0,REC3_VALUE1,REC3_VALUE2,REC3_VALUE3

#define CHKSUM_SEED (0x2a)
#define MAKE_CHKSUM7(v0,v1,v2,v3,v4,v5,v6) (0x100-(((v0)+(v1)+(v2)+(v3)+(v4)+(v5)+(v6)+CHKSUM_SEED)%0x100))

typedef union
{
    uint8_t si[2];
    struct
    {
        uint16_t s: 6;
        uint16_t i: 10;
    } b;
} si_t;

MAKE_SIZE_INDEX0(size,index) ((si_t){.b.s=size,.b.i=index}).si[0]
MAKE_SIZE_INDEX1(size,index) ((si_t){.b.s=size,.b.i=index}).si[1]

static uint8_t rec3[] = {REC3_DATA};
</code></pre>

<p>The problem lies with the macros <code>MAKE_SIZE_INDEX0</code> and <code>MAKE_SIZE_INDEX1</code>. I can't get them to compile (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.11))</p>

<p>The problem can be simplified to:</p>

<pre><code>uint8_t rec[] = {0x12, (si_t){.b.s=4,.b.i=8}.si[0], (si_t){.b.s=4,.b.i=8}.si[1], 0x34};
</code></pre>

<p>But that results in error:</p>

<pre><code>error: initializer element is not constant
</code></pre>

<p>I know I can create my records at run-time, but I wondered whether it is possible to let the preprocessor handle it.</p>

<p>My alternative is something like:</p>

<pre><code>#if defined (TGT_ARCHITECTURE_x86_64)
#define MAKE_SIZE_INDEX0(size,index) (((size)&amp;0x3f)+(((index)&lt;&lt;6)&amp;0xc0))
#define MAKE_SIZE_INDEX1(size,index) ((index&gt;&gt;2)&amp;0xff)
#endif
</code></pre>

<p>But this depends on whether the target is little-endian or big-endian and how it stores bitfields.</p>
",https://stackoverflow.com/questions/57651169/use-field-of-union-in-intialiser-of-another-variable,"['gcc', 'unions', 'ansi-c']",41,True,0,1
swift / CoreData - Create &quot;dummy&quot; NSManagedObjecIDs for data models (to test things without the need of managed objects),"<p>Say I have 2 <code>NSManagedObject</code>s in <code>CoreData</code>.</p>

<pre class=""lang-swift prettyprint-override""><code>class House: NSManagedObject {}
class Location: NSManagedObject {}
</code></pre>

<p>I also have data model <code>structs</code> like this:</p>

<pre class=""lang-swift prettyprint-override""><code>struct HouseModel {
    var objectID: NSManagedObjectID
    ...
}

sruct LocationModel {
    var objectID: NSManagedObjectID
    ...
}
</code></pre>

<p>For each loaded <code>managedObject</code> I basically use its attributes to initialize a new model struct to use for the UI and stuff (mainly collection views)</p>

<p>I have to have the <code>NSManagedObjectID</code> attribute in the <code>structs</code> in order to be able to make changes to the <code>managedObject</code> that struct belongs to. (I learned that I should use the <code>mainViewContext</code> only for reading while using something like <code>persistentContainer.performBackgroundTask</code> for writing. Thus, I need the <code>NSManagedObjectID</code> to load the objects on a background queue)</p>

<p>That's working but there is a problem with this approach:
I can't initialize one of these data models without a <code>managed object</code>. That's annoying when I want to create dummy data for UI testing or unit testing.</p>

<p>I know one solution: Create a <code>Dummy</code> <code>managedObject</code> with exactly one instance and use its objectID for stuff like that. But I don't really like this. Is there a better / more convenient way?</p>

<p>I mean, I would love to entirely remove the <code>objectID</code> attribute to keep <code>CoreData</code> separate from these model <code>structs</code>. But I don't see a way to do this. I need the connection.</p>
",https://stackoverflow.com/questions/56516220/swift-coredata-create-dummy-nsmanagedobjecids-for-data-models-to-test-thi,"['ios', 'swift', 'core-data']",605,True,0,1
Xamarin Android UnitTest and Instrumentation Test (not Forms),"<p>Recently I have implemented UI tests in Xamarin Android <a href=""https://www.nuget.org/packages/Xamarin.UITest/2.2.4"" rel=""nofollow noreferrer"">using Xamarin.UITests in version 2.2.4</a> and <a href=""https://www.nuget.org/packages/NUnit/2.6.4"" rel=""nofollow noreferrer"">NUnit 2.6.4</a> as they indicate in the <a href=""https://learn.microsoft.com/es-es/appcenter/test-cloud/preparing-for-upload/uitest"" rel=""nofollow noreferrer"">official MS page</a> to test everything related to the user interface and their respective validations, say, wait for an image to load, a button action, gestures, etc. .. This I did with all the <code>Fragments</code> and <code>Activities</code> of my Android project and in total I managed to build the structure to successfully execute approximately 300 tests.</p>

<p>The problem is that now <strong>I want to run Unit Tests independent of the UI</strong>, that is, each asynchronous tasks that connect to my web service. I have not succeeded in creating a unit testing project in which I can instantiate a class from my project and execute the methods that are communicated to the WS. I have searched a lot of information for the Android platform in particular, so that by adding the reference of my Android project, I can use the classes freely, but I do not give any results.</p>

<p>For example, after adding the reference of my project: <strong>MyApp.dll</strong>, I can use the classes of it, where I have a <code>Fragment</code> called <strong>ProfileFragment.cs</strong> that contains an asynchronous method called <code>GetProfileAsync()</code>.</p>

<p>I try to do the following in a test:</p>

<pre><code>[Test]
public async void GetProfileTest ()
{
    var profileFragment = new ProfileFragment();
    var result = await profileFragment.GetProfileAsync();

    Assert.IsNotNull (result);
}
</code></pre>

<p>However, using the framework of <code>Xamarin.UITest</code> or <code>NUnit for .Net Framework</code>, I get the following error:</p>

<blockquote>
  <p>Message: System.IO.FileNotFoundException: Could not load file or
  assembly 'Mono.Android, Version = 0.0.0.0, Culture = neutral,
  PublicKeyToken = 84e04ff9cfb79065' or one of its dependencies. The
  system can not find the specified file.</p>
</blockquote>

<p>Here are my two questions:</p>

<p><strong>- Do you have any idea how to test all the asynchronous methods of a class in an Android project in Unit Testing using NUnit Framework?</strong> <em>I need a guide how to do the setup of a NUnit project so that I can instantiate classes from my MonoAndroid project without receiving this exception.</em></p>

<p><strong>- What am I doing wrong?</strong></p>

<p><strong>- Would I need to do these tests on the backend only using NUnit for the .Net Framework?</strong></p>

<p><strong>- Should I separate and create the methods of my web services in the NUnit project directly?</strong> <em>I do not know how maintainable it is, since I have validations for Release mode and Debug mode of my Android project, which, depending on one or the other flame or another, connects to a different host, part of which is a large amount of HTTP GET and POST methods.</em></p>
",https://stackoverflow.com/questions/54190035/xamarin-android-unittest-and-instrumentation-test-not-forms,"['c#', 'android', 'unit-testing', 'xamarin', 'xamarin.android']",1869,True,0,1
In Jasmine unit tests: Can&#39;t resolve all parameters for TestFormInputComponentBase,"<p>I'm new to unit testing Angular application and I'm trying to test my first component. Actually, I'm trying to test an abstract base class that is used by the actual components, so I've created a simple Component in my spec based on that and I'm using that to test it.
But there is a dependency to handle (<code>Injector</code>) and I'm not stubbing it out correctly because when I try to run the test I get this error:</p>
<p><code>Can't resolve all parameters for TestFormInputComponentBase</code></p>
<p>But I'm not sure what I have missed?
Here is the spec:</p>
<pre class=""lang-js prettyprint-override""><code>import { GenFormInputComponentBase } from './gen-form-input-component-base';
import { Injector, Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';

// We cannot test an abstract class directly so we test a simple derived component
@Component({
    selector: 'test-form-input-component-base'
})
class TestFormInputComponentBase extends GenFormInputComponentBase {}

let injectorStub: Partial&lt;Injector&gt;;

describe('GenFormInputComponentBase', () =&gt; {
    let baseClass: TestFormInputComponentBase;
    let stub: Injector;

    beforeEach(() =&gt; {
        // stub Injector for test purpose
        injectorStub = {
            get(service: any) {
                return null;
            }
        };

        TestBed.configureTestingModule({
            declarations: [TestFormInputComponentBase],
            providers: [
                {
                    provide: Injector,
                    useValue: injectorStub
                }
            ]
        });

        // Inject both the service-to-test and its stub dependency
        stub = TestBed.get(Injector);
        baseClass = TestBed.get(TestFormInputComponentBase);
    });

    it('should validate required `field` input on ngOnInit', () =&gt; {
        expect(baseClass.ngOnInit()).toThrowError(
            `Missing 'field' input in AppFormInputComponentBase`
        );
    });
});
</code></pre>
<p>This is the <code>GenFormInputComponentBase</code> class that I'm trying to test:</p>
<pre class=""lang-js prettyprint-override""><code>import { Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { GenComponentBase } from './gen-component-base';

export abstract class GenFormInputComponentBase extends GenComponentBase
    implements OnInit {
    @Input() form: FormGroup | null = null;
    @Input() field: string | null = null;

    @Input() label: string | null = null;
    @Input() required: boolean | null = null;

    @Input('no-label') isNoLabel: boolean = false;

    ngOnInit(): void {
        this.internalValidateFields();
    }

    /**
     * Validates that the required inputs are passed to the component.
     * Raises clear errors if not, so that we don't get lots of indirect, unclear errors
     * from a mistake in the template.
     */
    protected internalValidateFields(): boolean {
        if (null == this.field) {
            throw Error(`Missing 'field' input in AppFormInputComponentBase`);
        }

        if (null == this.label &amp;&amp; !this.isNoLabel) {
            throw Error(
                `Missing 'label' input in AppFormInputComponentBase for '${
                    this.field
                }'.`
            );
        }

        if (null == this.form) {
            throw Error(
                `Missing 'form' input in AppFormInputComponentBase for '${
                    this.field
                }'.`
            );
        }

        return true;
    }
}
</code></pre>
<p>And <code>GenComponentBase</code> has the dependency that I'm trying to stub out</p>
<pre class=""lang-js prettyprint-override""><code>import { Injector } from '@angular/core';
import { LanguageService } from 'app/shared/services';

declare var $: any;

export abstract class GenComponentBase {
    protected languageService: LanguageService;

    constructor(injector: Injector) {
        this.languageService = injector.get(LanguageService);
    }

    l(key: string, ...args: any[]) {
        return this.languageService.localize(key, args);
    }
}
</code></pre>
<p>Any help would be appreciated. Thanks!</p>
<p><strong>Update:</strong></p>
<p>By adding a constructor to <code>TestFormInputComponentsBase</code> I can stub out the <code>LanguageService</code> and it works fine like that. But if I try to stub out the <code>Injector</code>, it will get ignored and it tries to use the real injector anyway.</p>
<pre class=""lang-js prettyprint-override""><code>@Component({})
class TestFormInputComponent extends GenesysFormInputComponentBase {
    constructor(injector: Injector) {
        super(injector);
    }
}

describe('GenesysFormInputComponentBase (class only)', () =&gt; {
    let component: TestFormInputComponent;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            providers: [
                TestFormInputComponent,
                {
                    provide: Injector,
                    useObject: {}
                }
            ]
        });

        component = TestBed.get(TestFormInputComponent);
    });

    it('should validate required field inputs on ngOnInit', () =&gt; {
        expect(() =&gt; component.ngOnInit()).toThrowError(
            `Missing 'field' input in GenesysFormInputComponentBase.`
        );
    });
});
</code></pre>
<p>I would expect to get some error due to the fact that the mock/stub injector provided is an empty object. But I get an error from the real injector. Can the injector simply not be mocked?</p>
<pre><code>    Error: StaticInjectorError(DynamicTestModule)[LanguageService]: 
    StaticInjectorError(Platform: core)[LanguageService]: 
    NullInjectorError: No provider for LanguageService!
</code></pre>
",https://stackoverflow.com/questions/54236304/in-jasmine-unit-tests-cant-resolve-all-parameters-for-testforminputcomponentba,"['angular', 'unit-testing', 'dependency-injection', 'jasmine', 'mocking']",3391,True,6,3
How do I set up Angular with Jest in October 2019?,"<p>As an Angular developer I want to <strong>get rid of Karma/Jasmine</strong> and <strong>use Jest instead</strong> so that I can test my application fast and without any pain.
Unfortunately, I ran into unexpected problems.</p>

<p>In the last few hours, I went through all those tutorials showing up on top of the SERPs:</p>

<ul>
<li><a href=""https://www.xfive.co/blog/testing-angular-faster-jest/"" rel=""noreferrer"">Testing Angular Faster with Jest - xfive.co</a> (recommended by jestjs.io)</li>
<li><a href=""https://blog.angularindepth.com/integrate-jest-into-an-angular-application-and-library-163b01d977ce"" rel=""noreferrer"">Integrate Jest into an Angular application and library - angularindepth.com</a></li>
<li><a href=""https://itnext.io/how-to-use-jest-in-angular-aka-make-unit-testing-great-again-e4be2d2e92d1"" rel=""noreferrer"">How to use Jest in Angular aka make unit testing great (again) - itnext.io</a></li>
<li><a href=""https://blog.upcoding.fr/use-jest-instead-of-karma-and-jasmin-for-your-angular-project/"" rel=""noreferrer"">Use Jest instead of Karma and Jasmine for your Angular project - upcoding.fr</a></li>
</ul>

<p>Here is what I did in detail:</p>

<ol>
<li>Create a new Angular application using <code>ng new my-application</code>.</li>
<li>Change directory: <code>cd my-application</code>.</li>
<li>Run <code>npm start</code> (<code>ng serve</code>) and <code>npm test</code> (<code>ng test</code>) to see if everything works - it works.</li>
<li>Install Jest using <code>npm install --save-dev jest jest-preset-angular @types/jest</code></li>
<li>Add this to <code>package.json</code>:</li>
</ol>

<pre><code>{
  ...
  ""jest"": {
    ""preset"": ""jest-preset-angular"",
    ""setupFilesAfterEnv"": [""&lt;rootDir&gt;/src/setupJest.ts""]
  }
}
</code></pre>

<ol start=""6"">
<li>Change the npm scripts in <code>package.json</code> to the following:</li>
</ol>

<pre><code>""test"": ""jest"",
""test:watch"": ""jest --watch"",
</code></pre>

<ol start=""7"">
<li>Into the folder <code>src</code> create a file <code>setupJest.ts</code> with the following content:</li>
</ol>

<pre><code>import 'jest-preset-angular';
</code></pre>

<p><strong>The problem:</strong><br>
When I run <code>npm test</code> now, the test suite fails to run with</p>

<pre><code>File not found: &lt;rootDir&gt;/tsconfig.spec.json
</code></pre>

<p>I have no idea what I can do about that because all those tutorials from above do not seem to handle this issue.<br> 
Please help me!</p>

<p>Thank you in advance!</p>
",https://stackoverflow.com/questions/58555483/how-do-i-set-up-angular-with-jest-in-october-2019,"['angular', 'typescript', 'unit-testing', 'jestjs']",5097,True,4,1
Simulate a click (in node) for vanilla JS using mocha and chai?,"<p>I'm using Mocha and Chai for unit testing.</p>

<p>Now I want to simulate a click event on an element. In a regular dom environment you could use <a href=""https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click"" rel=""nofollow noreferrer"">.click() method</a> As shown here: <a href=""https://jsfiddle.net/Spindle/jwyx6L84/"" rel=""nofollow noreferrer"">https://jsfiddle.net/Spindle/jwyx6L84/</a></p>

<p>However, since the tests I'm running in a Node environment, this isn't working obviously. </p>

<p>The following is the test scenario example:</p>

<pre><code>import { describe } from 'mocha';

const expect = require('chai').expect;
const jsdom = require('jsdom');
const { JSDOM } = jsdom;

describe('example...', function() {
  beforeEach(function() {
    const { window } = new JSDOM(`
      &lt;!doctype html&gt;&lt;html&gt;
          &lt;button class=""trigger"" onclick=""this.classList.add('test-class')""&gt;
          &lt;/button&gt;
        &lt;/html&gt;`, { runScripts: ""dangerously"" });
        // setting it to dangerously works...
    global.window = window;
  });
  it(`click event should be fired`, function() {
    const triggerElement = window.document.getElementsByClassName('trigger')[0];

   triggerElement.click();

   expect(triggerElement.classList.contains('test-class')).to.equal(true);

  });
});

</code></pre>

<p>So far my search has shown a few different options:</p>

<ul>
<li><a href=""https://airbnb.io/enzyme/"" rel=""nofollow noreferrer"">enzyme</a> Tried this, it will require a react adapter to work. Seems to be an overkill since I want to test vanillaJS?</li>
<li><a href=""https://github.com/Rich-Harris/simulant"" rel=""nofollow noreferrer"">simulant</a> While implementing I don't get past an error: <code>ReferenceError: window is not defined</code>. Even when I implement something like <a href=""https://github.com/rstacruz/jsdom-global"" rel=""nofollow noreferrer"">jsdom-global</a> (which makes the window object available in Node env) Can this only be used in a browser environment?</li>
<li><a href=""https://www.seleniumhq.org/"" rel=""nofollow noreferrer"">selenium</a> This seems to be quite verbose. </li>
<li><a href=""https://github.com/GoogleChrome/puppeteer"" rel=""nofollow noreferrer"">puppeteer</a> This seems promising for the use-case. However is this compatible with JSDOM?</li>
</ul>

<p><strong>What should I be using to simulate a click event for vanilla JS?</strong></p>

<hr>

<p>update:</p>

<p>Setting JSDOM to dangerously works. However, comes as the name 'dangerously' suggests with a risk. <a href=""https://github.com/jsdom/jsdom#executing-scripts"" rel=""nofollow noreferrer"">(source)</a></p>

<p>Just running your scripts in the node environment (and in the CI for that matter) doesn't seem desired. </p>
",https://stackoverflow.com/questions/55724041/simulate-a-click-in-node-for-vanilla-js-using-mocha-and-chai,"['javascript', 'mocha.js', 'chai', 'jsdom']",2456,False,2,0
Can anybody show me what I&#39;m doing wrong trying to test controller with call to unit of work?,"<p>I can't seem to figure this out, I have a C# MVC web application which uses entity framework, with a generic repository and unit of work.</p>

<p>I'm trying to test a controller method that uses unit of work to get a list of people, and I don't seem to be able to properly mock it!  The error I get is:</p>

<pre><code>System.ArgumentNullException: Value cannot be null.
Parameter name: source
</code></pre>

<p>I'll try and keep this as streamlined as possible, but if you want me to post more of my code I can do so.  So, my code is as the following:</p>

<p><strong>Controller</strong></p>

<pre><code>IQueryable&lt;PERSON&gt; people = unitOfWork.PersonRepository.GetAll();
var persontest = people.ToList();
</code></pre>

<p>There's more to this method, but it fails on the ToList().  The actual code is a lot more complicated, there's a lot more added to the IQueryable before the ToList() is called.</p>

<p><strong>UnitOfWork</strong></p>

<pre><code>public class UnitOfWork : IUnitOfWork, IDisposable
{
    private DBContext context = new PASICSDBContextqlEntities();
    private IRepository&lt;PERSON&gt; personRepository;

    public IRepository&lt;PERSON&gt; PersonRepository
    {
        get
        {
            if (personRepository == null)
            {
                personRepository = new Repository&lt;PERSON&gt;(context);
            }
            return personRepository;
        }
    }

    public void Save()
    {
        context.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
        disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
</code></pre>

<p><strong>Repository</strong></p>

<pre><code>public class Repository &lt;TEntity&gt; : IRepository &lt;TEntity&gt; where TEntity: class
{
    internal PASICSqlEntities context;
    internal DbSet&lt;TEntity&gt; dbSet;

    public Repository(PASICSqlEntities context)
    {
        this.context = context;
        dbSet = context.Set&lt;TEntity&gt;();
    }

    public virtual IEnumerable&lt;TEntity&gt; Get(
        Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null,
        Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null,
        string includeProperties = """")
    {
        IQueryable&lt;TEntity&gt; query = dbSet;

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

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

        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }

    public virtual IQueryable&lt;TEntity&gt; GetAll()
    {
        return dbSet.AsQueryable();
    }

    public virtual TEntity GetByID(object id)
    {
        return dbSet.Find(id);
    }

    public virtual void Insert(TEntity entity)
    {
        dbSet.Add(entity);
    }

    public virtual void Delete(object id)
    {
        TEntity entityToDelete = dbSet.Find(id);
        Delete(entityToDelete);
    }

    public virtual void Delete(TEntity entityToDelete)
    {
        if (context.Entry(entityToDelete).State == EntityState.Detached)
        {
            dbSet.Attach(entityToDelete);
        }
        dbSet.Remove(entityToDelete);
    }

    public virtual void Update(TEntity entityToUpdate)
    {
        dbSet.Attach(entityToUpdate);
        context.Entry(entityToUpdate).State = EntityState.Modified;
    }

    public void ExecuteRawSql(string query, params object[] parameters)
    {
        dbSet.SqlQuery(query, parameters);
    }
}
</code></pre>

<p><strong>TestController</strong></p>

<pre><code>public class HomeControllerTest
{
    private Mock&lt;IUnitOfWork&gt; _unitOfWorkMock;
    private HomeController _objController;
    private Mock&lt;IRepository&lt;PERSON&gt;&gt; _personRepository;

    [TestInitialize]
    public void Initialize()
    {
        _unitOfWorkMock = new Mock&lt;IUnitOfWork&gt;();
        _objController = new HomeController(_unitOfWorkMock.Object);
        _personRepository = new Mock&lt;IRepository&lt;PERSON&gt;&gt;();
        _personRepository.Setup(x =&gt; x.GetAll()).Returns(GetPersonList() as IQueryable&lt;PERSON&gt;).Verifiable();
    }

    [TestMethod]
    public void Index()
    {
        // Arrange
        _unitOfWorkMock.Setup(x =&gt; x.PersonRepository).Returns(_personRepository.Object);
        var viewModel = CreateIndexViewModelNoSearchParams();
        viewModel.SearchViewModel.Casenote = ""CASENOTE1"";

        // Act
        ViewResult result = _objController.Index(viewModel) as ViewResult;

        // Assert
        Assert.IsNotNull(result);
        Assert.AreEqual(1, viewModel.PersonViewModel.Count);
        Assert.AreEqual(2, viewModel.PersonViewModel[0].CasenoteList.Count);
        Assert.AreEqual(""Index"", result.ViewName);
    }

    #region Setup Methods

    private IndexViewModel CreateIndexViewModelNoSearchParams()
    {
        var viewModel = new IndexViewModel
        {
            SearchViewModel = new SearchViewModel
            {
                Hcn = null,
                Forename = null,
                Surname = null,
                Dob = null,
                Casenote = null
            }
        };
        return viewModel;
    }

    private List&lt;PERSON&gt; GetPersonList()
    {
        return new List&lt;PERSON&gt;
        {
            new PERSON
            {
                PAS_INT_NO = 1,
                SURNAME = ""TEST SURNAME 1"",
                FORENAMES = ""TEST FORENAMES 1"",
                DOB = new DateTime(2001,01,30),
                SEX = ""M"",
                GP_CODE = ""TEST1"",
                ADDRESS1 = ""TEST ADDRESS1"",
                ADDRESS2 = ""TEST ADDRESS2"",
                ADDRESS3 = ""TEST ADDRESS3"",
                ADDRESS4 = ""TEST ADDRESS4"",
                POSTCODE = ""TESTPC1"",
                CSA_NO = ""1234567890"",
                DEAD = ""N"",
                DATE_OF_DEATH = null,
                TITLE = ""MR"",
                DHA_CODE = ""ABC"",
                TELEPHONE = ""1234567890"",
                PREV_SURNAME_1 = null,
                PREV_SURNAME_2 = null,
                PREV_SURNAME_3 = null,
                MRSA_STATUS = null,
                MRSA_DATE = null
            },
            new PERSON
            {
                PAS_INT_NO = 2,
                SURNAME = ""TEST SURNAME 2"",
                FORENAMES = ""TEST FORENAMES 2"",
                DOB = new DateTime(2001,01,30),
                SEX = ""M"",
                GP_CODE = ""TEST2"",
                ADDRESS1 = ""TEST ADDRESS1"",
                ADDRESS2 = ""TEST ADDRESS2"",
                ADDRESS3 = ""TEST ADDRESS3"",
                ADDRESS4 = ""TEST ADDRESS4"",
                POSTCODE = ""TESTPC2"",
                CSA_NO = ""1234567890"",
                DEAD = ""N"",
                DATE_OF_DEATH = null,
                TITLE = ""MR"",
                DHA_CODE = ""ABC"",
                TELEPHONE = ""1234567890"",
                PREV_SURNAME_1 = null,
                PREV_SURNAME_2 = null,
                PREV_SURNAME_3 = null,
                MRSA_STATUS = null,
                MRSA_DATE = null
            },
            new PERSON
            {
                PAS_INT_NO = 3,
                SURNAME = ""TEST SURNAME 3"",
                FORENAMES = ""TEST FORENAMES 3"",
                DOB = new DateTime(2001,01,30),
                SEX = ""M"",
                GP_CODE = ""TEST3"",
                ADDRESS1 = ""TEST ADDRESS1"",
                ADDRESS2 = ""TEST ADDRESS2"",
                ADDRESS3 = ""TEST ADDRESS3"",
                ADDRESS4 = ""TEST ADDRESS4"",
                POSTCODE = ""TESTPC3"",
                CSA_NO = ""1234567890"",
                DEAD = ""N"",
                DATE_OF_DEATH = null,
                TITLE = ""MR"",
                DHA_CODE = ""ABC"",
                TELEPHONE = ""1234567890"",
                PREV_SURNAME_1 = null,
                PREV_SURNAME_2 = null,
                PREV_SURNAME_3 = null,
                MRSA_STATUS = null,
                MRSA_DATE = null
            },
            new PERSON
            {
                PAS_INT_NO = 4,
                SURNAME = ""TEST SURNAME 4"",
                FORENAMES = ""TEST FORENAMES 4"",
                DOB = new DateTime(2001,01,30),
                SEX = ""M"",
                GP_CODE = ""TEST4"",
                ADDRESS1 = ""TEST ADDRESS1"",
                ADDRESS2 = ""TEST ADDRESS2"",
                ADDRESS3 = ""TEST ADDRESS3"",
                ADDRESS4 = ""TEST ADDRESS4"",
                POSTCODE = ""TESTPC4"",
                CSA_NO = ""1234567890"",
                DEAD = ""N"",
                DATE_OF_DEATH = null,
                TITLE = ""MR"",
                DHA_CODE = ""ABC"",
                TELEPHONE = ""1234567890"",
                PREV_SURNAME_1 = null,
                PREV_SURNAME_2 = null,
                PREV_SURNAME_3 = null,
                MRSA_STATUS = null,
                MRSA_DATE = null
            }
        };
    }
    #endregion  
}
</code></pre>

<p>Sorry, I didn't keep that streamlined at all!  I have no idea what I'm doing, and I can't find any good sources for learning this stuff.  Because there's so many ways of implementing IoC, unit of work, repositories, services, etc, there's lots of different help out there for unit testing, but I can't apply it to my work.  Help!</p>
",https://stackoverflow.com/questions/57911112/can-anybody-show-me-what-im-doing-wrong-trying-to-test-controller-with-call-to,"['c#', 'unit-testing']",54,True,2,1
SAM AWS - Testing AWS Lambda that depend on layers,"<p>I am using AWS SAM framework to build a coupled services Lambda and api gateway. 
I am facing some difficulties to run a unit and integration tests for my lambdas functions which 're using layers (utilities functions, models, controllers, config ...)</p>

<p>I can stub some functions, but others are necessaries, a specially some librairies that i want to be on layer (such as lodash, ...).</p>

<p>Thank you in advance for your help. </p>

<blockquote>
  <p>Clarification</p>
</blockquote>

<p>I have a project which is structured as following </p>

<ul>
<li>serverless-poi

<ul>
<li>events/ => contains all events for local tests </li>
<li>lambda-create-poi

<ul>
<li>tests/unit/lambda-create-poi-spec</li>
<li>index</li>
<li>package</li>
</ul></li>
<li>lambda-delete-poi</li>
<li>lambda-update-poi</li>
<li>lambda-list-poi</li>
<li>lambda-list-poi</li>
<li>layer-poi

<ul>
<li>nodejs/

<ul>
<li>package</li>
<li>conf</li>
<li>models</li>
<li>controllers</li>
<li>utiles</li>
<li>some-shared-lib (ex: lodash, bluebird, ...)</li>
</ul></li>
</ul></li>
</ul></li>
</ul>

<p>All others lambdas have the same structure as lambda-create-poi. </p>

<p>I am planning to industrialize the deployement via bitbucket-ci. My pipline looks like : </p>

<pre><code>image: amazon/lambda-build-node10.x
pipelines:
branches:
master:
- parallel: 
   - step:
        name: lambda-create-poi
        caches:
          - node
        script:
          - cd lambda-create-poi
          - npm install
          - npm test

    - step:
        name: Same for other lambdas
        caches:
          - node
        script:
          #- cd lambda-xxxx
          #- npm install
          #- npm test

- step:
   name:  Package  
   script:      
        - pipe: atlassian/aws-sam-deploy:0.2.3
          variables:
             AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
             AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
             AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION
             S3_BUCKET: $S3_BUCKET
             STACK_NAME: 'my-stack-name'
             SAM_TEMPLATE: 'template.yaml'
             CAPABILITIES: ['CAPABILITY_IAM', 'CAPABILITY_AUTO_EXPAND']
             COMMAND: 'package-only'
- step:
    name:  Upload to S3  
    script:
        - pipe: atlassian/aws-s3-deploy:0.3.2
          variables:
            AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
            AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
            AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION
            S3_BUCKET: $S3_BUCKET
            # template packaged.yml after pipe atlassian/aws-sam-deploy package-only execution
            LOCAL_PATH: '.bitbucket/pipelines/generated/pipeline/pipes/atlassian/aws-sam-deploy'
            EXTRA_ARGS: '--exclude=* --include=packaged.yml'

- step:
    name: Deploy stack  
    script:
        - pipe: atlassian/aws-sam-deploy:0.2.3
          variables:
           AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
           AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
           AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION
           S3_BUCKET: $S3_BUCKET
           STACK_NAME: 'my-stack-name'
           TEMPLATE: 'https://bucket-access-lambda.s3-eu-west-1.amazonaws.com/packaged.yml'  
           CAPABILITIES: ['CAPABILITY_IAM', 'CAPABILITY_AUTO_EXPAND']
           WAIT: 'true'
           WAIT_INTERVAL: 60
           COMMAND: 'deploy-only'
</code></pre>

<p>My problem is in the parallel step can not find the layer for the unit testing. All the units tests failds (I have to stub all the layer event the utiles I use)</p>

<p>Thanks for your help.</p>
",https://stackoverflow.com/questions/58417008/sam-aws-testing-aws-lambda-that-depend-on-layers,"['amazon-web-services', 'aws-lambda', 'serverless', 'aws-lambda-layers']",604,False,2,0
&#39;ReferenceError: define is not defined&#39; when testing Angular app with jest using ApplicationInsights-js,"<p>I am assigned to write unit tests for our <strong>Angular</strong> application in our team, and I have done the configuration and setup for <strong><em>jest</em></strong> and got the tests working. But as our team have integrated Microsoft's <strong><em>ApplicationInsights-js</em></strong> into our application, my tests started to fail. I can't share the code due to company policy, but I will share what I can.</p>

<p>I have searched in Stack Overflow for this problem regarding <strong><em>ApplicationInsights-js</em></strong>, but there was no similar ones. But, I found this as a issue in the GitHub page of <strong><em>ApplicationInsights-js</em></strong>. The issue is <a href=""https://github.com/microsoft/ApplicationInsights-JS/issues/476"" rel=""nofollow noreferrer"">here</a>. I have tried adapting almost all the solutions there, but with no success. According to <a href=""https://github.com/microsoft/ApplicationInsights-JS/issues/476#issuecomment-468320127"" rel=""nofollow noreferrer"">this comment</a> of a member, according to my understanding, I tried changing the <strong>module</strong> to different ones in <em>tsconfig.json</em>, but it wasn't successful.</p>

<h3>Here is my error stack trace.</h3>

<pre><code>  ● Test suite failed to run

    ReferenceError: define is not defined

      1 | import { Injectable } from '@angular/core';
    &gt; 2 | import { AppInsights } from 'applicationinsights-js';
        | ^
      3 | import { environment } from '../../environments/environment';
      4 |
      5 | @Injectable({

      at Object.&lt;anonymous&gt; (node_modules/applicationinsights-js/bundle/ai.module.js:215:1)
      at Object.&lt;anonymous&gt; (src/app/services/app-insights.service.ts:2:1)
      at Object.&lt;anonymous&gt; (src/app/login/login.component.ts:8:1)
      at Object.&lt;anonymous&gt; (src/app/login/login.component.spec.ts:3:1)
</code></pre>

<hr>

<h3>tsconfig.json file</h3>

<pre><code>{
    ""compileOnSave"": false,
    ""compilerOptions"": {
        ""baseUrl"": ""./"",
        ""outDir"": ""./dist/out-tsc"",
        ""sourceMap"": true,
        ""declaration"": false,
        ""esModuleInterop"": true,
        ""module"": ""es2015"",
        ""moduleResolution"": ""node"",
        ""emitDecoratorMetadata"": true,
        ""experimentalDecorators"": true,
        ""importHelpers"": true,
        ""target"": ""es6"",
        ""types"": [""node"", ""jest""],
        ""typeRoots"": [""node_modules/@types""],
        ""lib"": [""es2018"", ""dom""],
        ""paths"": {
            ""cComponents"": [""dist/cComponents""],
            ""cComponents/*"": [""dist/cComponents/*""]
        }
    }
}

</code></pre>

<hr>

<blockquote>
  <p>This is my <strong><em>ApplicationInsights-js</em></strong> version.<br>
  <strong>""applicationinsights-js"": ""^1.0.20""</strong></p>
</blockquote>

<p><br/>
This has become a show stopper for my unit-testing. Any help is appreciated. If the information is not enough, I will try my best to give more info abiding to the company policies.</p>
",https://stackoverflow.com/questions/56077357/referenceerror-define-is-not-defined-when-testing-angular-app-with-jest-using,"['angular', 'unit-testing', 'jestjs', 'azure-application-insights']",2651,True,2,1
QtTest: prevent executable from being copied to system,"<p>So, there I'm writing some library and desided to have a proper unit-testing for it (like TDD and so on). QtTest framework looked suitable to start with. The library itself is fine, so is the test.</p>

<p>But when I added both the library and the test project to my job project, CI build surprisingly failed. It occured that the test executable (LibraryTest.exe or similar on Linux) was being copied:</p>

<ul>
<li>to %QTDIR%/tests in a separate folder on Windows</li>
<li>to /usr/tests on Linux</li>
</ul>

<p>My test project settings added this behavior to the ""install"" build stage, there they are (important ones):</p>

<pre><code>QT += core testlib

# The problem is below
CONFIG += c++11 qt warn_on depend_includepath #testcase
CONFIG -= app_bundle

LIBS *= -L$$PWD -lmylibrary # not exact, does not matter

TARGET = LibraryTest

SOURCES += \
    tst_my_library_test.cpp

DEFINES *= QT_FORCE_ASSERTS

DESTDIR = $$PWD/bin
</code></pre>

<p>As you can see, after commenting out <code>CONFIG += testcase</code> the executable is not copied somewhere anymore. I've read that this configuration option is used for automated tests, that looks useful, but nothing is written about any special install stage. The test executable exists in the <code>DESTDIR</code> just fine, so it is not some accident error.</p>

<p>My question is: why is it happening? Can I specify some other folder?
Automation is usefull, but even if implemented it would be probably bound to some more convenient directory.</p>

<p>Am I cooking the QtTest wrong? Thanks in advance for your attention.</p>
",https://stackoverflow.com/questions/56995826/qttest-prevent-executable-from-being-copied-to-system,"['qt', 'unit-testing', 'qmake', 'qttest']",79,True,1,1
Stored Procedure testing with a test database or wrap everything in transaction,"<p>Our team has a bunch of micro-apis, I'm currently setting up a C# specflow project to do unit testing on all our stored procedures. we have 3 options</p>

<ol>
<li><p>Create a testing database for each micro-api. At the beginning of each test we clear the tables and populated them with test data, and run the stored procedure against it.</p></li>
<li><p>We won't create a test database, just wrap everything in a transaction. We still clear and populate test data and run stored procedure against it, but at the end of each test we rollback the transaction</p></li>
<li><p>Use an in-memory database, however, from my research I don't think SQL Server supports that. I looked into EF and SQL lite. (please correct me if I'm wrong)</p></li>
</ol>

<p>What are the advantages and disadvantages of each. I'm trying to weigh them and see the best practice and what to watch out for.</p>

<p>I think option(1) is better because with option(2) other people might be using the database while your test cases are running and that could mess it up.</p>

<p>However with option(2) we won't have to create and maintain the testing database</p>
",https://stackoverflow.com/questions/56318101/stored-procedure-testing-with-a-test-database-or-wrap-everything-in-transaction,"['c#', 'sql-server']",1062,False,1,0
Integrating Unity Container into existing WinForms app: injection and child forms questions,"<p>I have an existing 90k+ line Winforms application that I am trying to refactor, add unit testing to, add dependency injection to, and eventually get it over to an MVC architecture. </p>

<p>And so I'm trying to figure out how to use Unity Container with Winforms and get it going with at least injecting some dependencies that represent some Data Access Layer classes (mostly remote REST services). </p>

<p>Some bits of code regarding where I'm at:</p>

<p>Over in my Program.cs:</p>

<pre><code>private static UnityContainer container;

public static void Main()
{
    container = new UnityContainer();
    container.RegisterType&lt;IIncidentDataService, IncidentQuery&gt;();
    container.RegisterType&lt;IRuleService, RulesQuery&gt;();

    Application.Run(container.Resolve&lt;MainForm&gt;());
}
</code></pre>

<p>Over in my MainForm.cs:  </p>

<pre><code>public partial class MainForm: Form
{
    private IIncidentDataServcie incidentDataService;
    private IRuleService ruleService;

    // constructor
    public MainForm(IIncidentDataService passedIncidentDataService, IRuleService passedRuleService)
    {
       this.InitializeComponent();
       incidentDataService = passedIncidentDataService;
       ruleService = passedRuleService;

     }

  &lt;lots more code&gt;
}
</code></pre>

<p>I realize I'm not doing this quite right yet.  Certainly, I don't want to have to pass more and more parameters to the constructor on MainForm, as I have several other services yet to pass.</p>

<p>Now, one of the reason I have several other services to pass is that MainForm has controls on it that are used to summon child forms... and I'll need to pass service objects / dependencies over to those. </p>

<p>So, how SHOULD I be passing a container of multiple dependencies over to this Windows form?</p>

<p>I get the feeling I should be making one single object out of all of these service-classes... and passing that alone instead.</p>
",https://stackoverflow.com/questions/57115301/integrating-unity-container-into-existing-winforms-app-injection-and-child-form,"['c#', 'winforms', 'dependency-injection', 'unity-container']",1385,True,1,1
Segmentation fault while testing with google test,"<p>I am passing a compound structure pointer to a function after doing all the memory initializations in a test fixture. But as soon as the function gets called the sizeof that struct changes.
Have tried setting watchpoints and  everything. don't the what's the issue.
Need help.
This is the code for the test.</p>

<p>sizeof(*ueCb) changes just after calling the function cwRrcSendMibCfgReq.
The function is copying some parameters from ueCb. ueCb has multiple structures inside of it. Accessing ueCb->currContestCellForSel in the function throws a segmentation fault even though I have explicitly allocated memory here. I have checked that the allocation occurs. I check sizeof(*ueCb) in gdb keeping the mentioned fucntion as a breakpoint. The header files are the same. Also ueId remains intact while calling the function. CW_ALLOC is an internal macro which allocates memory. it's working fine I have checked that.</p>

<p>Can't share the whole code because it's part of IP. This code is related to 5G protocol stack.My job is to do unit testing and the entire team isn't able to figure out where the problem is.</p>

<pre><code>TEST(testMib1, test)
{

    CwRrcUeCb* ueCb;
    CW_ALLOC(CW_REG,CW_POOL,&amp;ueCb, sizeof(CwRrcUeCb));
    memset(ueCb, 0, sizeof(CwRrcUeCb));
    ueCb-&gt;currContestCellForSel = (CwRrcCellCb *) 
    malloc(sizeof(CwRrcCellCb));
    ueCb-&gt;currContestCellForSel-&gt;phyCellId = 5;
    ueCb-&gt;ueId = 5;
    S16 ret = ROK;

    ret = cwRrcSendMibCfgReq(ueCb); // sizeof *ueCb changes after this statement
    free(ueCb-&gt;currContestCellForSel);        
    CW_FREE(CW_REG, CW_POOL, ueCb, sizeof (CwRrcUeCb));

    // have changed the order just to get to the main point
    EXPECT_EQ(ROK, ret);
    printf("" Event 9 Done\n\n\n"");
}
</code></pre>

<p>The backtrace is as follows:</p>

<pre><code>(gdb) backtrace
#0  0x000000000053a673 in cwRrcSendMibCfgReq (rrcUeCb=0x7ffff5d45320) at ../src/5gnrueapp/cw_rrc_fsm.c:2745
#1  0x000000000061dd59 in testMib1_test_Test::TestBody (this=0xa73500) at ../unittest/test_Event9Mib1.cc:79
#2  0x00007ffff71847a3 in void testing::internal::HandleExceptionsInMethodIfSupported&lt;testing::Test, void&gt;(testing::Test*, void (testing:
:Test::*)(), char const*) () from /lib64/libgtest.so.0
#3  0x00007ffff717ab27 in testing::Test::Run() () from /lib64/libgtest.so.0
#4  0x00007ffff717abce in testing::TestInfo::Run() () from /lib64/libgtest.so.0
#5  0x00007ffff717acd5 in testing::TestCase::Run() () from /lib64/libgtest.so.0
#6  0x00007ffff717e018 in testing::internal::UnitTestImpl::RunAllTests() () from /lib64/libgtest.so.0
#7  0x00007ffff717e2a7 in testing::UnitTest::Run() () from /lib64/libgtest.so.0
#8  0x000000000061e156 in main (argc=1, argv=0x7fffffffe1d8) at ../unittest/test_main.cc:38
</code></pre>

<p>the function which I'm testing</p>

<pre><code>S16 cwRrcSendMibCfgReq(CwRrcUeCb * rrcUeCb)
{
   CtzMibConfigRequest *mibConfig = NULLP;

   CW_ALLOC(CW_REG, CW_POOL, &amp;mibConfig, sizeof (CtzMibConfigRequest));

   if(NULL == mibConfig)
   {
      RLOG1(L_FATAL,""Memory Allocation Failed while sending Mib config req ueId:%d"",rrcUeCb-&gt;ueId);
      RETVALUE(RFAILED);
   }

   mibConfig-&gt;pres.pres = 1;
   mibConfig-&gt;systemFrameNumber       = rrcUeCb-&gt;cwMibInfo.systemFrameNumber;
   mibConfig-&gt;subCarrierSpacingCommon = rrcUeCb-&gt;cwMibInfo.subCarrierSpacingCommon;
   mibConfig-&gt;ssb_SubcarrierOffset    = rrcUeCb-&gt;cwMibInfo.ssb_SubcarrierOffset;
   mibConfig-&gt;dmrs_TypeAPosition      = rrcUeCb-&gt;cwMibInfo.dmrs_TypeAPosition;
   mibConfig-&gt;pdcch_ConfigSIB1.controlResourceSetZero =
      rrcUeCb-&gt;cwMibInfo.pdcch_ConfigSIB1.controlResourceSetZero;
   mibConfig-&gt;pdcch_ConfigSIB1.searchSpaceZero        = rrcUeCb-&gt;cwMibInfo.pdcch_ConfigSIB1.searchSpaceZero;

   mibConfig-&gt;ueId                    =  rrcUeCb-&gt;ueId;
   mibConfig-&gt;cellId                  =  rrcUeCb-&gt;currContestCellForSel-&gt;phyCellId;
   RLOG0(L_DEBUG,""[CFGREQ] [SRC:RRC    ==&gt;&gt; DST:CL(PHY)]   : CTZ_CPHY_MIB_CFG_REQ"");
   printf(""\n[SRC:RRC    ==&gt;&gt; DST:CL(PHY)]   : CTZ_CPHY_MIB_CFG_REQ\n"");
   CwLiCtzCfgReq(&amp;cwCb.ctzSapCbLst[0]-&gt;pst,CTZ_CPHY_MIB_CFG_REQ, mibConfig);

   RETVALUE(ROK);
}
</code></pre>
",https://stackoverflow.com/questions/59371183/segmentation-fault-while-testing-with-google-test,"['c++', 'c', 'googletest']",1845,True,1,1
Unit tests in Symfony 2.8 running hundreds of times slower than they should,"<p>I'm adding unit tests to an old Symfony 2.8 production codebase that never had them before so I can upgrade Symfony to a maintained version. We will also upgrade PHP since we're currently running PHP 5.5 which is also no longer maintained, but Symfony 2.8 throws far too many errors if it's run under PHP 7.3.</p>

<p>Although I'm able to get the unit tests running under both PHPUnit and Codeception (powered by  PHPUnit), they run incredibly slowly.</p>

<p>For example:</p>

<h3>SimpleTest.php</h3>

<pre><code>&lt;?php
class SimpleTest extends PHPUnit_Framework_TestCase {
  public function testShouldDoNothing() {
    $this-&gt;assertTrue(true);
  }
}
</code></pre>

<h3>phpunit.xml</h3>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;phpunit bootstrap=""vendor/autoload.php"" colors=""true""&gt;
    &lt;php&gt;
        &lt;server name=""KERNEL_DIR"" value=""app/""/&gt;
    &lt;/php&gt;
    &lt;testsuites&gt;
        &lt;testsuite name=""Application Test Suite""&gt;
            &lt;directory&gt;tests/unit&lt;/directory&gt;
        &lt;/testsuite&gt;
    &lt;/testsuites&gt;
&lt;/phpunit&gt;
</code></pre>

<h3>PHPUnit run output</h3>

<pre><code>PHPUnit 4.8.36 by Sebastian Bergmann and contributors.

Runtime:        PHP 5.5.9 with Xdebug 2.5.5

.

Time: 19.52 seconds, Memory: 6.00MB

OK (1 test, 1 assertion)
</code></pre>

<h3>codeception.yml</h3>

<pre><code>paths:
    tests: tests
    output: tests/_output
    data: tests/_data
    support: tests/_support
    envs: tests/_envs
actor_suffix: Tester
extensions:
    enabled:
        - Codeception\Extension\RunFailed
coverage:
    enabled: true
    include:
        - src/*
    low_limit: 50
    high_limit: 100
</code></pre>

<h3>Codeception run output</h3>

<pre><code>Codeception PHP Testing Framework v2.3.9
Powered by PHPUnit 4.8.36 by Sebastian Bergmann and contributors.

Unit Tests (1) --------------------------------------------------
Testing unit
+ SimpleTest: Should do nothing (0.29s)
-----------------------------------------------------------------

Time: 30.96 seconds, Memory: 23.25MB

OK (1 test, 1 assertion)
</code></pre>

<p>This test should consistently run in <code>0.00s</code>, and the total time should be less than <code>5 seconds</code>, not <code>20 seconds</code> or more.</p>

<p>How can I speed up unit testing under Symfony 2.8 in PHP 5.5?</p>

<hr>

<p>I've tracked down the problem to running PHP 5.5, which is currently a requirement. I've created a vanilla Symfony 2.8 installation with PHP 5.5 and with no code the tests are still impractically slow. When I switch to PHP 7.3, the tests are as fast as I've expected them to be in the past, however, our project does not yet run under PHP 7.3 as it causes fatal errors.</p>

<pre><code>D:\server\Apache24\htdocs\symfony-2.8&gt;php55 vendor\codeception\codeception\codecept run unit
Codeception PHP Testing Framework v2.3.9
Powered by PHPUnit 4.8.36 by Sebastian Bergmann and contributors.

Unit Tests (1) --------------------------------------------------
+ SimpleTest: Should do nothing (0.20s)
-----------------------------------------------------------------

Time: 21.84 seconds, Memory: 14.50MB

OK (1 test, 1 assertion)

D:\server\Apache24\htdocs\symfony-2.8&gt;php73 vendor\codeception\codeception\codecept run unit
Codeception PHP Testing Framework v2.3.9
Powered by PHPUnit 4.8.36 by Sebastian Bergmann and contributors.

Unit Tests (1) --------------------------------------------------
+ SimpleTest: Should do nothing (0.00s)
-----------------------------------------------------------------

Time: 264 ms, Memory: 10.00MB

OK (1 test, 1 assertion)
</code></pre>
",https://stackoverflow.com/questions/58740762/unit-tests-in-symfony-2-8-running-hundreds-of-times-slower-than-they-should,"['performance', 'unit-testing', 'phpunit', 'symfony-2.8', 'php-5.5']",356,False,1,0
Unit test for protocol over cin/cout - how to block on streams to wait for content?,"<p>I'm trying to write a unit test for a program which needs to communicate with another process over a protocol through cin/cout pipe. It works well when excuting and testing with keyboard or another program sending and receiving commands and responses.</p>

<p>In the unit test I would obviously need to replace cin/cout with other streams I can send and receive data from. (Through another thread and writing to the input stream of the protocol handler)</p>

<p>Unfortunately I can't find a method to get a blocking read method which waits until a stream gets more content. </p>

<p>The code below works fine when using cin.</p>

<pre><code>void Handler::loop() {
  string cmd, token;
  do {
    cout &lt;&lt; ""HANDLER WAIT FOR COMMAND:"" &lt;&lt; endl;

    // Block here waiting for input or EOF
    // only blocks on cin!!
    if (!getline(*pInputStream, cmd)) cmd = ""quit"";

    //  create the stream object
    istringstream inStream(cmd);

    inStream &gt;&gt; skipws &gt;&gt; token;
    cout &lt;&lt; ""HANDLER RECEIVED: "" &lt;&lt; token &lt;&lt; endl;

    if (token == ""quit"") break;
    // handle commands...
    else if (token == ""noop"") /* noop */;
    else cerr &lt;&lt; ""Unknown command: "" &lt;&lt; token &lt;&lt; endl;
    cout &lt;&lt; ""HANDLER COMMAND PROCESSED: "" &lt;&lt; token &lt;&lt; endl;

  } while (token != ""quit"");
}
</code></pre>

<p>When using </p>

<pre><code>istringstream is;
</code></pre>

<p>instead of cin  then 'getline(*pInputStream, cmd)' does not block any more and returns with -1 immediately. I can't find any other mothed which would accomplish what I need (if have done some research for some time now). </p>

<p>In Java I implemented it with:</p>

<pre><code>final BufferedReader in = 
    new BufferedReader(newnputStreamReader(inputStream));

while (running) {
  try {
    // wait until a line is ready to be read
    final String readLine = in.readLine();
...
</code></pre>

<p>This works fine with System.in or other streams. in.readline() always blocks until content is availabe. Ideal for unit testing.</p>

<p>So speficically how can this be accomplished in C++ or more generally how to unit test protocols over inter process pipes?</p>

<p>Thanks in advance for any ideas.</p>
",https://stackoverflow.com/questions/55387550/unit-test-for-protocol-over-cin-cout-how-to-block-on-streams-to-wait-for-conte,"['c++', 'io', 'istream']",407,False,1,1
"Windows 10, compiling tests from Git Bash will not work &quot;bash: junit-4.12.jar: command not found&quot;","<p>Currently doing my first year of studies, and up until now I've been using BlueJ for unit testing my code, which has worked nicely. But now I need to have abstract test classes and interfaces so I need to be able to run the tests from Git Bash. I have downloaded junit-4.12 and hamcrest-core-1.3 and put them in my working directory where the test classes I want to compile are. But I get these two errors when doing it (copied directly from Bash):</p>

<pre><code>$ javac -cp .;junit-4.12.jar;hamcrest-core-1.3.jar LinkedListTest.java
javac: no source files
Usage: javac &lt;options&gt; &lt;source files&gt;
use -help for a list of possible options
bash: junit-4.12.jar: command not found
bash: hamcrest-core-1.3.jar: command not found
</code></pre>

<p>I have Windows 10 and in my enviorment variables I have only edited my path and inserted where my jdk is, nothing else but that and I have been able to compile my regular classes this way, but my test classes will not work!</p>

<p>I have asked recently for help from my recent LABClass where TA:s help us out, but they have been unable to come with any help.</p>

<p>What am I doing wrong? Any help is appreciated since I need to do my assignments but I am unable to see if my solutions are viable since I can't test them!</p>
",https://stackoverflow.com/questions/54442185/windows-10-compiling-tests-from-git-bash-will-not-work-bash-junit-4-12-jar-c,"['java', 'junit', 'git-bash']",578,True,1,1
New remote Branch/Head is not added after fist pushing though Android Studio,"<p>Recently I have migrated my Android project from Git Hub to Git Lab and Also updated the Android studio from 3.2-3.3. In the current Studio IDE, I am getting a consistent Bug while checking out and commit a new Branch.</p>

<p>I am using a two-layer hierarchy in the Git[Development, and Master]. Each feature is considered as a separate branch derived from Development. After feature completion and unit testing, the feature branch will merge to development with a Pull request.  </p>

<p>For checkout a new Branch I am using the below shortcut in Android Studio.</p>

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

<p>In my previous environment[Git Hub &amp; Old Studio], when I check out a new branch and After pushing the codebase, It will create a new Brach/Head in the remote. But now it's not happening. It's added as a new commit under the Development branch. The commit&amp; Push done through the IDE itself.</p>

<p>I have checked the git status from the terminal under Studio. But it's showing the current branch as Feature. I don't know whether this is an issue in Git Lab. If anyone knows the fix, please update. I can create the remote branch terminal through command.</p>
",https://stackoverflow.com/questions/54499933/new-remote-branch-head-is-not-added-after-fist-pushing-though-android-studio,"['android', 'git', 'android-studio', 'gitlab']",72,False,1,0
How to mock custom JdbcCursorItemReader during individual step unit testing on Spring Batch?,"<p>I am trying to create a Junit test case for testing an individual step of my batch Job which in turn has a custom <code>JdbcCursorItemReader</code> and writes data into Flat file. I am unable to mock the data that can be injected into the processor for writing it into the Flatfile. Please help.</p>

<p>I followed steps in below link to create a test case to launch an individual step:</p>

<p><a href=""https://docs.spring.io/spring-batch/trunk/reference/html/testing.html"" rel=""nofollow noreferrer"">https://docs.spring.io/spring-batch/trunk/reference/html/testing.html</a></p>

<p>Since my reader component is stepscope I am using the context around section 10.4 in above link to put the required domain objects into <code>ExecutionContext</code> but while launching the step it does not recognize the same instead it executes the actual SQL query which I am injecting through config xml.</p>

<p>My config xml has step as below :</p>

<pre><code>&lt;step id=""sample-step"" next=""next-step""&gt;
 &lt;tasklet&gt;
    &lt;chunk reader=""customJDBCReader"" processor=""customProcessor"" 
     writer=""customFlatFileItemWriter"" commit-interval=""XXX"" /&gt;
 &lt;/tasklet&gt;
&lt;/step&gt;
</code></pre>

<p>My customreader implements <code>JdbcCursorItemReader</code> which has a SQL defined for reading information from database.</p>

<p>During my unit testing I am trying to mock the data instead of depending on actual data from database</p>

<pre><code>private StepExecution execution;

@BeforeStep
public StepExecution getStepExection() {
    execution = MetaDataInstanceFactory.createStepExecution();
    return execution;
}

@Test
public void testSampleStep() throws UnexpectedInputException, ParseException, Exception {
    MyDomainObject domainObject= new MyDomainObject ();
    domainObject.setID(""sampleID"");
    domainObject.setName(""sampleName"");
    domainObject.setImage(""sampleImage"");
    execution.getExecutionContext().put(""someKey"", domainObject);
    execution.setReadCount(1);

    JobExecution jobExecution = jobLauncherTestUtils.launchStep(""sample-step"", jobParameters, execution.getExecutionContext());
    AssertFile.assertFileEquals(new FileSystemResource(EXPECTED_FILE), new FileSystemResource(OUTPUT_FILE));
}
</code></pre>

<p>The expected result should be the launchstep needs to get the data from <code>executionContext</code> instead of database to write the same into faltfile.</p>
",https://stackoverflow.com/questions/54713720/how-to-mock-custom-jdbccursoritemreader-during-individual-step-unit-testing-on-s,"['spring-boot', 'spring-batch']",2134,True,1,1
How to get 100% test coverage over a DTO object class&#39;s getters when asserting function returns expected DTO object?,"<p>I'm unit testing an ASP.Net Core API by asserting that my repo layer returns a DTO object. As I'm testing behavior, I don't exactly care what values my DTO object has, so I'm autogenerating them using AutoFixture. I'm also trying to satisfy my company's code smell check, which requires our PRs to have a near 100% test coverage. When I mock my ORM to return my DTO object when called and in turn the function under test returns that object, I end up with my actual being the same object as my expected. When asserting with fluent assertion, it sees the object reference are equal and passes my test. However for test coverage, I will not see a coverage over the DTO's properties' getters. If the object reference where different, fluent assertion calls the getters. How do I force fluent assertion to always check the value of all properties by calling all the getters? </p>

<p>I've tried using <code>ComparingByValue&lt;T&gt;</code> and <code>ComparingByMember&lt;T&gt;</code>. I've also tried <code>IncludingProperties()</code>, <code>IncludingMembers()</code>, <code>IncludingAllDeclaredProperties()</code>, and <code>IncludingAllRuntimeProperties()</code>.</p>

<pre class=""lang-cs prettyprint-override""><code>        [Fact]
        public void GivenObjectReferenceIsTheSame_FluentAssertionDoesntCallTheGetters()
        {
            var someDTO = _fixture.Create&lt;SomeDTO&gt;();
            var otherDTO = someDTO;

            otherDTO.Should().BeEquivalentTo(someDTO);
        }
</code></pre>

<pre class=""lang-cs prettyprint-override""><code>        [Fact]
        public void GivenObjectReferenceIsDifferent_FluentAssertionCallsTheGetters()
        {
            var someDTO = _fixture.Create&lt;SomeDTO&gt;();
            var otherDTO = JsonConvert.DeserializeObject&lt;SomeDTO&gt;(JsonConvert.SerializeObject(someDTO));

            otherDTO.Should().BeEquivalentTo(someDTO);
        }
</code></pre>

<p>I would like a way to always force fluent assertion to call the getters in order to get test coverage over the DTOs without having to explicitly write useless tests over the DTOs</p>
",https://stackoverflow.com/questions/57562741/how-to-get-100-test-coverage-over-a-dto-object-classs-getters-when-asserting-f,"['asp.net-core', 'xunit', 'fluent-assertions', 'test-coverage']",2043,True,1,1
"Mockito testing in MVP kotlin - However, there was exactly 1 interaction with this mock exception","<p>I have developed an application with Kotlin and MVP architecture.I want to do unit testing using Mockito but unable to achieve it.I'm getting ""However, there was exactly 1 interaction with this mock exception"".
In my application i have used 5 different classes.</p>

<ol>
<li>View - Interface</li>
<li>Intractor - Interface</li>
<li>IntractorImpl - Class</li>
<li>Presenter - Interfacce</li>
<li>PresenterImpl - Class</li>
</ol>

<p><strong>View:-</strong> It contain all methods required for to communicate activity/fragment.</p>

<p><strong>Intractor:-</strong> It contain the result interface methods.</p>

<p><strong>IntractorImpl :-</strong> It contain database/server logic, it will implemented from Intractor</p>

<p><strong>Presenter :-</strong> It contain methods to access the IntractorImpl class</p>

<p><strong>PresenterImpl :-</strong> It is implemented from Presenter and Intractor result methods </p>

<p>This architecture which i followed for implementing, now to implement the Mockito i'm getting confusion and as per the articles i found in google if i try to implement i'm getting <strong>""However, there was exactly 1 interaction with this mock exception""</strong></p>

<p>For mockito i have used following imports</p>

<pre><code> //Mockito
testImplementation ""org.mockito:mockito-core:2.24.5""
testImplementation ""org.mockito:mockito-inline:2.24.5""
</code></pre>

<p>Please if anyone knows anything,help me out. First time i'm using Mokito.
If anyone need more information i can post it. Following is my code</p>

<pre><code>class EventTest {
    @Mock
    val homeActivity = HomeActivity()
    lateinit var eventView: HomeView
    lateinit var eventInteractorImpl: HomeInteractorImpl
    lateinit var eventPresenter: HomePresenter
    lateinit var eventInteractor: HomeInteractor.OnEventsReceivedListener
    @Before
    fun setUpEventPresenter() {
        eventView = mock(HomeView::class.java)
        eventInteractorImpl = mock(HomeInteractorImpl::class.java)
        eventPresenter = HomePresenterImpl(eventView, eventInteractorImpl)
        eventInteractor = mock(HomeInteractor.OnEventsReceivedListener::class.java)
    }

    @Test
    fun startEventTest() {
        val testEvents = Event(
            ""1"",
            ""Test"",
            ""Next week we have the vacation planing in Vizag"",
            ""This is for test"",
            ""1"",
            ""01-10-2019"",
            ""26-09-2019"",
            ""8.00"",
            ""10.47"",
            """",
            true
        )
        val events: ArrayList&lt;Event&gt; = ArrayList&lt;Event&gt;()
        events.add(testEvents)
        eventPresenter.getEventsList(homeActivity)
        verify(eventView).showProgress()
        verify(eventView).showEvents(events)
        verify(eventView).hideProgress()
    }

}
</code></pre>

<p>If i put <code>verify(eventView).showProgress()</code> no exception is coming.</p>

<pre><code> override fun getEventsList(context: Context) {
    homeView.showProgress()
    homeInteractor.getEvents(context, this)
}
</code></pre>

<p>In getEvents() method we are calling server/local database, for Server we are using Retrofit.</p>
",https://stackoverflow.com/questions/58114720/mockito-testing-in-mvp-kotlin-however-there-was-exactly-1-interaction-with-th,"['android', 'kotlin', 'mockito']",239,False,1,1
Creating sample list of data for a unit test,"<p>I'm trying to create a unit test for a method that takes an arrayList as an input, and returns a different arrayList as an output.</p>

<p>From what I understood about unit testing, I need to make the data then assert that they're correct, but creating an arrayList with sufficient size for the requirements of the method seems complicated.</p>

<p>method to be tested</p>

<pre><code>public static List&lt;String&gt; processList(List&lt;String&gt; input){
    //process array
    return new ArrayList&lt;String&gt;();//return new list with new/modded data
}
</code></pre>

<p>I can do something like</p>

<pre><code>ArrayList&lt;String&gt; inputList = new ArrayList();
inputList.add(""data1"");
...
inputList.add(""data30"");
</code></pre>

<p>or make some code that generates a fake array</p>

<pre><code>for(int i=0;i&lt;30;i++){
   inputList.add(""data""+i);//actual code will be slightly more complicated
}
</code></pre>

<p>But I would need a few lines for some calculation and variety as the data isn't as simple as I make it appear in this question.</p>

<p>The first solution will take lots of space, the second seems like it will require testing itself, therefore defeating the purpose of a unit test.</p>

<p>I was also thinking of saving the array elements in a text file accessible by the project, and for every input type, I will access the required text file and convert the lines to an array.</p>

<p>Basically, how do I create several arrays of around 10-30 elements each to a unit test a single method that takes a single array input without making a mess?</p>
",https://stackoverflow.com/questions/57706613/creating-sample-list-of-data-for-a-unit-test,"['java', 'unit-testing', 'junit']",6521,True,0,2
React / Unit Test (Jest) click method with preventDefault,"<p>So I got a little issue I am stumped with...</p>

<p>I have a <code>Link</code> component which will either go to a specific route via a <code>to</code> prop, if a certain condition is met. If that condition is not met, that link, when clicked, will do something else (launch a custom modal, in my case).</p>

<p>I have a class method which is bound to an <code>onClick</code> handler on my <code>Link</code> component</p>

<pre class=""lang-js prettyprint-override""><code>// Card.jsx

import Link from 'components/Link';

...

static props = {
  condition: PropTypes.bool
};

constructor(props) {
  this.state = {
    showModal: false
  };
}

...

goToUrlOrLaunchModal() {
  return (
    &lt;Link
      to=""www.google.com""
      onClick={this.handleClick}
    /&gt;
  );
}


... 


handleClick(e) {
  const { condition } = this.props;

  if (!condition) {
    e.preventDefault();

    this.setState({
      showModal: true
    });
  }
}
</code></pre>

<p>My issue is with unit testing. I have a unit test for clicking the link when <code>condition</code> is <code>false</code></p>

<pre class=""lang-js prettyprint-override""><code>// Card.test.js

...

import renderer from 'react-test-renderer';

...

const event = {
  preventDefault: jest.fn()
};

const component = renderer.create(&lt;Card&gt;).getInstance();

instance.handleClick(event);
expect(event.preventDefault).toHaveBeenCalled();
expect(instance.state.showModal).toBe(true);

</code></pre>

<p>Where I am getting lost is testing the other side - when <code>condition</code> is <code>true</code>, I do not need to call <code>preventDefault</code> or perform any logic after that. I do not need anything in <code>handleClick</code> to fire. The only logic in <code>handleClick</code> is for when <code>condition</code> is false.</p>

<p>The logic to go to the route when clicking the <code>Link</code> component is fine, it's just the unit test for when <code>condition</code> is <code>true</code>. </p>

<p>I need to test that <code>preventDefault</code> has not been called, and that <code>instance.state.showModal</code> is to be <code>true</code>, but I am stumped. Here is what I keep thinking it has to be, but cannot get past it...</p>

<pre class=""lang-js prettyprint-override""><code>const event = {
  preventDefault: jest.fn()
};

expect(instance.handleManageClick).not.toHaveBeenCalled();
expect(event.preventDefault).not.toHaveBeenCalled();
expect(instance.state.showModal).toBe(false);
</code></pre>

<p>If anyone has some guidance, would be very much appreciated! Thank you!</p>
",https://stackoverflow.com/questions/57696294/react-unit-test-jest-click-method-with-preventdefault,"['javascript', 'reactjs', 'unit-testing', 'react-test-renderer']",2597,True,0,1
How can we retrieve an interface from the base class and test it?,"<p><em>Unit Testing inquiry</em></p>

<p>I have to test the functionality of several classes, handled via their <code>superclass</code>. </p>

<p>I.e.: We have a custom class <code>CustomerInitialiserImpl</code> that extends <code>SpAsyncHandler</code>, which latter has the following method: <code>protected executeAsync(ExecuteAsync executeAsync)</code> (The parameter <code>ExecuteAsync</code> is an interface and what the method <code>executeAsync</code>, does is run the interface methods in a specific order within one or more async threads).</p>

<p><code>ExecuteAsync</code> looks like the following:</p>

<pre><code>public interface ExecuteAsync {
       void initApi();
       void doInBackground();
       void onPostExecute();
}
</code></pre>

<p><code>CustomerInitialiserImpl</code> has the following method:</p>

<pre><code>public void initialiseCustomer(int id) {
       executeAsync(new ExeuteAsync() {
/*here are instantiated the 3 overridden methods of the interface*/
       });
}
</code></pre>

<p>Since I don't care about the Async work done in <code>SpAsyncHandler</code>, it has its own tests, I need, however, to test if the methods of the interface are executed correctly and whether they trigger the expected outcome (f.i. the correct <code>post</code> events via <code>EventBus</code>, etc).</p>

<p>I've been trying to find a way to grab those instantiated interfaces on my test class, but I can't seem to find a way around it.</p>

<p>I have tried using <code>PowerMockito</code> to grab the <code>protected</code> method and see if I can return the <code>interface</code>, but I haven't succeeded.</p>

<p>Also, this interface includes the instantiation of some specific <code>api</code> methods that are to be mocked. Any clues on how can I proceed and if this can be done? I know the architecture doesn't sound ideal. How can I proceed?</p>
",https://stackoverflow.com/questions/57312186/how-can-we-retrieve-an-interface-from-the-base-class-and-test-it,"['java', 'android', 'unit-testing', 'superclass']",62,False,0,1
Valgrind gives possibly lost memory with g_test_trap_subprocess (),"<p>I am currently working on unit tests with glib-Testing for a C library I am writing. Part of these tests check that code fails on expected occasions (I am used to these sort of tests from Python where you would assert a certain Exception was raised). I am using the recipe in <a href=""https://developer.gnome.org/glib/stable/glib-Testing.html#g-test-trap-subprocess"" rel=""nofollow noreferrer"">the manual for glib-Testing for <code>g_test_trap_subprocess ()</code></a> (see minimal example below) which works fine from the unit-testing point of view and gives the correct tests.</p>

<p>My problem is when I run valgrind on the following minimal example (<code>test_glib.c</code>):</p>

<pre class=""lang-c prettyprint-override""><code>#include &lt;glib.h&gt;

void test_possibly_lost(){
        if (g_test_subprocess()){
                g_assert(1 &gt; 2);
        }
        g_test_trap_subprocess(NULL, 0, 0);
        g_test_trap_assert_failed();
}

int main(int argc, char **argv){
        g_test_init(&amp;argc, &amp;argv, NULL);

        g_test_add_func(""/set1/test"", test_possibly_lost);

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

<p>compiled with</p>

<pre><code>gcc `pkg-config --libs --cflags glib-2.0` test_glib.c
</code></pre>

<p>The output of <code>valgrind --leak-check=full ./a.out</code> is then</p>

<pre><code>==15260== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==15260== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==15260== Command: ./a.out
==15260== 
/set1/test: OK
==15260== 
==15260== HEAP SUMMARY:
==15260==     in use at exit: 24,711 bytes in 40 blocks
==15260==   total heap usage: 2,507 allocs, 2,467 frees, 235,121 bytes allocated
==15260== 
==15260== 272 bytes in 1 blocks are possibly lost in loss record 36 of 40
==15260==    at 0x483AB65: calloc (vg_replace_malloc.c:752)
==15260==    by 0x4012AC1: allocate_dtv (in /usr/lib/ld-2.29.so)
==15260==    by 0x4013431: _dl_allocate_tls (in /usr/lib/ld-2.29.so)
==15260==    by 0x4BD51AD: pthread_create@@GLIBC_2.2.5 (in /usr/lib/libpthread-2.29.so)
==15260==    by 0x48BE42A: ??? (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260==    by 0x48BE658: g_thread_new (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260==    by 0x48DCBF0: ??? (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260==    by 0x48DCC43: ??? (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260==    by 0x48DCD11: g_child_watch_source_new (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260==    by 0x48B7DF4: ??? (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260==    by 0x48BEA93: g_test_trap_subprocess (in /usr/lib/libglib-2.0.so.0.6000.6)
==15260==    by 0x1091DD: test_possibly_lost (in /dir/to/aout/a.out)
==15260== 
==15260== LEAK SUMMARY:
==15260==    definitely lost: 0 bytes in 0 blocks
==15260==    indirectly lost: 0 bytes in 0 blocks
==15260==      possibly lost: 272 bytes in 1 blocks
==15260==    still reachable: 24,439 bytes in 39 blocks
==15260==         suppressed: 0 bytes in 0 blocks
==15260== Reachable blocks (those to which a pointer was found) are not shown.
==15260== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==15260== 
==15260== For counts of detected and suppressed errors, rerun with: -v
==15260== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
</code></pre>

<p>The possibly lost memory bothers me, coincidentally my code also possibly loses 272 bytes so I think this might be a problem with the way I use glib rather than my own structs. Personally, I would treat possibly lost memory as definitely lost and I would like to get rid of it.</p>

<p>So my question is whether there is a <code>free</code> that I could cleverly insert to free the memory, a different recipe to check for failed asserts or are these lost 272 bytes just something I will have to live with?</p>
",https://stackoverflow.com/questions/57395919/valgrind-gives-possibly-lost-memory-with-g-test-trap-subprocess,"['c', 'unit-testing', 'valgrind', 'glib']",441,True,0,1
Are my Unit tests written correctly to test my code functions,"<p>Trying to write Unit tests to test my Python code project.</p>

<p>I have a gestioner.py file which checks for the User input and see if they are valid (from an allowed list) or not, (from a 'danger_list')
and then also checks if the entered command has any suspicious charecters entered to prevent security attacks.</p>

<p>Now I want to add Unit tests to my functions code in the Gestioner.py</p>

<p>Was following the writeup in Stackoverflow question: <a href=""https://stackoverflow.com/questions/3371255/writing-unit-tests-in-python-how-do-i-start"">Writing unit tests in Python: How do I start?</a></p>

<p>and then py.test documentation (<a href=""https://docs.pytest.org/en/latest/contents.html"" rel=""nofollow noreferrer"">https://docs.pytest.org/en/latest/contents.html</a>)</p>

<p>and I've written following test_gestioner.py to start my unit tests as below:</p>

<p>And all my three tests seeming Pasing, all the time. But I doubt if my these tests are really and correctly testing my code because when I expect the test to fail still that test Passes. </p>

<p>Am I doing this Unit testing of my code correctly ?
it appears to me that I am not, so please suggest where am I doing mistake in my unit tests ?</p>

<p><strong>Here are is my main script, Gestioner.py</strong></p>

<pre><code>

import sys
import re


class CmdGestioner:
    _allowed_list = ['fichier', 'binfile', 'prep', 'rep' ]
    _danger_list = ['gen', 'regen'] 

    def __init__(self):
        None

    def chk_cmds(self, mycmd):
        print('chk_cmds: lets look term at {}'.format(mycmd))
        regex = re.compile(r'[&amp;`%;$&gt;&lt;!#]')
        msg = bool(regex.search(mycmd))
        print('My command: ' +mycmd)
        if msg is True:
            print(msg)
            print('Found a suspicious entry in the command : {}'.format(mycmd))
            return -1
        else:
            print('Command seems clean {}'.format(mycmd))
            return 0


    def is_valid(self, in_command):
        valid = True


        cmd_mtg_str = ''.join(str(elem) for elem in in_command)



        for term in cmd_mtg_str.split():

            if term.strip('--') not in self._allowed_list:
                if term.strip('--') in self._forbidden_list:
                    valid = False
                    print('Found a forbidden Sec_Service command '+term)
                else:
                    print ('%s not found in list so need to runs checks on this!' % (term))
                    checkResult = self.chk_cmds(term)
                    if checkResult == -1:
                        valid = False
            else:
                print ('Found in list so term %s is valid' % (term))
        return valid




test_command = ' '.join(str(elem) for elem in sys.argv[1:])
cmd = CmdGestioner()

status = cmd.is_valid(test_command)
print ('\nStatus for command: %s is %s' % (test_command,status))

</code></pre>

<p><strong>and my unit test file (test_gestioner.py)</strong></p>

<pre><code>import sys
import re
import unittest
import pytest
from gestioner import CmdGestioner

cmd = CmdGestioner()


def test_chk_cmds_valid():
    mycmd = ""--binfile testbinfile""
    cmd.chk_cmds(mycmd)
    assert 'Status for command: ' +mycmd +' is True'


def test_chk_cmds_danger():
    mycmd = ""--gen genf""
    cmd.chk_cmds(mycmd)
    assert 'Status for command: ' +mycmd +' is False'


def test_chk_cmds_attacks():
    mycmd = "";ls""
    cmd.chk_cmds(mycmd)
    assert 'Found a suspicious entry in the command : ' .format(mycmd)
    assert 'Status for command: ' +mycmd +' is False


</code></pre>

<p><strong>My Unit tests being executed:</strong></p>

<pre><code>PS C:\Work\Questions_forums\SecService_messaging&gt; py.test -v                                                                                                                                                                                       ================================================================================== test session starts =============================================================================================================================
platform win32 -- Python 3.7.4, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- c:\users\SecUser\appdata\local\programs\python\python37\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.7.4', 'Platform': 'Windows-10-10.0.18362-SP0', 'Packages': {'pytest': '5.0.1', 'py': '1.8.0', 'pluggy': '0.12.0'}, 'Plugins': {'html': '1.21.1', 'metadata': '1.8.0'}}
rootdir: C:\Work\Questions_forums\SecService_messaging
plugins: html-1.21.1, metadata-1.8.0
collected 3 items

test_gestioner.py::test_chk_cmds_valid PASSED                                                                                                                                                                                                                           [ 33%]
test_gestioner.py::test_chk_cmds_danger PASSED                                                                                                                                                                                                                          [ 66%]
test_gestioner.py::test_chk_cmds_attacks PASSED                                                                                                                                                                                                                         [100%]

========================================================================================================================== 3 passed in 0.03 seconds ==========================================================================================================================
</code></pre>
",https://stackoverflow.com/questions/59143025/are-my-unit-tests-written-correctly-to-test-my-code-functions,"['python', 'unit-testing', 'pytest']",78,True,0,1
Azure Dev Ops Build Pipeline xunit nest fails (.net Core),"<p>I have a xunit test project written in .net core 2.2 which is being built using Azure Dev Ops</p>

<p>I have a .NET Core stage that builds the test project first using a command of build, task version 2.*, this stage works but im not sure if its necessary.</p>

<p>I have tried a second .NET Core state task version 2.* with command of test, this was continuing forever so I set a short timeout of 1 min (for now)</p>

<p>Here I get errors such as Assert.Equal() Failure, Expected: OK, Actual:   0</p>

<p>I have also added a 3rd stage Visual Studio Test, task version 2.* test assemblies, I have tried using Specific Location and Version.</p>

<p>I have been toggling between trying the two test types and some googling hasn't resolved it.</p>

<p>The software is to build a .net core website and we have 3 sets of unit tests to mock some interfaces to APIs and a small helper library.</p>

<p>UPDATE</p>

<hr>

<p>I have created a new Unit Testing Project using MSTest, in order to rule out xunit (for now)</p>

<p>The Yaml is below</p>

<p>steps:</p>

<pre><code>- task: VSTest@2
  displayName: 'VsTest - testAssemblies'
  inputs:
    testAssemblyVer2: |
     **\*test*.dll
     !**\*TestAdapter.dll
     !**\obj\**
     **\$(BuildConfiguration)\*\*unittests.dll
     !**\*Microsoft.VisualStudio.TestPlatform*
    vstestLocationMethod: location
    vstestLocation: 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\TestPlatform\'
    codeCoverageEnabled: true
    otherConsoleOptions: '/Framework:.NETCoreApp,Version=v2.2 /logger:console;verbosity=""normal""'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'
  timeoutInMinutes: 1
</code></pre>

<p>And here is an output from the log</p>

<pre><code>========================================================
Test selector : Test assemblies
Test assemblies : **\*test*.dll,!**\*TestAdapter.dll,!**\obj\**,**\Release\*\*unittests.dll,!**\*Microsoft.VisualStudio.TestPlatform*
Test filter criteria : null
Search folder : d:\a\1\s
Run settings file : d:\a\1\s
Run in parallel : false
Run in isolation : false
Path to custom adapters : null
Other console options : /Framework:.NETCoreApp,Version=v2.2 /logger:console;verbosity=""normal""
Code coverage enabled : true
Diagnostics enabled : false
Rerun failed tests: false
vstest.console.exe, specified location : C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Extensions\TestPlatform\
========================================================
[warning]No test assemblies found matching the pattern: **\*test*.dll,!**\*TestAdapter.dll,!**\obj\**,**\Release\*\*unittests.dll,!**\*Microsoft.VisualStudio.TestPlatform*.
======================================================
</code></pre>
",https://stackoverflow.com/questions/56950223/azure-dev-ops-build-pipeline-xunit-nest-fails-net-core,"['unit-testing', '.net-core', 'azure-devops', 'xunit']",165,False,0,0
Comparing ConcurrentQueue.Count to integer returns wrong result,"<p>I am writing usual <em>reader-writer</em> functionality with one main thread that equeues and several threads that dequeues. So, there is a part of the code where I am comparing count of items in my <code>ConcurrentQueue</code> with some integer number, let's call it ""maxSize"". Despite the fact that <code>.Count</code> returns <em>1</em> and <em>maxSize</em> is 10, <code>queue.Count &gt;= maxSize</code> returns true.</p>

<p>I tried to debug with breakpoints, set only one dequeue thread and even pause it. That happened right after main thread enqueued and after several lines of code this comparing returns the result that says 1 >= 10. 
I am sure the main thread puts only 1 item at this moment, I am sure no <code>Dequeue()</code> was called. Also, I've tried to double-check with locking but sometimes it does not help.
I am wondering that there could be some <em>magic</em> that does not allow me to compare values properly in a way I do it, because when I see in a debugger that 1 >= 10 is true, I'm torn apart.</p>

<pre><code>
int maxSize = 10;
Timer timer;

ctor(int interval)
{
    queue = new ConcurrentQueue&lt;HttpSessionState&gt;();
    timer = new Timer(TimeSpan.FromSeconds(interval).TotalMilliseconds);
    timer.Elapsed += (sender, args) =&gt; PulseIfAvailableForProcessing(true);
}

void Process()
{
    queue.Enqueue(obj);
    // interval here is huge, several minutes
    timer.Start();
    PulseIfAvailableForProcessing(false);
}

bool PulseIfAvailableForProcessing(bool isTimeout)
{
    if (isTimeout)
    {
        ...
    }
    else
    {
        // here 1 &gt;= 10 gives true
        if (queue.Count &gt;= maxSize)
        {
            lock (_dataLock)
            {
                // here in debug queue.Count is still 1, however 1 &gt;= 10 returns false
                if (queue.Count &gt;= maxSize)
                {
                    Pulse();
                }
            }
        }
    }
}
</code></pre>

<p>In despair I've added logging and I see that during unit testing the issue is reproducible even inside of a lock statement.</p>
",https://stackoverflow.com/questions/55798088/comparing-concurrentqueue-count-to-integer-returns-wrong-result,"['c#', 'multithreading', 'concurrent-queue']",311,False,0,0
How to test (in google test) that a function is called with the correct parameters,"<p>I have a class and this class has a method (""original_method"") that uses two objects of different types. In this method there are two calls: one call to a method of the first object that returns a value which is then used for calling a method of the second object. I was wondering what is the correct way of unit testing such behavior (using google-test). Specifically, I want to test that the argument provided to the second object is indeed the value returned from the first.</p>

<p>Currently I achieve this using parametrized tests - the code below shows what I do:</p>

<pre class=""lang-cpp prettyprint-override""><code>TEST_P(SomeTestSuite, checkingIfCalledWithTheRightArgument)
{
    EXPECT_CALL(*obj1, get_some_value()).WillOnce(Return(name_of_value));
    EXPECT_CALL(*obj2, do_a_calculation(name_of_value));

    obj0-&gt;call_original_method();
}
</code></pre>

<p>I have a fixture for my original class under testing, i have mocks for obj1 and obj2, I provide a value for ""name_of_value"" in the parameters and the test works.</p>

<p>My problem is that this doesn't seem to be the correct way, I believe I shouldn't have to pass a parameter to check such a functionality. I would appreciate if somebody could explain to me how i should have approached the problem. </p>

<p>Thank you.</p>

<p>EDIT:</p>

<p>I think I could do:</p>

<pre class=""lang-cpp prettyprint-override""><code>TEST_F(SomeTestSuite, checkingIfCalledWithTheRightArgument)
{
    EXPECT_CALL(*obj1, get_some_value());

    auto name_of_value = obj1-&gt;get_some_value();

    EXPECT_CALL(*obj2, do_a_calculation(name_of_value));

    obj0-&gt;call_original_method();
}

</code></pre>

<p>but I'm not sure if this captures (or actually tests) the original behaviour...</p>
",https://stackoverflow.com/questions/58680487/how-to-test-in-google-test-that-a-function-is-called-with-the-correct-paramete,"['c++', 'googletest']",559,False,0,0
How to integrate mocking framework with Specflow,"<p>I am looking to do some end to end testing using specflow.</p>

<p>I have a windows service that picks up various files, does some processing, prints out those files and then moves said files to a success or failed archive folder.</p>

<p>I don't want to actually print the files out during my tests so thought that instead I could use a mocking framework to mock the result of the print operation for my tests.</p>

<p>I have used a number of mocking frameworks for my unit testing in the past but not used one alongside specflow.</p>

<p>I am not sure the best/easiest way to integrate the two. I have seen mention of creating a specflow binding file and use the [beforescenario] tag to initialise and do my mocking code in that method.</p>

<p>Would this work? Is there anything else I would need to do? Is there a better solution?</p>

<p>Rough example of test</p>

<pre><code>@BizTalk
Feature: Printing_Push
    Tests Printing

Background:
    Given all test data is stored under C:\TestData\XXXXXXXXXXXX

@HappyFlow
@SysTest
Scenario: Printing_HappyFlow_Success
    When the file is copied
        | Property      | Value                            |
        | Source File  | XXXXXXXXXXXXXXXXXXXX.dat                        |            
        | Target Folder | C:\Temp\XXXXXXXXX  |
    Then 1 files expected with extension dat will appear in the C:\xxxxxxxxxxxxxx folder within 10 seconds.
</code></pre>

<p>A filesystem watcher picks up the file. It is then processed before being printed and then the file is moved to an archive folder. The test will initiate this process by dropping file into expected file location. The test does not directly call the code.</p>
",https://stackoverflow.com/questions/57182705/how-to-integrate-mocking-framework-with-specflow,"['c#', 'unit-testing', 'mocking', 'integration-testing', 'specflow']",785,False,0,0
Does .NET Core handle correctly multiple classes/file instead of larger ones,"<p>Sorry it's more about a good practice question than an actual technical issue but I'm a bit concerned here and I need your opinion. </p>

<p>I'm a software engineer, mainly front-end but I started working on the back-end of my current project, which is in .NET Core, I'm having some discussion with the senior back-end developer here.</p>

<p>I'm completely for single-responsibility classes, unit-testing and extraction of logic that shouldn't fit the same class, but he tends to have larger functions/classes.</p>

<p>As we discussed he told me that .NET Core wasn't handling correctly a high number of classes/files and told me there would be performance impact. This seems unreal to me, as I've worked before on many other back-end languages and it was never raised as something that could impact the performance in a noticeable way. </p>

<p>Is there any way I can prove him wrong ( or right ? ) about that subject ? It's quite of a blocker for me as I'd love to increase general quality of code in the back-end. </p>

<p>Thank you for your answers, I'd be glad to read articles or anything related to the subject.</p>
",https://stackoverflow.com/questions/54885663/does-net-core-handle-correctly-multiple-classes-file-instead-of-larger-ones,"['c#', '.net', 'asp.net-core', 'architecture']",130,False,0,1
"JPA: &#39;CascadeType.REMOVE&#39; or &#39;orphanRemoval = true&#39;, which use in a n:n relation that generate new table/class with EmbeddeId class?","<p>I am developing an REST API to a pizzeria store. And here i'm trying to delete a Flavor and all data related to it. Further explained below:</p>

<p>Classes:</p>

<ul>
<li><p><code>Flavor</code> have at least one <code>Filling</code>, each one taking a position on it.</p>

<ul>
<li>i.e: Souce (at pos. 1), mozzarela (at pos. 2) tomato (at pos. 3) </li>
</ul></li>
<li><p><code>Flavor</code>s must have a price to each <code>Size</code></p></li>
</ul>

<p>With that in mind, we can conclude that exist two many-to-many relationships:</p>

<ul>
<li><code>Flavor</code> to many <code>Filling</code></li>
<li><code>Flavor</code> to many <code>Size</code></li>
</ul>

<p><a href=""https://i.stack.imgur.com/iVD1f.png"" rel=""nofollow noreferrer"">Class diagram of actual implementation</a></p>

<p>The requirement is to: delete a <code>Flavor</code>, and automatically delete all the <code>FillingPositionFlavor</code> and <code>FlavorPriceSize</code>.</p>

<p>But,I'm confused on use of <code>CascadeType.REMOVE</code> and <code>orphanRemoval = true</code>:</p>

<p>When I use Cascade and OrphanRemoval on Flavor.sizePrices, get a HibernateException when trying to edit a Flavor, exclusion works fine:
<code>A collection with cascade=""all-delete-orphan"" was no longer referenced by the owning entity instance: com.pkg.Flavor.sizePrices</code></p>

<p>When I use Cascade on Flavor.sizePrices, get a PSQLException when excluding a Flavor, editing works fine:
<code>ERROR: update or delete on table ""tb_flavor"" violates foreign key constraint ""fk9orw0yhtc0e06ka84dbcd2c82"" on table ""tb_flavor_size_price""</code></p>

<p>I'm doing unit testing of services in Spring Boot to test all the CRUD operations.</p>

<p>Below is the actual code, I hid properties like id and others to facilitate the read.</p>

<pre class=""lang-java prettyprint-override""><code>@Entity
@Table(name = ""tb_flavor"")
class Flavor {

   @OneToMany(cascade = {CascadeType.PERSIST,CascadeType.REMOVE},orphanRemoval = true)
   private Set&lt;FlavorPositionFilling&gt; flavors = new HashSet&lt;FlavorPositionFilling&gt;();

   @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE},orphanRemoval = true)
   private Set&lt;FlavorPriceSize&gt; priceSizes;

   // other properties and methods
}
</code></pre>

<pre class=""lang-java prettyprint-override""><code>@Entity
@Table(name = ""tb_flavor_price_size"")
class FlavorPriceSize {

   @EmbeddedId
   private FlavorPriceSizeEmbeddeId id;
   private float price;

   // other properties and methods
}

@Embeddable
class FlavorPriceSizeEmbeddeId implements Serializable {
   @ManyToOne(cascade = { CascadeType.ALL })
   @JoinColumn(name = ""ID_FLAVOR_FK"", referencedColumnName = ""id_flavor"")
   private Flavor flavor;

   @ManyToOne(cascade = { CascadeType.ALL })
   @JoinColumn(name = ""ID_SIZE_FK"", referencedColumnName = ""id_size"")
   private Size size;
}
</code></pre>

<pre class=""lang-java prettyprint-override""><code>@Entity
@Table(name = ""tb_flabor_position_filling"")
class FlaborPositionFilling {

    @EmbeddedId
    private FlaborPositionFillingEmbeddedId id;
    private Integer position;
}

@Embeddable
class FlaborPositionFillingEmbeddedId implements Serializable {
    @ManyToOne(cascade = CascadeType.REMOVE)
    @JoinColumn(name=""ID_FLAVOR_FK"", referencedColumnName=""id_flavor"")
    private Flavor sabor;

    @ManyToOne()
    @JoinColumn(name=""ID_FILLING_FK"", referencedColumnName=""id_filling"")
    private Filling filling;
}

</code></pre>

<p>I've read a lot about both, but still not understand the right use of each and their effect on operations. Can anyone explain it to me? Show videos, images, code...</p>
",https://stackoverflow.com/questions/56519863/jpa-cascadetype-remove-or-orphanremoval-true-which-use-in-a-nn-relation,"['java', 'hibernate', 'jpa', 'many-to-many', 'cascade']",1433,True,0,1
C# Cast concrete class variables at run time (Dependency Injection),"<p>I'm trying to implement dependency injection in my project to connect with SQL server for unit testing.
I have used the inbuilt abstract classes came in SQL library and created my own Mock classes for SqlCommand,SqlConnection and SqlTransaction.
Below are the my classes.</p>

<p>I'm unable to use SqlCommand property(SqlParameterCollection) method which is named as AddWithValue in my program.cs file at compile time.</p>

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

<p><strong>'DbParameterCollection' does not contain a definition for 'AddWithValue' and no accessible extension method 'AddWithValue' accepting a first argument of type 'DbParameterCollection' could be found (are you missing a using directive or an assembly reference?)</strong></p>

<p>Object DbParameterCollection resides in abstract class DbCommand however the given Object which has the AddWithValue method resides in concrete class which is SqlCommand.</p>

<p>How can i tell the compiler that AddWithValue method should be called on the property of class SqlCommand and not on DBCommand.</p>

<p>Here are all my classes.</p>

<p>As i'm new to this i haven't found anything injecting concrete classes at runtime using reflection or there might be some other ways to do it.</p>

<p>SQLWrapper.cs</p>

<pre><code>namespace DAL
{
    public class SQLWrapper
    {
        private Context _ctx;
        private string _referenceID;
        private string _connectionKey;
        private static string _connectionString;
        private int _timeout = 180;

        public SQLWrapper(Context ctx, string referenceID, string connectionKey)
        {
            _ctx = ctx;
            _referenceID = referenceID;
            _connectionKey = connectionKey;
        }

        public async Task&lt;Error&gt; GetConnectingStringAsync()
        {
           // Gets the connection string from config
        }

        /// &lt;summary&gt;
        /// Executes the statement.
        /// &lt;/summary&gt;
        /// &lt;param name=""ctx""&gt;&lt;/param&gt;
        /// &lt;param name=""command""&gt;&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public async Task&lt;Error&gt; ExecuteStatementAsync()
        {
            Error error = null;
            try
            {
                error = await GetConnectingStringAsync();
                if (error != null)
                {
                    return error;
                }

                using (_ctx.connection)
                {
                    _ctx.connection.ConnectionString = _connectionString;
                    _ctx.command.CommandTimeout = _timeout;
                    try
                    {
                        await _ctx.connection.OpenAsync();
                        _ctx.command.Connection = _ctx.connection;
                        _ctx.command.Prepare();
                        _ctx.transaction = _ctx.connection.BeginTransaction();
                        await _ctx.command.ExecuteNonQueryAsync();
                        _ctx.transaction.Commit();
                        return null;
                    }
                    catch (Exception ex)
                    {
                        if (_ctx.transaction != null)
                        {
                            _ctx.transaction.Rollback();
                        }
                        return error;
                    }
                }
            }
            catch (Exception ex)
            {
                return error;
            }
        }        
    }
}

</code></pre>

<p>MockCommand.cs</p>

<pre><code>namespace DAL
{
    class MockCommand : DbCommand
    {
        private string _commandText;
        private int _commandTimeout;
        private DbConnection _DbConnection;

        public MockSQL Connection { get; set; }
        public override string CommandText { get =&gt; _commandText; set =&gt; _commandText = value; }
        public override int CommandTimeout { get =&gt; _commandTimeout; set =&gt; _commandTimeout = value; }
        public override CommandType CommandType { get =&gt; throw new NotImplementedException(); set =&gt; throw new NotImplementedException(); }
        public override bool DesignTimeVisible { get =&gt; throw new NotImplementedException(); set =&gt; throw new NotImplementedException(); }
        public override UpdateRowSource UpdatedRowSource { get =&gt; throw new NotImplementedException(); set =&gt; throw new NotImplementedException(); }
        protected override DbConnection DbConnection { get =&gt; _DbConnection; set =&gt; _DbConnection = value; }

        new public SqlParameterCollection Parameters { get; }
        protected override DbParameterCollection DbParameterCollection =&gt; null;

        protected override DbTransaction DbTransaction { get =&gt; throw new NotImplementedException(); set =&gt; throw new NotImplementedException(); }

        public override void Cancel()
        {
            throw new NotImplementedException();
        }

        public override int ExecuteNonQuery()
        {
            return 0;
        }

        public override object ExecuteScalar()
        {
            throw new NotImplementedException();
        }

        public override void Prepare()
        {
            return;
        }

        protected override DbParameter CreateDbParameter()
        {
            throw new NotImplementedException();
        }

        protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
        {
            throw new NotImplementedException();
        }
    }
}

</code></pre>

<p>MockSQL.cs</p>

<pre><code>namespace DAL
{
    class MockSQL : DbConnection
    {
        private string _connectionString;
        public override string ConnectionString { get =&gt; """"; set =&gt; _connectionString = value; }

        public override string Database =&gt; throw new NotImplementedException();

        public override string DataSource =&gt; throw new NotImplementedException();

        public override string ServerVersion =&gt; throw new NotImplementedException();

        public override ConnectionState State =&gt; throw new NotImplementedException();

        public override void ChangeDatabase(string databaseName)
        {
            throw new NotImplementedException();
        }

        public override void Close()
        {
            throw new NotImplementedException();
        }

        public override void Open()
        {
            return;
        }

        protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
        {
            return new MockTransaction();
        }

        protected override DbCommand CreateDbCommand()
        {
            throw new NotImplementedException();
        }
    }
}

</code></pre>

<p>MockTransaction.cs</p>

<pre><code>namespace DAL
{
    class MockTransaction : DbTransaction
    {
        public override IsolationLevel IsolationLevel =&gt; throw new NotImplementedException();

        protected override DbConnection DbConnection =&gt; throw new NotImplementedException();

        public override void Commit()
        {
            return;
        }

        public override void Rollback()
        {
            throw new NotImplementedException();
        }
    }
}

</code></pre>

<p>Context.cs</p>

<pre><code> public class Context
    {
        public DbConnection connection;
        public DbCommand command;
        public DbTransaction transaction;
        public ICongigRPC config;
    }
</code></pre>

<p>ContextInitializer.cs</p>

<pre><code>public static class ContextInitializer
    {
        public static Context InitCtx()
        {
            return new Context()
            {
                connection = new SqlConnection(),
                command = new SqlCommand(),
                transaction = null
            };
        }
    }
</code></pre>

<p>Program.cs</p>

<pre><code>Context ctx = MockContextInitializer.MockInitCtx();
            ctx.command.CommandText = ""SELECT * FROM MEMBERMAPPING WHERE OldMemberID = @OldMemberID;"";
            ctx.command.Parameters.AddWithValue(""@OldMemberID"", ""1234"");
            SQLWrapper wrapper = new SQLWrapper(ctx, ""123"", ""123"");
            wrapper.ExecuteStatementAsync();
</code></pre>
",https://stackoverflow.com/questions/58488519/c-cast-concrete-class-variables-at-run-time-dependency-injection,"['c#', 'sql-server']",152,False,0,0
Should you write unit tests for code that tests application behavior?,"<p>I'm wondering if you should or should not write unit tests for code that's part of the main application and can be called by the customer even though the code is only responsible for stress testing part of the application. </p>

<p>Actually, I should maybe explain why I'm asking: I used to have the opinion all production code should have unit tests no matter what the code does. But I now got two people telling me not to write unit tests for code like this and one of them is a person that teaches others about TDD and unit testing and whom I respect a lot. His explanation was:
'The purpose of unit tests is to verify good design practices, provide internal documentation of understanding of requirements and design decisions, and serve as a continuous proof of functional correctness of units of code (not necessarily the functional correctness of the entire deliverable). That had nothing to do with stress tests, that are only aimed to produce an artifact of proof of performance or reliability.'</p>

<p>So I'm now really confused if my thinking of all production code needing unit tests was wrong for years.</p>
",https://stackoverflow.com/questions/58072967/should-you-write-unit-tests-for-code-that-tests-application-behavior,['unit-testing'],25,False,-2,1
Failed loading ext\php_xdebug-2.6.1-7.1-vc14-nts.dll and Error:No code coverage driver is available,"<p>so i've been doing some unit testing on my laravel project. I need to know the code coverage of my test and so do i install xdebug on my computer. but after i follow the installation guide i always get this error</p>
<blockquote>
<p>PS D:\Telkom\tpncms&gt; vendor\bin\phpunit tests\Feature\WebmasterBannersTest.php</p>
<p>Failed loading ext\php_xdebug-2.6.1-7.1-vc14-nts.dll</p>
<p>PHPUnit 6.5.14 by Sebastian Bergmann and contributors.</p>
<p>Error:         No code coverage driver is available</p>
<p>..........                                                        10 / 10 (100%)</p>
<p>Time: 3.79 seconds, Memory: 26.00MB</p>
</blockquote>
<p>here are the snippet of my php.ini</p>
<pre><code>[XDebug]
zend_extension = php_xdebug-2.6.1-7.1-vc14-nts.dll
xdebug.profiler_append = 0
xdebug.profiler_enable = 0
xdebug.profiler_enable_trigger = 0
xdebug.profiler_output_dir = &quot;c:\xampp\tmp&quot;
;xdebug.profiler_output_name = &quot;cachegrind.out.%t-%s&quot;
xdebug.remote_enable = 1
xdebug.remote_handler = &quot;dbgp&quot;
xdebug.remote_host = &quot;127.0.0.1&quot;
xdebug.remote_log=&quot;c:\xampp\tmp\xdebug.txt&quot;
xdebug.remote_port = 9000
xdebug.trace_output_dir = &quot;c:\xampp\tmp&quot;
; 3600 (1 hour), 36000 = 10h
xdebug.remote_cookie_expire_time = 36000
</code></pre>
<p>i also pass my php info to download the Xdebug version from the <a href=""https://xdebug.org/wizard.php"" rel=""nofollow noreferrer"">https://xdebug.org/wizard.php</a> recommendation, so i get the right installation for my device. ive been searching for the right solution from this site like changing the php.ini, or changing the Xdebug version, but nothings work</p>
<p>while in the php info the xdebug is appearing. where does it go wrong?
im using laravel 5.5 and visual studio code as my text editor</p>
<p>i installed my xdebug on C:\PHP7.1\ext\php_xdebug-2.6.1-7.1-vc14-nts.dll.</p>
<p>is it because i already installed the php outside the php that come with the XAMPP?
if so how do i solve it?</p>
",https://stackoverflow.com/questions/54921276/failed-loading-ext-php-xdebug-2-6-1-7-1-vc14-nts-dll-and-errorno-code-coverage,"['php', 'laravel', 'unit-testing', 'xdebug']",301,False,0,1
NuGet metapackage in a project doesn&#39;t allow the project to refer to its contents,"<p>There are several analyzers whose NuGet packages I almost always include in any project I make.  It's annoying adding them all individually whenever I start a new project, so I have long wanted to make a NuGet package of my own that just says ""include these other packages"".  I recently did so, and it seems to work fine.  I made the following nuspec file, did a ""nuget pack"" and then a ""nuget push"" to a private package server:</p>

<pre><code>&lt;package xmlns=""http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd""&gt;
  &lt;metadata&gt;
    &lt;id&gt;Rwv37.Metapackage.Analyzers&lt;/id&gt;
    &lt;version&gt;1.0.0&lt;/version&gt;
    &lt;authors&gt;Robert William Vesterman&lt;/authors&gt;
    &lt;owners&gt;Robert William Vesterman&lt;/owners&gt;
    &lt;requireLicenseAcceptance&gt;false&lt;/requireLicenseAcceptance&gt;
    &lt;description&gt;A collection of frequently used analyzers.&lt;/description&gt;
    &lt;copyright&gt;Copyright 2019 Robert William Vesterman&lt;/copyright&gt;
    &lt;developmentDependency&gt;true&lt;/developmentDependency&gt;
    &lt;dependencies&gt;
      &lt;group targetFramework=""netstandard2.0""&gt;
        &lt;dependency id=""CSharpGuidelinesAnalyzer"" version=""3.1.0"" /&gt;
        &lt;dependency id=""IDisposableAnalyzers"" version=""2.1.2"" /&gt;
        &lt;dependency id=""Microsoft.CodeAnalysis.FxCopAnalyzers"" version=""2.9.4"" /&gt;
        &lt;dependency id=""StyleCop.Analyzers"" version=""1.1.118"" /&gt;
      &lt;/group&gt;
    &lt;/dependencies&gt;
  &lt;/metadata&gt;
&lt;/package&gt;
</code></pre>

<p>I then decided to do the same thing with a bunch of test-related packages that I almost always include in all of my unit test projects:</p>

<pre><code>&lt;package xmlns=""http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd""&gt;
  &lt;metadata&gt;
    &lt;id&gt;Rwv37.Metapackage.UnitTesting&lt;/id&gt;
    &lt;version&gt;1.0.0&lt;/version&gt;
    &lt;authors&gt;Robert William Vesterman&lt;/authors&gt;
    &lt;owners&gt;Robert William Vesterman&lt;/owners&gt;
    &lt;requireLicenseAcceptance&gt;false&lt;/requireLicenseAcceptance&gt;
    &lt;description&gt;A collection of frequently used unit testing stuff.&lt;/description&gt;
    &lt;copyright&gt;Copyright 2019 Robert William Vesterman&lt;/copyright&gt;
    &lt;developmentDependency&gt;true&lt;/developmentDependency&gt;
    &lt;dependencies&gt;
      &lt;group targetFramework=""netstandard2.0""&gt;
        &lt;dependency id=""FluentAssertions"" version=""5.7.0"" /&gt;
        &lt;dependency id=""FluentAssertions.Analyzers"" version=""0.11.4"" /&gt;
        &lt;dependency id=""Moq"" version=""4.12.0"" /&gt;
        &lt;dependency id=""Moq.Analyzers"" version=""0.0.7"" /&gt;
        &lt;dependency id=""xunit"" version=""2.4.1"" /&gt;
        &lt;dependency id=""xunit.analyzers"" version=""0.10.0"" /&gt;
      &lt;/group&gt;
    &lt;/dependencies&gt;
  &lt;/metadata&gt;
&lt;/package&gt;
</code></pre>

<p>That did not work.  When I add this metapackage to a unit testing project, I can see it (and its constituent packages) in VS 2019's Solution Explorer, but I get a bunch of errors saying things like:</p>

<blockquote>
  <p>The type or namespace name 'FluentAssertions' could not be found (are you missing a using directive or an assembly reference?)</p>
</blockquote>

<p>I thought maybe I was misunderstanding the ""developmentDependency"" tag, so I removed that and bumped the version number, but this did not help.</p>

<p>What am I doing wrong? How do I do it correctly? Thanks.</p>
",https://stackoverflow.com/questions/57337354/nuget-metapackage-in-a-project-doesnt-allow-the-project-to-refer-to-its-content,"['nuget', 'nuget-package']",145,True,0,1
C# IoC Project Structure Standards,"<p>What is the recommended folder structure for a IoC C# project? For a MVVM project, the standard is to create folders named Views and ViewModels (and where do you put interfaces and unit testing classes?)</p>

<p>What about a DLL project, that has no views, but exposes many classes to be created via IoC, which folders should be in my project?</p>

<p>Also as I'm starting to refactor code into IoC, I'm running into issues with the SettingsFile class that contains data that is serialized into a file. It contains a few methods:</p>

<ul>
<li>void SetDefaultValues()</li>
<li>SettingsFile Load()</li>
<li>void Save()</li>
<li>string Validate()</li>
<li>SettingsFile Copy()</li>
</ul>

<p>The main issue is with Load, as deserializing the object creates a new hard instance of the class, bypassing the principles of IoC. What's the right way of handling the scenario?</p>

<p>I'm thinking of moving all code outside of that class so that this class is only responsible for being serialized/deserialized without any code, and then excluding it from IoC. Is this the right thing to do? It's a similar problem when using Entity Framework and using any auto-generated table classes.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/54103609/c-ioc-project-structure-standards,"['c#', 'mvvm', 'inversion-of-control', 'castle-windsor']",265,True,0,1
Cannot resolve AndroidJUnit after migrating to Androidx,"<p>I have successfully migrated to Androidx, everything seems to work. Now I'm stuck in migrating (or basically creating tests) for my project.</p>

<p>I added those dependencies to my project:</p>

<pre><code>    implementation fileTree(dir: 'libs', include: ['*.jar'])
  implementation 'androidx.appcompat:appcompat:1.1.0'
  implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
  testImplementation 'junit:junit:4.12'
  androidTestImplementation 'androidx.test.ext:junit:1.1.1'
  androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
  androidTestImplementation 'androidx.test:rules:1.2.0'
  androidTestImplementation 'androidx.test:runner:1.2.0'

  implementation 'androidx.multidex:multidex:2.0.1'
  implementation 'androidx.cardview:cardview:1.0.0'
  implementation 'com.google.android.material:material:1.2.0-alpha03'

  implementation 'com.google.android.gms:play-services-maps:17.0.0'
  implementation 'com.google.android.gms:play-services-location:17.0.0'
  implementation 'com.google.android.gms:play-services-identity:17.0.0'
  implementation 'com.google.android.gms:play-services-gcm:17.0.0'
  implementation 'joda-time:joda-time:2.9.9'
  implementation 'com.google.code.gson:gson:2.8.5'
  implementation 'ch.acra:acra:4.6.1'
  implementation 'com.squareup.okhttp3:okhttp:4.2.1'
  implementation 'com.diegocarloslima:fgelv:0.1.2'
  implementation 'com.luckycatlabs:SunriseSunsetCalculator:1.1'
  implementation project(':cp963_cpik_lib') 
</code></pre>

<p>I created two paths for two tests (one is for test which works fine and Android studio recognize the @Test annotation of junit class, the other is for androidTest which Android studio does not recognize any of the classes). Both test and androidTest are green and have the same package name as my src folder. </p>

<p>This is the test file (works just fine):</p>

<pre><code>    import org.junit.Test;

import static org.junit.Assert.*;

/**
 * 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>This is androidTest that I'm not sure why Android Studio is not able to import any of the classes</p>

<pre><code>@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    @Test
    public void useAppContext() {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();

        assertEquals(""xxxxxx"", appContext.getPackageName());
    }
}
</code></pre>

<p>The classes that I mean are @RunWith, AndroidJUnit4, @Test, InstrumentationRegistry, assertEquals. </p>

<p>I basically used the generated tests that came with a new project. Do I need somehow to configure Android Studio to use junit in androidTest? or is it something to do with the copilot library that I'm using?</p>

<p>Thank you</p>

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

<p>I added the previous test that was in my project:</p>

<pre><code>public class ApplicationTest extends ApplicationTestCase&lt;Application&gt; {
public ApplicationTest() {
    super(Application.class);
}
</code></pre>

<p>}
It's an old project which I'm trying to use more up to date dependencies and unit testing.</p>

<p><strong>Edit 2</strong>
This is my build.gradle.</p>

<pre><code>apply plugin: 'com.android.application'

android {

  compileSdkVersion 28
  buildToolsVersion '28.0.3'
  defaultConfig {
    applicationId ""xxx.xxx.xxx""
    minSdkVersion 19 // 17 = 4.2 Jelly Bean, 18 = 4.3 jelly bean, 19 = 4.4 kitkat
    //noinspection ExpiredTargetSdkVersion
    targetSdkVersion 19 // 21 = 5.1 Lollipop
    versionCode 65
    versionName ""1.65""
    testInstrumentationRunner ""androidx.test.runner.AndroidJUnitRunner""
    multiDexEnabled true
  }
  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
      signingConfig signingConfigs.config
    }
    debug {
      signingConfig signingConfigs.config
    }
  }
}

dependencies {
  implementation fileTree(dir: 'libs', include: ['*.jar'])
  implementation 'androidx.appcompat:appcompat:1.1.0'
  implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
  testImplementation 'junit:junit:4.12'
  androidTestImplementation 'androidx.test.ext:junit:1.1.1'
  androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
  androidTestImplementation 'androidx.test:rules:1.2.0'
  androidTestImplementation 'androidx.test:runner:1.2.0'

  implementation 'androidx.multidex:multidex:2.0.1'
  implementation 'androidx.cardview:cardview:1.0.0'
  implementation 'com.google.android.material:material:1.2.0-alpha03'

  implementation 'com.google.android.gms:play-services-maps:17.0.0'
  implementation 'com.google.android.gms:play-services-location:17.0.0'
  implementation 'com.google.android.gms:play-services-identity:17.0.0'
  implementation 'com.google.android.gms:play-services-gcm:17.0.0'
  implementation 'joda-time:joda-time:2.9.9'
  implementation 'com.google.code.gson:gson:2.8.5'
  implementation 'ch.acra:acra:4.6.1'
  implementation 'com.squareup.okhttp3:okhttp:4.2.1'
  implementation 'com.diegocarloslima:fgelv:0.1.2'
  implementation 'com.luckycatlabs:SunriseSunsetCalculator:1.1'

  implementation project(':cp963_cpik_lib')
  androidTestImplementation 'junit:junit:4.12' // I tried with this and without but I got the same result.
}
</code></pre>
",https://stackoverflow.com/questions/59457535/cannot-resolve-androidjunit-after-migrating-to-androidx,"['android', 'junit', 'android-espresso']",493,False,0,0
"When using Javascript&#39;s Reflect API to build an instance of a class that extends another, why are indexed arrays a shared scope?","<p>I've built a sample using the <a href=""https://www.typescriptlang.org/play/#code/MYGwhgzhAEBCkFMDC4rQN4ChrQPoFsEAXMALgwG0BrBAT3IiICcBLAOwHMBdB59jgL4BubNGAB7NoyYBXYEXFMAFAEoMonEQAWLCADoCxMNAC8GYaIGYrmUJBgBZWinvQEADyII2AExjwIZFQYLBwAByZxMIBGAH5eVk4RUQkpZjkFZXYWInIABTAmIhYwEAAeJxcoAD4VUJxoCBkwhGUVDWgAeQAjACsEeT17Fg42JW1dABpobKIVERwrG1TGaG7EAEk0sDZgBFNoNgQAd2hK4KV6iKjo8gBydcC7ydFDEnJ6nC0EEBBxe+OihAPjulms7VsklWTAQADMQAMiFtGDs9gcAEpwhGDFbpeRKc72aYUR4IZEkXYILjzTAw+GI8mohAGQgkA7oaDfX7-aB3OnY4qSO7QZZQohiSQkfDsMBeHyMykHI6nQlQS6ia4xe6pKUyuXPV6ssjqBrQDjicQ+bq0BAAoEgsECCG4tbiDgyCAKtFmTH0nFi2T41UQYk6sDStiyhDy7aU6kibpuj1e5lvMAUO7my3WhB3LgHO5hiNRkHJUqtIhKABE0WgVegAGpoAApADKnQAcnppPwWLDaEpSSmVO1y0VqwAmOuNlvtrs9zh9gf8hmxvYjzBjytVgDM06bbc73b4i-7SiLeujw9HCPHVYALPvZ0eFxwl4Ok561wgN0A"" rel=""nofollow noreferrer"">Typescript playground</a>, but the behaviour isn't related to typescript specifically. It's a bit easier to show in code (link includes compiled JS, for those looking to ignore TS):</p>

<p>If you extend a class which uses an indexed array as a property</p>

<pre><code>class BaseClass {
  _meta: {[key: string]: string};
  constructor() {
    this._meta = {};
  }
}

class MyClass extends BaseClass {
  prop1?: string;

  constructor(init: Partial&lt;MyClass&gt;){
    super()
    Object.assign(this, init);
  }
}
</code></pre>

<p>Then from a base model use the reflection API to create other instances, you can get different behaviours depending how you build your subsequent models.</p>

<p>If you create a new object to assign to <code>_meta</code>, it works the way you'd expect it to:</p>

<pre><code>const baseInstance = new MyClass({
  prop1: 'base',
  _meta: {
    hello: 'world'
  }
})

const reflectInstance = Reflect.construct(MyClass, [baseInstance]);
reflectInstance._meta = { hello: 'reflection' }

alert(""1 "" + JSON.stringify(baseInstance)) // as expected
alert(""2 "" + JSON.stringify(reflectInstance)) // as expected
</code></pre>

<p>but if you assign to the container using array notation, the scope becomes contaminated, i.e. it shares scope with the source model:</p>

<pre><code>const contaminatedInstance = new MyClass({
  prop1: 'contaminated',
  _meta: {
    goodbye: 'world'
  }
})

const bogusInstance = Reflect.construct(MyClass, [contaminatedInstance]);
bogusInstance._meta['goodbye'] = 'contaminated';

alert(""3 "" + JSON.stringify(contaminatedInstance)) // _meta has unexpectedly changed
alert(""4 "" + JSON.stringify(bogusInstance)) // as a result of bogusInstance

</code></pre>

<p>Does anyone know why this is? I can fuzzily justify things by saying the _meta property has a common address, and because it's extended there wasn't a <code>new</code> invocation of the base model thus making it common; but this is a difficult case to remember when it comes up outside of unit testing; especially during a PR.</p>

<p>Any advice on how to avoid this while still using array notation would be great.</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/57467502/when-using-javascripts-reflect-api-to-build-an-instance-of-a-class-that-extends,"['javascript', 'typescript', 'associative-array', 'reflect']",40,True,0,1
Equivalent of C# async main in F#,"<p>I was wondering what would be the equivalent of the C# async <code>main</code> in F#. More to the point, is there a special way of consuming/using async methods from <code>main</code> in an F# program or is it just a matter of waiting for completion?</p>

<p>To be more concrete, say we are using the .NET Core Generic Host. </p>

<p>In a C# program, <code>main</code> might look like this:</p>

<pre><code>class Program
{
    static async Task Main(string[] args)
    {
         await new HostBuilder().Build().RunAsync();
    }
}
</code></pre>

<p>In an F# program, my instinct would be to do something like this:</p>

<pre><code>[&lt;EntryPoint&gt;]
let main args =
    HostBuilder().Build.RunAsync().Wait()
</code></pre>

<p>...or...</p>

<pre><code>[&lt;EntryPoint&gt;]
let main args =
    HostBuilder().Build.RunAsync() |&gt; Async.AwaitTask |&gt; Async.RunSynchronously
</code></pre>

<p>...or...</p>

<pre><code>[&lt;EntryPoint&gt;]
let main args = 
    async {
        return HostBuilder().Build.RunAsync() |&gt; Async.AwaitTask
    } |&gt; Async.RunSynchronously
</code></pre>

<p>...or just avoid async...but that's no fun...</p>

<pre><code>[&lt;EntryPoint&gt;]
let main args =
    HostBuilder().Build.Run()
</code></pre>

<p>There are a few more formulations I could show but I think these make the point.</p>

<p>I imagine that part of the answer lies in answering these other questions</p>

<ol>
<li>""what does it mean to run an async main method"" and </li>
<li>""what's the point of making main async?""</li>
</ol>

<p>Going by examples, async <code>main</code> seems mostly to be about making it possible for other places to call <code>main</code> in an async way (in those cases where <code>main</code> is not really ""main"", ie. unit testing, etc). </p>

<p>In the case of F#, I imagine there are at least 2 things preventing one from just returning an Async computation from <code>main</code>:</p>

<ol>
<li>The EntryPointAttribute that enforces an int return type for status codes...right?</li>
<li>The compiler probably is not prepared to handle the async computation as the exit value of the program...right?</li>
</ol>
",https://stackoverflow.com/questions/55208939/equivalent-of-c-async-main-in-f,"['f#', 'async-await', 'f#-async']",1544,True,13,1
Jasmine/Jest type conflicts,"<p>I am relatively new here and would need some help.
Company I work for uses karma and jasmine for unit testing.
Now they would like to migrate some tests to jest.
I got a ticket assigned to me. We are using typescript btw...
I got jest installed, prefixed with .spec.jest.ts to separate jest test from karmas. And it works fine. Jest just picks up those files that are prefixed. But when i try to do some build things we do with our project I get the type declaration conflicts between jest and jasmine.
For example: node_modules/@types/jest/index.d.ts:32:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: beforeAll, beforeEach, afterAll, afterEach, describe, fdescribe, xdescribe, it, fit, xit, expect, clock, DEFAULT_TIMEOUT_INTERVAL, CustomMatcherFact
ory, CustomEqualityTester</p>

<p>I am aware that jest is build on top of jasmine but is there some kind of workaround, we want to migrate our tests gradually. One at a time.
Is there some kind of workaround to namespace the types for jest or something like that so no conflicts occur?</p>

<p>Tnx in advance for your help :)</p>

<p>I tried to google some workaround but nothing that would solve the issue came across.</p>
",https://stackoverflow.com/questions/58589383/jasmine-jest-type-conflicts,"['javascript', 'typescript', 'jasmine', 'jestjs', 'karma-jasmine']",1784,True,6,1
"Vue Unit Testing: How to test complex components with props, vuex store, watchers, getters etc","<p>I have a question about unit testing (Jest) within a vue app - I guess it is rather an architectural question, but maybe specific code examples could also help me out.</p>

<p>I have sketched out a more or less complex setup of vue components from my app. They are still simplified but I guess they should help to describe the situation.</p>

<p><a href=""https://i.stack.imgur.com/Tt21v.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Tt21v.png"" alt=""Vue Parent and Children components""></a>
<a href=""https://gofile.io/?c=jvtx0f"" rel=""nofollow noreferrer"">(PDF Attachment for those preferring non-pixel data :)</a></p>

<p>I have a <strong>Wrapper</strong> which has three child components:</p>

<ul>
<li><strong>Search</strong> (Input field to search on Map)   </li>
<li><strong>List</strong> (List of stores, represented also as markers on map)</li>
<li><strong>Map</strong> (Google Map itself)</li>
</ul>

<p>I would really like to write some unit tests for this, but it seems so super tedious to setup those tests, so that I doubt that this is the way to do it.</p>

<p>It starts with the way I load the google maps API: The wrapper loads it asynchronously, sets API key etc. As soon as the google map API is loaded it passes it down to the children.</p>

<p>Of course the map only really starts to load, create and display markers, as soon as <code>google</code> is present and I can use <code>new this.google.maps.Map()</code> for example.</p>

<p>Even if I would like to test some methods of the <strong>Map</strong> component, I have to provide an actual google object, because otherwise the whole init process in <code>mount()</code> fails. It can't make a map. </p>

<p><em>So do I have to load the actual google's map API in my tests? Or could I somehow skip mounting the map but still test a few isolated methods?</em></p>

<p>Further you can see that my <strong>Map</strong> watches a getter from the vuex store: Whenever the <code>searchCoordinates</code> set by <strong>Search</strong> change in my vuex store, I want to execute some functions (for example center my map to the new search coordinates or remove a current location marker if the search did not return valid searchCoordinates).</p>

<p><em>How could I somehow break down the interlinking between these components, but still write good and helpful tests, which help me to guarantee that the app does what it is supposed to do?</em></p>

<p>I know that I can use a vuex store within my tests (<a href=""https://medium.com/@lachlanmiller_52885/mocking-vuex-in-vue-unit-tests-b6eda1c4d301"" rel=""nofollow noreferrer"">Medium article about vuex testing</a>).
But still I feel like the whole app is so much inter-connected that doing actual <em>unit testing</em> – testing one small piece at a time – is impossible.
It seems like that I would have to mount not only <strong>Map</strong> alone, but also the other components and a vuex store with actual data, to really write bulletproof tests.</p>

<p><em>A few other examples, where I struggle:</em></p>

<ul>
<li>In my <code>mounted()</code> I subscribe to an action with <code>this.$store.subscribeAction((action) =&gt; {...</code> - of course $store is undefined in my tests. <a href=""https://lmiller1990.github.io/vue-testing-handbook/vuex-in-components.html#using-a-mock-store"" rel=""nofollow noreferrer"">Should I mock it</a>?</li>
<li>As I said I am watching a getter: This throws errors like <code>TypeError: Cannot use 'in' operator to search for 'searchCoordinates' in undefined</code>. Would I have to mock all the getters as well? If so: what remains to be tested? If I mock (~=leave away) all the vuex stuff, it seems to me, that testing becomes useless...</li>
</ul>

<p>But maybe I am mistaken here. Also I am quite new to unit testing, so any hints are very welcome.
Thank you very much in advance. I hope somebody has some valuable input.
All those examples (even in books like <a href=""https://www.oreilly.com/library/view/vuejs-up-and/9781491997239/"" rel=""nofollow noreferrer"">Vue.js - up and running</a>) are always broken down to very simple and understandable examples, but on the other hand don't really reflect real-life apps...</p>

<p>Cheers</p>

<p>----- Edit:</p>

<p>I got a <code>needs more focus</code> vote by someone.
So I try to sum up simple and small questions:</p>

<p><strong>Summary of Questions</strong></p>

<ol>
<li>Does somebody have a general input on how to test larger and more complex vue applications?</li>
<li>Is there a way to test a component with a google map (or a component that is relying heavily on any third party code)</li>
<li>Is mocking getters, store and actions a good idea in this case? (I have my doubts there).</li>
<li>For testing watched properties from the vuex store, I read <a href=""https://stackoverflow.com/questions/49431735/how-to-test-vue-watcher-that-watches-a-computed-property-from-vuex"">in this thread</a> that <code>mapState</code> should be mocked. (in my case probably my getters). Does this make sense to mocke those getters in my case?</li>
<li>Is it best practice to simplify as many things as possible in an tested component (for example, I started to override some methods, which failed (the one including google map initiation) to just get my test up and running:</li>
</ol>

<pre><code>const initMapMock = jest.fn();
const initMarkersMock = jest.fn();
...
const wrapper = shallowMount(Map, {
    methods: {
        initMap: initMapMock, // replace initMap(), which needs google map API
        initMarkers: initMarkersMock,
      },
    ...

</code></pre>

<p>Does that make sense?</p>
",https://stackoverflow.com/questions/58922748/vue-unit-testing-how-to-test-complex-components-with-props-vuex-store-watcher,"['unit-testing', 'vue.js', 'jestjs', 'vuex', 'vue-test-utils']",997,True,2,1
Why are my dependencies not replaced during my integration tests?,"<p>I have a Data Access project <code>DataAccess</code> with an Entity Framework Core <code>DbContext</code> defined:</p>

<pre><code>public class MyDbContext : DbContext
{
    public DbSet&lt;MyEntity&gt; MyEntities { get; set; }
}
</code></pre>

<hr>

<p>My web API project <code>Services</code> has a reference to <code>DataAccess</code> and the following in its <code>Startup.cs</code>:</p>

<pre><code>public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext&lt;DataAccess.MyDbContext&gt;(o =&gt; o.UseSqlServer(_configuration.GetConnectionString(""MyConnectionStringName"")));
}
</code></pre>

<p>(<code>_configuration</code> is an <code>IConfiguration</code> that is passed into the constructor of <code>Startup.cs</code> - not relevant to this discussion).</p>

<p>This project has a reference to <code>Microsoft.AspNetCore.App</code> which itself has a reference to <code>Microsoft.EntityFrameworkCore.SqlServer</code>.</p>

<hr>

<p>Then I have a separate unit testing project <code>ServiceTests</code> that has a reference to <code>Services</code>, as well as a reference to <code>Microsoft.EntityFrameworkCore.InMemory</code> so that I can swap-out the SQL Server provider for an in-memory one.</p>

<p>The following integration test is defined:</p>

<pre><code>public void MyIntegrationTest
{
    var server = new TestServer(new WebHostBuilder()
        .UseEnvironment(""Testing"")
        .UseStartup&lt;Services.Startup&gt;()
        .ConfigureTestServices(services =&gt;
        {
            services.AddDbContext&lt;DataAccess.MyDbContext&gt;(o =&gt; o.UseInMemoryDatabase(""TestDbName""));
        }));
    var dbContext = server.Host.Services.GetService&lt;DataAccess.MyDbContext&gt;();

    Assert.True(dbContext.MyEntities.Any(f =&gt; f.Bar == ""quux""));
}
</code></pre>

<hr>

<p>The problem is that this test blows up at <code>server.Host.Services.GetService&lt;DataAccess.MyDbContext&gt;()</code>, saying it cannot load <code>Microsoft.EntityFrameworkCore.SqlServer.dll</code>. This is strange to me because my expectation is that the registration of the in-memory database should override the one for the SQL Server database, so there should be no need to load anything specific to SQL Server.</p>

<p>And even if there was such a need, <code>ServiceTests</code> references <code>Service</code> which loads <code>Microsoft.EntityFrameworkCore.SqlServer.dll</code>, so I would expect that the latter would be transitively loaded if it was needed.</p>

<p>Can anyone advise as to where I'm going wrong? I've tried many suggestions, such as registering the test DbContext as a singleton, but nothing I've attempted is able to circumvent this problem.</p>
",https://stackoverflow.com/questions/57579349/why-are-my-dependencies-not-replaced-during-my-integration-tests,"['c#', 'asp.net-core', 'entity-framework-core']",199,False,3,0
How do I use Jasmine to test a Phaser 3 project?,"<p>I am currently developing a minigame in the phaser.js framework, and since the scope of the project is quite large, I really want to work with unit tests.
However when trying to setup unit tests in Jasmine for Phaser, I run into errors regarding dependencies.</p>

<p>I am not experienced with Jasmine or any other testing framework, so it could be I am overlooking something obvious to a experienced developer.</p>

<p>My .spec file looks like this:</p>

<pre><code>describe(""motorMain"", function() {
    var Phaser = require('../phaser');
    var MotorMain = require(""../motorMain""); 

    var motorMain;
    var phaser;

    beforeEach(function() {
        phaser = new Phaser();
        motorMain = new motorMain();
      });

    it(""should increase the score if a object is clicked"", function(){
        var scoreBeforeClicking = motorMain.score;
        var gameobject;
        motorMain.clickhandler("""",gameobject);
        expect(scoreBeforeClicking+1).toEqual(score);
    })
});
</code></pre>

<p>But since Phaser is reliant on running in a browser, when I run this it complains about not being able to access elements such as <code>window</code> and <code>document</code> in Phaser.</p>

<p>I get errors such as:</p>

<blockquote>
  <p>ReferenceError: document is not defined</p>
</blockquote>

<p>Does anyone have experience with testing Phaser games? I can't seem to find any information on it online. Is it even possible to test phaser games?</p>

<p>As for other testing frameworks, I also looked into nightwatch, but it's Phaser support is outdated, and it is mainly e2e instead of unit-testing, so it isn't what I am looking for. I also saw online that there was a shimming version of Phaser 2.4.7 developed by someone, but this is outdated now that so much has changed in Phaser 3.</p>
",https://stackoverflow.com/questions/55690117/how-do-i-use-jasmine-to-test-a-phaser-3-project,"['jasmine', 'phaser-framework']",728,True,3,1
AES decryption with PyCryptodome does not produce the expected result,"<p>I have some difficulties reproducing AES encryption and decryption in python. </p>

<p><strong>Context</strong>: A year ago, I created a small django based application using <a href=""https://github.com/ricmoo/aes-js"" rel=""nofollow noreferrer"">this javascript library</a> for <strong>client side encryption</strong>. Basically, some users' inputs are encrypted with a key and sent as hexadecimal strings to be stored. </p>

<p>For the illustration, I'll focus on <code>bd45bcccd0</code> (a.k.a '<em>Masha</em>' encrypted with john's key: <code>3ed8bd71327aafd855aac37921519767</code>)</p>

<h2>Encryption and decryption with the current js library</h2>

<ul>
<li><strong>encryption</strong> utf-8 -> bytes -> encrypted bytes -> hex</li>
<li><strong>decryption</strong> hex -> encrypted bytes -> bytes -> utf-8</li>
</ul>

<p><code>id_password</code> is a MD5 hash of the user's password. It is stored in the session storage and is used as a key</p>

<pre class=""lang-js prettyprint-override""><code>  function encrypt(t){
    var key = aesjs.utils.hex.toBytes(sessionStorage.getItem(""id_password""));
    var textBytes = aesjs.utils.utf8.toBytes(t);
    var aesCtr = new aesjs.ModeOfOperation.ctr(key);
    var encryptedBytes = aesCtr.encrypt(textBytes);
    var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
    return encryptedHex;
    }

  function decrypt(t){
    var key = aesjs.utils.hex.toBytes(sessionStorage.getItem(""id_password""));
    var textBytes = aesjs.utils.hex.toBytes(t);
    var aesCtr = new aesjs.ModeOfOperation.ctr(key);
    var decriptedBytes = aesCtr.decrypt(textBytes);
    var decrypted_utf8 = aesjs.utils.utf8.fromBytes(decriptedBytes);
    return decrypted_utf8;
    }
</code></pre>

<p>Once loaded in <code>key</code>, I get a 16 items array (So I guess a AES 128bits CTR is performed): </p>

<pre class=""lang-js prettyprint-override""><code>var key = aesjs.utils.hex.toBytes(sessionStorage.getItem(""id_password""));
console.log(key)
Array(16) [ 62, 216, 189, 113, 50, 122, 175, 216, 85, 170, … ]
</code></pre>

<p>With the current code, encryption and decryption work</p>

<h2>Python implementation</h2>

<p>For unit-testing purposes, I wanted to be able to decrypt. I am using <a href=""https://pycryptodome.readthedocs.io/en/latest/src/introduction.html"" rel=""nofollow noreferrer"">this library</a>. To mimic the client side as much as possible, I tried the following: </p>

<pre class=""lang-py prettyprint-override""><code>john_key = ""3ed8bd71327aafd855aac37921519767""
cipher = AES.new(codecs.decode(john_key,'hex_codec'), AES.MODE_CTR)
d = cipher.decrypt(codecs.decode('bd45bcccd0', 'hex_codec'))
d.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xac in position 0: invalid start byte
</code></pre>

<p>Here is the problem but I am not sure at which stage it occurs. Here is what I checked: </p>

<pre class=""lang-py prettyprint-override""><code># key's length is correct
k = codecs.decode(john_key,'hex_codec')
k
b'&gt;\xd8\xbdq2z\xaf\xd8U\xaa\xc3y!Q\x97g'
len(k)
16
# decoded message's length is correct
d = cipher.decrypt(codecs.decode('bd45bcccd0', 'hex_codec'))
len(d)
5
</code></pre>

<p>Since I can't rely on a library I can't reproduce the results, I wonder whether I misused PyCryptodome or whether the way this javascript library implements AES CTR encryption is reliable. Any insights? </p>
",https://stackoverflow.com/questions/59453751/aes-decryption-with-pycryptodome-does-not-produce-the-expected-result,"['javascript', 'python', 'encoding', 'cryptography', 'aes']",1719,True,2,1
How to fix &#39;java.lang.NoClassDefFoundError: org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversalSource$GraphTraversalSourceStub&#39;?,"<p>I am trying to initialize an in-memory graph using TinkerGraph. </p>

<p>Firstly, i have defined the bean in my context xml file and tried to initialise the TinkerGraph.</p>

<p>My intention is to unit test the classes that i have created for forming the gremlin queries, the end queries that i get from these classes are in the form of a string, so in order to execute them through the TinkerGraph, i have the used the approach given in the following post:
<a href=""https://stackoverflow.com/questions/50254378/get-gremlin-query-as-a-string-and-execute-it-in-java-without-submitting-it-to-th"">Get Gremlin query as a String and execute it in java without submitting it to the GremlinServer</a></p>

<p>I would also like to know whether the approach that i have taken is the preferred approach, for running the gremlin queries as part of the unit testing?</p>

<p>Following are the dependencies i have included in the pom.xml:</p>

<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;org.apache.tinkerpop&lt;/groupId&gt;
    &lt;artifactId&gt;tinkergraph-gremlin&lt;/artifactId&gt;
    &lt;version&gt;3.2.4&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
      &lt;groupId&gt;org.apache.tinkerpop&lt;/groupId&gt;
      &lt;artifactId&gt;gremlin-groovy&lt;/artifactId&gt;
      &lt;version&gt;3.0.2-incubating&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>

<p>EmbeddedGremlinQueryEngine is as follows:</p>

<pre><code>
import org.apache.tinkerpop.gremlin.driver.Result;
import org.apache.tinkerpop.gremlin.driver.ResultSet;
import org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.List;

public class UcsEmbeddedGremlinQueryEngine implements GremlinEngine{

    private static final Logger logger = LoggerFactory.getLogger(UcsEmbeddedGremlinQueryEngine.class);
    private GraphTraversalSource graphTraversalSource = null;
    private Graph graph = null;
    private ScriptEngine engine = null;
    private Bindings bindings = null;

    public UcsEmbeddedGremlinQueryEngine() {
        graph = TinkerGraph.open();
        graphTraversalSource = graph.traversal();
        engine = new GremlinGroovyScriptEngine();
        bindings = engine.createBindings();
        bindings.put(""g"", graphTraversalSource);
    }

    public void shutdown() throws Exception {
        if (graph != null){
            graph.close();
        }
        logger.info(""TinkerGraph shutdown complete."");
    }

    @Override
    public List&lt;Result&gt; query(String query) {
        List&lt;Result&gt; res = null;
        try {
            ResultSet results = (ResultSet) engine.eval(query, bindings);
            res = results.all().join();

            for (Result r : res) {
                System.out.println(""result: "" + r + '\n');
            }

        } catch (ScriptException e) {
            e.printStackTrace();
        }
        return res;
    }

    // This function reads the initScript and run them as gremlin queries.
    public synchronized void initialize() {
        logger.debug(""Initializing embedded TinkerGraph. This will only take a few seconds...."");
        //TODO include the execution of queries as part of initialisation
    }
}
</code></pre>

<p>Stack trace is as follows:</p>

<pre><code>java.lang.NoClassDefFoundError: org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversalSource$GraphTraversalSourceStub
    at org.apache.tinkerpop.gremlin.groovy.loaders.StepLoader.load(StepLoader.groovy:54)
    at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:236)
    at org.apache.tinkerpop.gremlin.groovy.loaders.GremlinLoader.load(GremlinLoader.groovy:28)
    at org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.&lt;init&gt;(GremlinGroovyScriptEngine.java:189)
    at org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.&lt;init&gt;(GremlinGroovyScriptEngine.java:172)
    at com.intuit.gro.mcsdata.gemlinengine.UcsEmbeddedGremlinQueryEngine.&lt;init&gt;(UcsEmbeddedGremlinQueryEngine.java:28)
</code></pre>

<p>EmbeddedGremlinQueryEngine is defined as a bean in the xml file, when the bean is loaded i get the error as 
Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversalSource$GraphTraversalSourceStub</p>

<p>I don't understand how the GraphTraversalSourceStub comes into picture during initialization, I was not able to find any information about it. 
Any help would be appreciated.</p>
",https://stackoverflow.com/questions/56524089/how-to-fix-java-lang-noclassdeffounderror-org-apache-tinkerpop-gremlin-process,"['spring', 'gremlin', 'tinkergraph']",2651,True,2,2
Sinon spies not triggered after await - why? [Vue Unit Test],"<p>I'm new to Vue and Vue unit testing in general, so please bear with me. :)</p>

<p>I need to test that two VueX actions are dispatched from the created() hook on a specific component creation. The first dispatch triggers its Sinon spy, but the second will not. No spies will function after the first await statement. </p>

<p>It's probably important to note that the code itself functions correctly and does what is expected. It's only the unit test that is failing. </p>

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

<pre><code>async created() {
  await this.$store.dispatch(GET_A)
  await this.$store.dispatch(GET_B)

  // Do a bunch of other things after.
}
</code></pre>

<p>This is the unit test (using Chai &amp; Mocha):</p>

<pre><code>// Bunch of other things happen here, like setting up localVue, etc.

describe('TestPage.vue', () =&gt; {
  let actions
  let getters
  let store
  let router

  beforeEach(() =&gt; {
    actions = {
      GET_A: sinon.stub(),
      GET_B: sinon.stub(),
    }

    store = new Vuex.Store({
      actions,
      getters
    })

    router = new VueRouter()
  })

  it('created() should trigger the action GET_B.', () =&gt; {
    const wrapper = shallowMount(TestPage, {
      store,
      localVue,
      router,
      attachToDocument: true
    })

    expect(actions.GET_B.called).to.be.equal(true)
  })
})
</code></pre>

<p>If I swap the order of the two dispatch methods in the created() hook, the test will pass, because GET_B is first. However, then the unit test for GET_A will fail. </p>

<p>I was thinking it could be something along the lines of the stubbed actions are not returning a promise, causing the test to pause at await until it times out.</p>

<p>I've made many attempts at finding a similar issue that others have had, and this was the closest I could get: <a href=""https://github.com/sinonjs/sinon/issues/1735"" rel=""nofollow noreferrer"">https://github.com/sinonjs/sinon/issues/1735</a></p>

<p>That said from what I understand his solution at that link can't be applied here.</p>

<p>I'd be very grateful for any suggestions as to what I can do to fix this!</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/55557986/sinon-spies-not-triggered-after-await-why-vue-unit-test,"['javascript', 'vue.js', 'sinon']",127,False,1,0
Jasmine - Can&#39;t access shadowRoot of custom web component,"<p>I've recently been trying to use jasmine for some unit testing of a custom web component that utilises the shadow dom.
The component takes in a text property and passes it to a child element to use as its text content, I'm trying to verify that the textContent is what it should be.</p>

<p>Every time I try to access the <code>shadowRoot</code> of my component, to then access its children, it simply returns null.</p>

<p>I've simplified some names but the code is the same.</p>

<p>Component:</p>

<pre><code>@Component({
    tag: 'my-button',
    styleUrl: 'my-button.css',
    shadow: true,
})
export class MyButton {
    @Prop() text: string;
    @Prop() iconName: string;
    @Prop() url: string;

    render() {
        return (
            &lt;div class=""button-outer""&gt;
                &lt;ion-button class=""button"" expand=""block"" href={this.url}&gt;
                    &lt;holo-icon class=""button-icon"" slotName=""icon-only"" iconName={this.iconName} /&gt;
                    &lt;p class=""button-label""&gt;{this.text}&lt;/p&gt;
                &lt;/ion-button&gt;
            &lt;/div&gt;
        );
    }
}
</code></pre>

<p>HTML:</p>

<pre><code>&lt;my-button
    text=""Test""
    icon-name=""assets/svg/test-icon.svg""
    url=""/test""
&gt;&lt;/my-button&gt;
</code></pre>

<p>Test: (TestBed is setup as normal - async)</p>

<pre><code>describe('has the expected html tags', () =&gt; {
    let buttons;

    beforeEach(() =&gt; {
        button = page.querySelector('my-button');
    });

    it('has text ""Test""', () =&gt; {
        const label = button.shadowRoot.querySelector('div &gt; ion-button &gt; p');
        expect(label.textContent).toBe('Test');
    });
}
</code></pre>

<p>Karma Result:
<code>TypeError: Cannot read property 'querySelector' of null</code></p>

<p>The web component was developed in a separate project and imported in as an npm package, if that makes any difference?</p>

<p>I can create an element in the test, and attach a shadow root to it, and I can access and read its contents fine, just not actual elements that belong to the external page component I'm testing.
It's really blocking me on other tests that use the shadow dom too. All I can find is answers suggesting <code>fixture.detectChanges()</code> but that doesn't seem to do anything.</p>

<p>Has anyone come across this or has a workaround or anything? Would be greatly appreciated :)</p>

<p><strong>EDIT</strong></p>

<p>I would just query the <code>text</code> attribute of my component if I knew how to preserve it, but it just gets replaced by <code>_ngcontent-c##=""""</code></p>
",https://stackoverflow.com/questions/54237573/jasmine-cant-access-shadowroot-of-custom-web-component,"['angular', 'typescript', 'ionic-framework', 'jasmine', 'karma-jasmine']",1502,False,8,0
How to Unit Test a C++/WinRT Component? Preferably with Code Coverage,"<p>I'm in the process of writing some new C++/WinRT based components in order to replace some much older C++/CX code.  The goal is to be able to use third-party C++ tools that don't understand CX (static code analyzers, etc).</p>

<p>However the first step in the journey is to ensure I can properly unit test my own code.  Unit testing C++/CX code typically used the ""C++ Unit Test App"" project type, which is C++/CX based and has its own issues (lack of code coverage support, run all required before tests show up in the explorer, stability, etc)</p>

<p>Browsing through the available project types in Visual Studio 2017, I did not see a unit test project template for C++/WinRT based projects.  Is my only option to use the ""C++ Unit Test App"" template with all its failings, or is there another way to build tests for a C++/WinRT library?</p>

<p>Perhaps there is a way to configure either the ""Native Unit Test Project"" or ""Google Test"" project templates to support what I'm looking for?</p>

<p>Ideally what I'm looking for is something that doesn't require launching a UI, is pure C++(/WinRT), and supports Visual Studio's Code Coverage Analysis.</p>
",https://stackoverflow.com/questions/54700557/how-to-unit-test-a-c-winrt-component-preferably-with-code-coverage,"['visual-c++', 'visual-studio-2017', 'c++-winrt']",1127,True,1,2
&quot;Cannot access disposed object&quot; Error on VS SQL Unit Testing Project,"<p>I have been working on a SQL Server (SSDT) solution on VS 2017, which includes SQL unit test projects that were created by right clicking on items on the SQL project and selecting ""Create Unit Tests..."".</p>

<p>I configure the connections by right clicking on the unit testing projects and selecting ""SQL Server Test Configuration..."", which opens a popup to define which database the tests will run in.</p>

<p>I opened this solution on my second laptop for the first time and realised that when I click on ""SQL Server Test Configuration..."" I get an error that says: ""Cannot access a disposed object. Object name: 'ComboBox'""</p>

<p>I could not find anything related to my situation online, most of which seems to relate to .NET code, whereas I'm struggling with the VS interface. I tried uninstalling and re-installing VS 2017 (15.9.9), created a brand new SQL project and a corresponding unit test. Problem persists.</p>

<p>The problem does not exist in my other laptop and a VM I'm using. My second laptop has a lot more legacy things installed but I need to use it because its specs are much higher and has a SQL server on it.</p>

<p>Any ideas as to what I can try?</p>
",https://stackoverflow.com/questions/55160595/cannot-access-disposed-object-error-on-vs-sql-unit-testing-project,"['visual-studio-2017', 'sql-server-data-tools', 'sql-server-unit-testing']",765,True,1,1
Correct way of writing tests for React,"<p>So I just stambled upon this issue. I would like to ask about the best way of solving this issue. This is relevant part of my <code>App.js</code> code:</p>

<pre><code>addTask = (text) =&gt; {
    const {tasks} = this.state;
    tasks.push({text});
    this.setState({tasks});
};

&lt;AddTaskConfirmBtn
    text={
        this.state.newTaskValue // This is just a simple state string
    }
    addTask={
        this.addTask
    }/&gt;
</code></pre>

<p><code>AddTask</code> test</p>

<pre><code>it('should addTask', function () {
    wrapper
        .instance()
        .addTask('testing');
    expect(
        wrapper
            .state('tasks')
    ).toEqual([
        {text: 'make todo with hooks'},
        {text: 'write tests'},
        {text: 'do the daily'},
        {text: 'testing'},
    ])
});
</code></pre>

<p><code>AddTaskConfirmBtn</code> code:</p>

<pre><code>render() {
    return (
        &lt;button
            onClick={
                    this.props
                        .addTask // This is the issue. This adds an object to the array. It is solved below
            }&gt;
            Add task
        &lt;/button&gt;
    );
}
</code></pre>

<p>// just for reference. This is the way I solved the problem</p>

<pre><code>render() {
    return (
        &lt;button
            onClick={
                () =&gt; {
                    this.props
                        .addTask(this.props.text)
                }
            }&gt;
            Add task
        &lt;/button&gt;
    );
}
</code></pre>

<p>And here is my test:</p>

<pre><code>describe('&lt;AddTaskConfirmBtn/&gt;',
    function () {
        let wrapper;
        let addTaskMock = jest.fn();
        beforeEach(
            function () {
                wrapper = shallow(
                    &lt;AddTaskConfirmBtn addTask={addTaskMock}/&gt;
                );
            }
        );
        it('should addTaskToTasks onClick',
            function () {
                wrapper
                    .find('button')
                    .simulate('click');
                expect(addTaskMock).toHaveBeenCalledTimes(1);
            }
        );
    }
)
</code></pre>

<p>First of all I am in the process of learning Unit testing and TDD, so please be gentle with my stupidity. </p>

<p>Now to my issue. I was testing my code the way seen above. So adding the correct value and pushing it to the state, and comparing. The AddTaskConfirmBtn was just checking if the method was called.</p>

<p>But I just realized there is an error I didn't account for with my testing. I was pushing the wrong thing into the array (I believe it was the event object I was pushing into the state). I fixed it, but the interesting thing was the tests didn't catch it. Obviously because I didn't write them this way.</p>

<p>So my question is, should I worry about it? Should I account for situations like this in my tests? Or is it just something that happens? Or maybe I should put safeguards in the method itself? Like</p>

<pre><code>addTask = (text) =&gt; {
    if (typeof text !== ""string"") {
        console.log(""text is not a string"", text);
        return null;
    }
    const {tasks} = this.state;
    tasks.push({text});
    this.setState({tasks});
};
</code></pre>

<p>How should it be done in the best way possible?</p>
",https://stackoverflow.com/questions/57361004/correct-way-of-writing-tests-for-react,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",48,True,1,1
How to mock a @ViewChild MatTabGroup in jest?,"<p>I'm trying to test a new piece of code I added to my project. It allows users to select a tab on a page and when they refresh, the page is loaded on the same tab. I'm using localstorage to do this. </p>

<p>The issue I'm having is in the tests where it cannot set <code>selectedIndex</code> of <code>undefined</code>.</p>

<p>In the html on the mat-tab I have an event handler (<code>selectedTabChange</code>):</p>

<pre><code>&lt;mat-tab-group
  [selectedIndex]=""selectedTab.value""
  (selectedIndexChange)=""selectedTab.setValue($event)""
  (selectedTabChange)=""handleMatTabChange($event)""
&gt;
  &lt;mat-tab label=""Tab 1""&gt;
    &lt;div *ngIf=""selectedTab.value === 0""&gt; ... &lt;/div&gt;
  &lt;/mat-tab&gt;

  &lt;mat-tab label=""Tab 2""&gt;
    &lt;div *ngIf=""selectedTab.value === 1""&gt; ... &lt;/div&gt;
  &lt;/mat-tab&gt;

  &lt;mat-tab label=""Tab 3""&gt;
    &lt;div *ngIf=""selectedTab.value === 2""&gt; ... &lt;/div&gt;
  &lt;/mat-tab&gt;

&lt;/mat-tab-group&gt;
</code></pre>

<p>In the component I have </p>

<pre><code>@ViewChild(MatTabGroup) tabGroup: MatTabGroup;


ngAfterViewInit() {
  const index = Number(localStorage.getItem('userTabLocation')) || 0;
  this.tabGroup.selectedIndex = index;
}

handleMatTabChange(event: MatTabChangeEvent) {
  localStorage.setItem('userTabLocation', String(event.index));
}
</code></pre>

<p>Tests:</p>

<p>Checking if ViewChild is defined but it's <code>undefined</code>.</p>

<pre><code>it('Should have `ViewChild` variable defined', () =&gt; {
  expect(component.tabGroup).toBeDefined();
});
</code></pre>

<p>Also in some of my other tests I get:</p>

<pre><code>TypeError: Cannot set property 'selectedIndex' of undefined

   99 |   }
  100 | 
&gt; 101 |   ngAfterViewInit() {
      |   ^
  102 |     const index = Number(localStorage.getItem('userTabLocation')) || 0;
  103 |     this.tabGroup.selectedIndex = index;
</code></pre>

<p>Things I have tried:</p>

<ol>
<li>I read this really helpful article <a href=""https://blog.angularindepth.com/angular-unit-testing-viewchild-4525e0c7b756"" rel=""nofollow noreferrer"">https://blog.angularindepth.com/angular-unit-testing-viewchild-4525e0c7b756</a></li>
<li><p>Since my view child is a MatTabGroup, I've no idea how to stub that so the above article didn't help much. I tried this but that broke even more tests:</p>

<pre><code>component.tabGroup = TestBed.createComponent(MatTabGroup).componentInstance as MatTabGroup;
</code></pre></li>
<li><p>I have added the MatTabGroup into the providers like so, which didn't help:</p>

<pre><code>TestBed.configureTestingModule({
      imports: [ ... ],
      declarations: [ ... ],
      providers: [
      {
         provide: MatTabGroup,
      }],
}).compileComponents();
</code></pre></li>
<li><p>I have added the useValues into the providers with the matTabGroup like so, which also didn't help:</p>

<pre><code>TestBed.configureTestingModule({
      imports: [ ... ],
      declarations: [ ... ],
      providers: [
      {
         provide: MatTabGroup,
         useValues: {
            selectedIndex: 0,
         }
      }],
}).compileComponents();
</code></pre></li>
<li><p>I have added the <code>MatTabsModule</code> into the imports, also no luck:</p>

<pre><code>TestBed.configureTestingModule({
      imports: [ MatTabsModule ],
      declarations: [ ... ],
}).compileComponents();
</code></pre>

<p>But that gives the following error:</p>

<pre><code>Template parse errors:
More than one component matched on this element.
Make sure that only one component's selector can match a given element.
Conflicting components: MatTab,MatTab (""
</code></pre>

<p>(EDIT): This was happening because I was importing <code>MaterialModule</code> too.</p></li>
</ol>

<p>Any ideas? Really stuck on this. </p>

<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/55514142/how-to-mock-a-viewchild-mattabgroup-in-jest,"['javascript', 'angular', 'typescript', 'jestjs']",1914,False,1,0
Loading and persisting an In-Memory SQLite database with EF Core,"<p>I'm doing some research for a new project and I'm trying to determine if it's possible (and advisable) to load a SQLite database into memory, perform CRUD operations against it, and persist it back out.  </p>

<p>I've seen many examples of utilizing SQLite databases (in memory) for unit testing, and in all of those examples, the data is just trashed in the end - this is NOT what I wish to do.</p>

<p>I'm going to likely use Microsoft SQL Server to manage the overall site data and act as a storage engine (users and credentials and their associated SQLite databases, etc).  </p>

<p>When a user selects a SQLite database in the UI, I would like to load it into memory on the server, allow the user to operate against it, and then persist it back to the storage engine (SQL Server) without needing to save a .db file to the filesystem.</p>

<p>I'm comfortable with aspects of EF Core + SQL Server and SQLite (against the filesystem).  But what's new to me is the idea of operating against a SQLite database in memory.</p>

<p>So my questions are:</p>

<ul>
<li>Is this possible with EF Core?</li>
<li>If so, how would I configure my SQLite <code>DbContext</code> class to accomplish this?</li>
<li>Are there any major downsides to this?</li>
</ul>

<p>Thank you</p>
",https://stackoverflow.com/questions/58862690/loading-and-persisting-an-in-memory-sqlite-database-with-ef-core,"['c#', 'entity-framework', 'sqlite', '.net-core', 'ef-core-3.0']",2128,True,1,1
Unit testing WinForms forms,"<p>In unit testing .net winforms, we're coming across the need to manipulate and verify the state of various form controls, as well as to fire events on those controls. The problem is that the controls are private by default on the form, and the test method can't get at them.</p>

<p>So far, we've resorted to using magic strings to get the controls via reflection. This works, but it's brittle. Tests will break if the control name changes.</p>

<p>Changing all the controls to internal works, but it's a bit of a pain in that we have to remember to do it for each and every control we might want to access in a test.</p>

<p>I thought maybe I might use expression trees to get around the ""privateness"" of the control, but nothing obvious comes to mind as to how to go about building such code.</p>

<p>There's also the problem of raising events. So far, we're magic strings to hold event names, then using reflection to locate the <em>OnXXX</em> method and invoking it, but again, we'd like to do away with that.</p>

<p>Is there a way to use expression trees (or any other semantics or mechanisms) to access private controls, in order to manipulate or verify their state and fire their events?</p>
",https://stackoverflow.com/questions/58612047/unit-testing-winforms-forms,"['c#', 'unit-testing', 'events', 'reflection', 'expression-trees']",73,False,0,0
"How do I run tests built using VisualStudio, via CMake/CTest/Catch2 from the CLI?","<p>I'm trying to learn several things at once (arguably my first problem...), namely: unit testing with Catch2 and building with CMake.</p>

<p>In the course of my investigations, CTest appeared on the radar as a pre-baked way of managing tests within CMake, and seems to 'support' Catch2.</p>

<p>While things seem to build okay, I can't run my tests as automatically as I'd hope.  </p>

<p>Specifically, I have a source tree, which at some point contains the library I'm testing, and I'd like to be able to sit at the top of the tree and execute some sort of 'run my tests' command (and ideally run them as part of the full build, but that's for another day).</p>

<p>So here's my CMakeLists.txt file (<code>L:\scratch\shared\testeroolib\CMakeLists.txt</code>) for the library of interest:</p>

<pre><code>cmake_minimum_required(VERSION 3.5)
project(testeroolib)

add_library(${PROJECT_NAME} STATIC src/testeroolib.cpp)
target_include_directories(${PROJECT_NAME} PUBLIC include)

set(PROJECT_TEST ${PROJECT_NAME}_test)

add_executable(${PROJECT_TEST} test/catch2_main.cpp)
target_link_libraries(${PROJECT_TEST} PRIVATE Catch)
target_link_libraries(${PROJECT_TEST} PRIVATE ${PROJECT_NAME})

enable_testing()
add_test(NAME TesterooLibTest COMMAND ${PROJECT_TEST})
</code></pre>

<p>If I do the naive thing and run ctest from the same location I run cmake, I get:</p>

<pre><code>L:\scratch&gt;ctest
*********************************
No test configuration file found!
*********************************
...
</code></pre>

<p>or</p>

<pre><code>L:\scratch&gt;ctest .
Test project L:/scratch
No tests were found!!!
</code></pre>

<p>From what I've read elsewhere, <code>make test</code> would do the trick with GCC and friends, but I'm using VS.  </p>

<p>So here, the advice seems to be that I should use a build target of <code>ALL_TESTS</code> but that doesn't do the trick for me.</p>

<pre><code>L:\scratch&gt;cmake --build BUILD --target ALL_TESTS
...
MSBUILD : error MSB1009: Project file does not exist.
Switch: ALL_TESTS.vcxproj
</code></pre>

<p>Of course, I <em>can</em> just run the test:</p>

<pre><code>L:\scratch&gt;BUILD\shared\testeroolib\Debug\testeroolib_test.exe
===============================================================================
All tests passed (1 assertion in 1 test case)
</code></pre>

<p>I'm hoping I've made some tiny snafu, but there is every chance I've got completely the wrong end of the stick here!</p>
",https://stackoverflow.com/questions/57892275/how-do-i-run-tests-built-using-visualstudio-via-cmake-ctest-catch2-from-the-cli,"['visual-studio', 'cmake', 'ctest', 'catch2']",2705,True,0,2
Testing Angular component without referencing other nested components,"<p><em>I won't be including too much code as it would make it too complication to understand</em></p>

<p>I am new to Angular and totally new to the unit testing framework <code>Jasmine</code>. So, in my Angular app, i have a component, <code>Test-Table-component</code>, which uses/references Angular's <em>Material Table</em>, which requires it to reference <code>MatDialogRef, MatDialogModule</code> etc. etc.</p>

<p>The component also uses <code>HttpClient</code> as it makes REST calls to our WebAPI. </p>

<p>Anyways, i guess it's time to curse <code>Jasmine</code> now. So, firstly, i create a test file to test my component : <code>test-table.component.spec.ts</code>. I followed the docs and some tuts and finally ended up with some code. Before i include the code, let me explain the issue. As my <code>Test-table</code> component relies on other components/dependencies, i am needing to reference each and every single one of them to the testing class, which seems like a huge work. I tried to apply the <code>No_Errors_Schema</code> trick, but then i end up with tons of other exceptions, which again requires me to reference all the other dependencies, which, again, leads to other errors. </p>

<p>So this is what i have now :</p>

<pre><code> describe('TestTableComponent',  async() =&gt; 
{
const mockDialogRef = {
    close: jasmine.createSpy('close')
};
let component: TestTableComponent;
let fixture: ComponentFixture&lt;TestTableComponent&gt;;
let de: DebugElement;


beforeEach(async(() =&gt; 
{
    TestBed.configureTestingModule({declarations:[TestTableComponent],
        imports: [ReactiveFormsModule, MatTableModule, FormsModule, HttpClientModule],
        schemas: [NO_ERRORS_SCHEMA], providers: [{
            provide: MatDialogRef,
            useValue: mockDialogRef
        }]
    }).compileComponents();
}));
beforeEach(() =&gt;
{

    fixture = TestBed.createComponent(TestTableComponent);
    component = fixture.componentInstance;

    de = fixture.debugElement;
})


it('should check if data is returned by the API', async(() =&gt;{
    fixture.detectChanges();
    const result = component.GetEmployees();
    fixture.whenStable().then(()=&gt;{
    expect(result).toBeDefined();
    })
}))
});
</code></pre>

<p>which now throws :</p>

<blockquote>
  <p>StaticInjectorError(Platform: core)[TestTableComponent -> MatDialog]: 
      NullInjectorError: No provider for MatDialog!</p>
</blockquote>

<p>So finally, how can i test ONLY the <code>GetEmployees()</code> function, without having to reference all these other dependencies ?</p>
",https://stackoverflow.com/questions/57390602/testing-angular-component-without-referencing-other-nested-components,"['angular', 'jasmine']",285,False,0,1
groupby() is not binning the columns and DataFrame original column gets deleted when using .allias,"<p>I am new to spark(2.x.x) using spark-sql , I created a dataframe using spark sql context.</p>

<pre><code>dff = sqlCtx.read.format(""com.databricks.spark.csv"").option(""header"", ""true"").option(""inferSchema"",""true"").option(""delimiter"",""\t"").load(""/home/hduser/Desktop/allFromDesktop/pyspark/creditData.csv"")

dff.show()

Income|Limit|Rating|Cards|Age|Education|Gender|Student|Married|       Ethnicity|Balance|Age_class|
+---+------------------+-----+------+-----+---+---------+------+-------+-------+----------------+-------+---------+
|  0|14.890999999999998| 3606|   283|    2| 34|       11|  Male|     No|    Yes|       Caucasian|    333|    25-34|
|  1|           106.025| 6645|   483|    3| 82|       15|Female|    Yes|    Yes|           Asian|    903|      65+|
|  2|104.59299999999999| 7075|   514|    4| 71|       11|  Male|     No|     No|           Asian|    580|      65+|
</code></pre>

<p>i tried unit testing the code</p>

<pre><code>tab=dff.select(['Age_class','Balance','Limit']).groupby('Age_class').agg
  (F.count('Limit')  ,F.mean('Limit').alias('Limit_avg'),F.min('Limit').alias('Limit_min'),F.max('Limit').alias('Limit_max')).withColumn('total',sum(col('Limit')).
  over(Window)).withColumn('Percent',col('Limit')*100/col('total')).drop(c
  ol('total'))
  tab.show()
</code></pre>

<p>and found that as soon as agg(),count function executes the original column gets replaced by new .allias column names 
unit test #1 (first part of the python code executed succesfully)</p>

<pre><code>tab=dff.select(['Age_class','Balance','Limit']).groupby('Age_class').agg(F.count('Limit_count')
    ,F.mean('Limit').alias('Limit_avg'),
    F.min('Limit').alias('Limit_min'),
    F.max('Limit').alias('Limit_max'))
    tab.show()
</code></pre>

<p>With output:</p>

<pre><code>output:
---------+------------+------------------+---------+---------+
|Age_class|count(Limit)|         Limit_avg|Limit_min|Limit_max|
+---------+------------+------------------+---------+---------+
|    45-54|          65| 4836.630769230769|      855|    11200|
|      &lt;25|          11|3932.6363636363635|     2120|     6375|
|    55-64|          68|            4530.0|     1311|    11966|
##Here you can see i lost my original 'Limit' column ##
</code></pre>

<p>Original Dataframe which  has a column 'Limit' got deleted (why??) replaced by new column i.e i loose my original dataframe column  when <em>second part</em> of the code runs it is unable to find original column in the dataframe .
soo..
Rest of the part of the statment i.e *.withColumn('total',sum(col('Limit')).
   over(Window)).withColumn('Percent',col('Limit')<em>100/col('total')).drop(col('total'))</em></p>

<p>Shows the error :</p>

<pre><code>Py4JJavaError: An error occurred while calling o2104.withColumn.
: org.apache.spark.sql.AnalysisException: cannot resolve '`Limit`' given input columns: [Age_class, Limit_max, Limit_min, Limit_avg, count(Limit)];;
</code></pre>

<p>Now when i changed my groupby clause to -->>.groupby('Age_class','Limit') insted of .groupby('Age_class') my code gets executed with desired result ** 
<strong>QUESTION 1: Why i need to add ""Limit"" column to groupby() clause ?? When i alredy mentioned it in SELECT statement
QUESTION 2:After execution the ""Age_class"" column did not get converted to groups(bins) even though iam using ""groupby""  see expected  result table below i was expecting some thing like  ??</strong></p>

<pre><code>+---------+----------+------------------+----------+----------+-------+
|age_class|Limit|count(Limit)|Limit_avg|Limit_min|Limit_max|Percentage
+---------+----------+------------------+----------+----------+-------+
|
  45-54     |120|3183.0666666666666|338|12612|12.0||
  &lt;25       |150| 2970.733333333333|276|15672|15.0||
  55-64     |56| 3493.660714285714|385|15945|5.6||
  35-44     |254| 3403.771653543307|250|15857|25.4||
  25-34     |397| 3298.823677581864|343|18424|39.7||
  65+       |23|3210.1739130434785|571|14896|2.3|
+---------+----------+------------------+----------+----------+-------+
tab=dff.select(['Age_class','Balance','Limit']).groupby('Age_class','Limit').agg(F.count('Limit')
,F.mean('Limit').alias('Limit_avg'),
F.min('Limit').alias('Limit_min'),
F.max('Limit').alias('Limit_max')).withColumn('total',sum(col('Limit')).over(Window)).withColumn('Percent',col('Limit')*100/col('total')).drop(col('total'))
tab.show()
</code></pre>

<p>Actual output('Age_class' Not converted into groups(a.k.a bins)):</p>

<pre><code>+---------+-----+------------+---------+---------+---------+-------------------+
|Age_class|Limit|count(Limit)|Limit_avg|Limit_min|Limit_max|            Percent|
+---------+-----+------------+---------+---------+---------+-------------------+
|    45-54| 7838|           1|   7838.0|     7838|     7838| 0.4137807247233719|
|    35-44|  886|           1|    886.0|      886|      886|0.04677337612974069|
|    45-54| 4632|           1|   4632.0|     4632|     4632|  0.244530788073317|
|    55-64| 1448|           1|   1448.0|     1448|     1448|0.07644226708336853|
|    55-64| 5107|           1|   5107.0|     5107|     5107| 0.2696068080074331|
|    45-54| 2586|           1|   2586.0|     2586|     2586| 0.1365191316834192|
|    35-44| 4159|           1|   4159.0|     4159|     4159| 0.2195603513810288|
|    45-54| 4943|           1|   4943.0|     4943|     4943| 0.2609489821775488|
|    45-54| 2558|           1|   2558.0|     2558|     2558|0.13504096629782922|
|    25-34| 3969|           1|   3969.0|     3969|     3969|0.20952994340738237|
|    35-44| 5319|           1|   5319.0|     5319|     5319| 0.2807986316411859|
|    45-54| 8100|           1|   8100.0|     8100|     8100| 0.4276121294028212|
|    45-54| 6040|           1|   6040.0|     6040|     6040| 0.3188613903201284|
|    45-54| 4673|           1|   4673.0|     4673|     4673|0.24669524453078806|
|      65+| 2330|           1|   2330.0|     2330|     2330| 0.1230044767294535|
|    45-54| 6922|           1|   6922.0|     6922|     6922| 0.3654235999662134|
|      65+| 4263|           1|   4263.0|     4263|     4263|0.22505067995607736|
|    25-34| 4391|           1|   4391.0|     4391|     4391|0.23180800743306024|
|      65+| 7499|           1|   7499.0|     7499|     7499|0.39588436523355014|
|    45-54| 8732|           1|   8732.0|     8732|     8732|  0.460976433820424|
+---------+-----+------------+---------+---------+---------+-------------------+
</code></pre>
",https://stackoverflow.com/questions/56156756/groupby-is-not-binning-the-columns-and-dataframe-original-column-gets-deleted,"['apache-spark', 'dataframe', 'apache-spark-sql']",532,True,-4,1
AWS getting generic clients,"<p>I've been building a Lambda function in AWS that makes use of the following items, S3, SQS, SNS and KMS. While switching between unit tests and actual lambda tests I have written a generic method to return the IAmazonService interface, that interface is like the below</p>

<pre><code>public static T GetAmazonClient&lt;T&gt;(ILambdaContext context) where T : IAmazonService, new()
{
    T client = default(T);
    try
    {    
        if (context.GetType() == typeof(TestLambdaContext))
        {
            Console.WriteLine(""I am a unit test and I will have to build a profile"");
            //Build the profile for my unit test
            client = ClientObjectIhaveBuilt;
        }
        else
        {
            Console.WriteLine(""I am a Lambda instance and I should inherit my credentials"");
            client = (T)Activator.CreateInstance(typeof(T));
        }
    }
    catch (Exception ex)
    {
        //Some logging happens here with the exception
    }
    Console.WriteLine(JsonConvert.SerializeObject(client));
    return client;
}
</code></pre>

<p>Then in my code I can do something like this</p>

<pre><code>using (var sqsClient = AmazonClientHelper.GetAmazonClient&lt;AmazonSQSClient&gt;(context))
{
    var request = new ChangeMessageVisibilityRequest(SQSURL, message.ReceiptHandle, timeout);
    Console.WriteLine(""Extending Visibility of SQS Entry"");
    var response = await sqsClient.ChangeMessageVisibilityAsync(request);
}
</code></pre>

<p>In Unit Testing this has worked absolutely fine, I am able to retrieve messages, read from S3 and everything else I wish to do, but when hosted in AWS the Lambda doesn't seem to be creating the right client accounts. </p>

<p>I have hosted this in my own testing AWS account and had it work end to end fine, but when uploading it to my company account I find that the client objects created do not instantiate correctly, the client object output in the JSON serialiser at the end is blank object with no service URL or credentials (this may be correct but looks suspect)</p>

<p>Our clients break down at the first hurdle when we try to extend visibility on our SQS items; The client tries to extend visibility but we encounter an operation cancelled request.</p>

<p>NB: Sit tight, I'm trying to get a copy of the stacktrace and serialised client output</p>
",https://stackoverflow.com/questions/54634570/aws-getting-generic-clients,"['c#', 'amazon-web-services', '.net-core', 'aws-lambda']",136,True,0,1
Why are my Karma unit tests throwing an error for missing value accessors in components that do not have any forms?,"<p>I am setting up unit testing for our Ionic4 uni project (getting online help and research is an expected part of the project) and am having issues getting all the ""create component"" tests to pass in Karma. I have not written any tests myself, so am only trying to sort out all the errors thrown by the auto-generated ones. </p>

<p>The problem is that some components are throwing the following error: ""Uncaught Error: Uncaught (in promise): Error: No value accessor for form control with name: X"", X being a form field in a completely different component (which tests are passing fine). This error only occurs if I run all tests. If I run specifically the ones that are failing, they will pass without problems. </p>

<p>I have tried researching the issue and error message, but so far have found nothing related to my specific issue. The problem is that there is no form in 2 of the 3 components that complain and in the 3rd, the complaints are about fields in another component.</p>

<p>This is the error message for the component Event:</p>

<pre class=""lang-js prettyprint-override""><code>Uncaught Error: Uncaught (in promise): Error: No value accessor for form control with name: 'username'
    Error: No value accessor for form control with name: 'username'
        at te (webpack:///node_modules/@angular/forms/fesm5/forms.js:2144 &lt;- test-config/karma-test-shim.js:2092:1740)
        at J (webpack:///node_modules/@angular/forms/fesm5/forms.js:2054 &lt;- test-config/karma-test-shim.js:2092:117)
        at webpack:///node_modules/@angular/forms/fesm5/forms.js:4337 &lt;- test-config/karma-test-shim.js:2106:16703
        at e.invoke (webpack:///node_modules/zone.js/dist/zone.js:391 &lt;- test-config/karma-test-shim.js:2140:7006)
        at e.onInvoke (webpack:///node_modules/zone.js/dist/async-test.js:106 &lt;- test-config/karma-test-shim.js:2290:1819)
        at e.onInvoke (webpack:///node_modules/zone.js/dist/proxy.js:126 &lt;- test-config/karma-test-shim.js:2253:2259)
        at e.invoke (webpack:///node_modules/zone.js/dist/zone.js:390 &lt;- test-config/karma-test-shim.js:2140:6946)
        at Object.onInvoke (webpack:///node_modules/@angular/core/fesm5/core.js:17299 &lt;- test-config/karma-test-shim.js:600:1161)
        at e.invoke (webpack:///node_modules/zone.js/dist/zone.js:390 &lt;- test-config/karma-test-shim.js:2140:6946)
        at t.run (webpack:///node_modules/zone.js/dist/zone.js:150 &lt;- test-config/karma-test-shim.js:2140:2205)
        at webpack:///node_modules/zone.js/dist/zone.js:889 &lt;- test-config/karma-test-shim.js:2140:13729
        at e.invokeTask (webpack:///node_modules/zone.js/dist/zone.js:423 &lt;- test-config/karma-test-shim.js:2140:7690)
        at e.onInvokeTask (webpack:///node_modules/zone.js/dist/async-test.js:90 &lt;- test-config/karma-test-shim.js:2290:1616)
        at e.onInvokeTask (webpack:///node_modules/zone.js/dist/proxy.js:157 &lt;- test-config/karma-test-shim.js:2253:2880)
        at e.invokeTask (webpack:///node_modules/zone.js/dist/zone.js:422 &lt;- test-config/karma-test-shim.js:2140:7611)
        at Object.onInvokeTask (webpack:///node_modules/zone.js/dist/zone.js:304 &lt;- test-config/karma-test-shim.js:2140:4663)
        at e.invokeTask (webpack:///node_modules/zone.js/dist/zone.js:422 &lt;- test-config/karma-test-shim.js:2140:7611)
        at Object.onInvokeTask (webpack:///node_modules/@angular/core/fesm5/core.js:17290 &lt;- test-config/karma-test-shim.js:600:1073)
        at e.invokeTask (webpack:///node_modules/zone.js/dist/zone.js:422 &lt;- test-config/karma-test-shim.js:2140:7611)
        at t.runTask (webpack:///node_modules/zone.js/dist/zone.js:195 &lt;- test-config/karma-test-shim.js:2140:2868)
        at v (webpack:///node_modules/zone.js/dist/zone.js:601 &lt;- test-config/karma-test-shim.js:2140:9981)
        at t.invokeTask [as invoke] (webpack:///node_modules/zone.js/dist/zone.js:502 &lt;- test-config/karma-test-shim.js:2140:8826)
        at y (webpack:///node_modules/zone.js/dist/zone.js:1744 &lt;- test-config/karma-test-shim.js:2171:631)
        at g (webpack:///node_modules/zone.js/dist/zone.js:1770 &lt;- test-config/karma-test-shim.js:2171:873) thrown


</code></pre>

<p>This is the .ts for Event:</p>

<pre class=""lang-js prettyprint-override""><code>export class EventPage implements OnInit {
    activity: any;
    allEvents = [];

    constructor(private router: Router, private authService: AuthService, private activityService: ActivityService, private dataService: DataService) {
    }


    ngOnInit() {
        this.activityService.getAllActivities().subscribe(data =&gt; this.allEvents = data);
        this.activity = 'all-activities';
    }

    loadEvent(activity) {
        this.dataService.setData('activity', activity);
        this.router.navigateByUrl('/specific-event/activity');
    }

    goToCreateEvent() {
        this.router.navigate(['create-event']);
    }

    segmentChanged(event) {
        this.activity = event.target.value;
    }
}

</code></pre>

<p>The .spec.ts:</p>

<pre class=""lang-js prettyprint-override""><code>import {CUSTOM_ELEMENTS_SCHEMA, TemplateRef, ViewContainerRef} from '@angular/core';
import {async, ComponentFixture, TestBed} from '@angular/core/testing';

import {EventPage} from './event.page';
import {Router} from '@angular/router';
import {AuthService} from '../../services/authentication-service/auth.service';
import {ActivityService} from '../../services/activity-service/activity.service';
import {DataService} from '../../services/data.service';
import {SharedDirectivesModule} from '../../directives/shared-directives.module';
import {HasRoleDirective} from '../../directives/has-role.directive';
import {CommonModule} from '@angular/common';
import {UserService} from '../../services/user-service/user.service';
import {ActivityServiceMock, UserServiceMock} from '../../../../test-config/mocks-ionic';

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

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [SharedDirectivesModule],
            declarations: [EventPage],
            schemas: [CUSTOM_ELEMENTS_SCHEMA],
            providers: [
                {provide: Router, useValue: null},
                {provide: AuthService, useValue: null},
                {provide: ActivityService, useValue: new ActivityServiceMock()},
                {provide: DataService, ueValue: null},
                {provide: UserService, useValue: new UserServiceMock()},
                {provide: TemplateRef, useValue: null},
                {provide: ViewContainerRef, useValue: null}]
        })
            .compileComponents();
    }));

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

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

</code></pre>

<p>And this is the form from the component Register, which does have the field being requested in Event:</p>

<pre><code>   &lt;form&gt;
        ...
                        &lt;ion-item&gt;
                            &lt;ion-input name=""username"" placeholder=""Username"" type=""username"" ngModel required
                                       [(ngModel)]=""username""&gt;&lt;/ion-input&gt;
                        &lt;/ion-item&gt;

                        &lt;ion-item&gt;
                            &lt;ion-input name=""displayname"" placeholder=""Displayname"" type=""username"" ngModel required
                                       [(ngModel)]=""displayname""&gt;&lt;/ion-input&gt;
                        &lt;/ion-item&gt;

        ...
    &lt;/form&gt;
</code></pre>
",https://stackoverflow.com/questions/56145413/why-are-my-karma-unit-tests-throwing-an-error-for-missing-value-accessors-in-com,"['unit-testing', 'karma-jasmine', 'ionic4']",207,False,0,0
Should I pass private state with params to functions or should functions use the private state?,"<p>I have an Angular app with the following scenario, although I believe this scenario is suitable for other frameworks/scenario's too:</p>

<pre><code>public export class FooComponent {
    private userId: number;

    constructor(private readonly authService: AuthService) { }

    ngOnInit() {
        this.userId = authService.GetUser().id;

        this.getDataByUserId(this.userId);    
    }

    private getDataByUserId(userId: number) { 
        // Load data using the param
    }

    public anotherFunction(fooId: number) {
       // Gets called by an event occurring or something
       // Perform an API Call

       // Now reload the data by using the private state variable.
       this.getDataByUserId(this.userId);
    }
}
</code></pre>

<p>Should <code>getDataByUserId(userId: number)</code> use a parameter to receive the userId, or should it be parameter-less and just access the <code>private userId</code> of the component?</p>

<p>In my mind, the pro's and con's of passing the variable as a param are the following:</p>

<p><strong>Pro's</strong><br>
- Easier unit testing; if the component is a bit bigger you might not need to set up the component in a specific way to work, you only need to pass a number
- If many functions of your component access that one variable and change it, you might end up in scenario's where the variable is in an invalid state.</p>

<p><strong>Con's</strong><br>
- If you don't set up the component in a specific way anymore since you can just pass the value as a param, the ""state"" of the your component during the test might not reflect the expected state during a production scenario. Since your test does not reflect real working conditions they might be considered brittle.
- If you pass the wrong value, things will/can go wrong.</p>

<p>What is considered the better option here? Where does one draw the line?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/59101776/should-i-pass-private-state-with-params-to-functions-or-should-functions-use-the,"['angular', 'architecture']",55,False,0,1
Initializing Variable From Const With Some Changes,"<p>I'm trying to create some scenarios for unit testing purposes and running into some problems when dealing with complex objects that I'd like to start from a base state.</p>

<p>In the below example is a simplified case where we have a query builder that may take three parameters. In this case we must always supply all three parameters to avoid a NPE when trying to access a reference.</p>

<pre><code>package main

import (
  ""fmt""
)

type Searcher struct {
  Param string
}

type CompleteSearcher struct {
  A *Searcher
  B *Searcher
  C *Searcher
}

func (c *CompleteSearcher) FormatQuery() string {
  return fmt.Sprintf(""%s%s%s"", c.A.Param, c.B.Param, c.C.Param)
}

func main() {
  testCases := []struct {
    scenario string
    want string
    searcher *CompleteSearcher
  }{
    {
      scenario: ""A populated"",
      want: ""A"",
      searcher: &amp;CompleteSearcher{
          A: &amp;Searcher{Param: ""A""},
          B: &amp;Searcher{},
          C: &amp;Searcher{},
        },
    },
  }

  for _, tc := range testCases {
    got := tc.searcher.FormatQuery()
    if got != tc.want {
      fmt.Println(""error"")
    }
  }
}
</code></pre>

<p>My specific problem with this is mostly that the scenario must initialize all fields creating a noisy test where it's somewhat unclear what's actually under test. You can imagine with even more searchable fields, cache classes, backend classes, etc. that a simple enough function can have an enormous object responsible for actually doing the setup.</p>

<p>So what I'd like to do instead is something like the following.</p>

<pre><code>baseSearcher := &amp;CompleteSearcher{
  A: &amp;Searcher{},
  B: &amp;Searcher{},
  C: &amp;Searcher{},
}
testCases := []struct {
  scenario string
  want string
  searcher *CompleteSearcher
}{
  {
    scenario: ""A populated"",
    want: ""A"",
    searcher: New(baseSearcher){A: &amp;Searcher{Param: ""A""}}
  },
}
</code></pre>

<p>Essentially I'd like to be able to test an entire object, but have the option to start with a ""base"" version of that object to prevent repeated setup in each scenario setup. From what I can tell there's no way to create a copy (even a shallow-copy) and then also do another assignment in a single statement, making it effectively impossible to have each scenario handle the object directly.</p>

<p>Any tips on how to resolve this issue?</p>
",https://stackoverflow.com/questions/57487057/initializing-variable-from-const-with-some-changes,"['unit-testing', 'go']",89,True,0,1
How to wrap python logging module?,"<p>I would like to wrap the creation of a logger and all its associated configuration, formatters and handlers in a separate module, so that from my application I would just write:</p>
<pre><code>import my_logger

test_logger = my_logger.getlogger(&quot;logger_name&quot;)
</code></pre>
<p>This logger will be used in a unit testing framework using <code>unittest.TestCase</code> for logging purposes.</p>
<p>I use a <code>QueueHandler</code> and a <code>QueueListener</code> on one handler (as per <a href=""https://docs.python.org/3/howto/logging-cookbook.html#dealing-with-handlers-that-block"" rel=""nofollow noreferrer"">https://docs.python.org/3/howto/logging-cookbook.html#dealing-with-handlers-that-block</a>), as the handler is using the Telegram API and I would like to avoid hanging the whole application while waiting for the Telegram server to be available (for whatever reason).</p>
<p>The (perhaps silly) question is:</p>
<p>how can I automatically handle the start and stop of the <code>QueueListener</code> when I start and stop the execution of the tests? Do I have to subclass a class of the logging module (which one?) to add, say, a start/stop method?</p>
<p>Thank you very much.</p>
<p><strong>UPDATED (01)</strong></p>
<p>I think I was not complete in my question. I already have the wrapper for the logger, you will find it below:</p>
<pre><code>import logging
from logging.handlers import QueueHandler
from logging.handlers import QueueListener
import queue
from time import strftime

from notifiers.logging import NotificationHandler


def getLogger(name):
            
    LOG_DIR = &quot;logs&quot;

    _test_logger = logging.getLogger(name)
    _test_logger.setLevel(logging.INFO)
    

    # Create a file handler for the test logger.
    # This handler will create the log file of the tests.
    # TODO: create the LOG_DIR if it does not exist
    now = strftime(&quot;%Y%m%d_%H%M%S&quot;)
    # TODO: use os.path methods instead of directly writing path into filenames
    _tl_fh = logging.FileHandler(&quot;..\\{}\\{}_{}.txt&quot;.format(LOG_DIR, now, name))
    _tl_formatter = logging.Formatter(&quot;%(asctime)s - %(levelname)s - %(message)s&quot;)
    _tl_fh.setFormatter(_tl_formatter)
    _test_logger.addHandler(_tl_fh)
    
    # Create a console handler for the test logger.
    # This is the logger to the console
    _tl_console = logging.StreamHandler()
    _test_logger.addHandler(_tl_console)
    
    # Create a notifier logger. This will notify via Telegram:
    # * start of a test suite
    # * Stop of a test suite
    # * Test suite and test case errors
    
    # Create an unlimited size queue and attach it to a queue handler
    que = queue.Queue(-1)
    queue_handler = QueueHandler(que)
    # Create a Telegram notification handler.  
    hdlr = NotificationHandler(&quot;telegram&quot;, defaults=defaults)
    # On the other side of the queue attach a queue listener
    _listener = QueueListener(que, hdlr)
    queue_handler.setLevel(logging.ERROR)
    _test_logger.addHandler(queue_handler)
    formatter = logging.Formatter(&quot;%(asctime)s - %(levelno)s - %(levelname)s - %(message)s&quot;)

    hdlr.setFormatter(formatter)
    #=======================================================================
    # Start the queue listener
    #=======================================================================
    
    _listener.start()
    
    return _test_logger
    
</code></pre>
<p>The &quot;problem&quot; is the <code>_listener.start()</code> line. How can I stop the listener at the end of the test?
Is it possible to add a start/stop methods to the loggers, so that I can write something like?</p>
<pre><code>import my_logger

test_logger = my_logger.getlogger(&quot;logger_name&quot;)
[...] execute some test here

test_logger.stop()
</code></pre>
",https://stackoverflow.com/questions/58592557/how-to-wrap-python-logging-module,"['python-3.x', 'logging']",3917,False,0,4
Jest - TypeError: response.json is not a function,"<p>We are unit testing a React-Native application (using Jest) which does various API calls using <code>fetch</code>.</p>
<p>We have mocked calls to <code>fetch</code> in our API call functions in order to test them. This works well so far. We also have functions that combine these API calls and operate some logic on them.</p>
<p>For example, here is one function that, given a token, will get the related user's first project (<code>project[0]</code>) and return the list of items from this project.</p>
<pre><code>export async function getAllItems(token) {
  try {
    const response = await getCurrentUser(token); // fetch called inside
    const responseJson = await response.json();
    const allItemsResp = await getAllItemsFromSpecificProject(
      token,
      responseJson.projectIds[0],
    );                                            // fetch called inside
    return await allItemsResp.json();
  } catch (error) {
    console.log(error);
    return null;
  }
}
</code></pre>
<p>Both functions <code>getCurrentUser</code> and <code>getAllItemsFromSpecificProject</code> are simple <code>fetch</code> calls and are currently mocked properly. Here one test that tries to test the <code>getAllItems</code> function:</p>
<pre><code>it('Gets all items', async () =&gt; {
  getAccessTokenMockFetch();
  const token = await getAccessToken('usherbrooke@powertree.io', 'test!23');

  getAllItemsMockFetch();
  const items = await getAllItems(token.response.access_token);

  expect(items.response.length).toEqual(3);
});
</code></pre>
<p>For clarity, here is how <code>getAccessTokenMockFetch</code> is done. <code>getAllItemsMockFetch</code> is almost identical (with different data in the response):</p>
<pre><code>function getAccessTokenMockFetch() {
  global.fetch = jest.fn().mockImplementation(() =&gt; {
    promise = new Promise((resolve, reject) =&gt; {
      resolve(accepted);
    });

    return promise;
  });
}
</code></pre>
<p>where accepted contains the JSON content of a successful call. When we run this test, we get the following error:</p>
<pre><code>TypeError: Cannot read property 'response' of null
</code></pre>
<p>And we <code>console.log</code> this one in the catch:</p>
<pre><code>TypeError: response.json is not a function
</code></pre>
<p>which explains why response is <code>null</code>. It seems the <code>json()</code> call is not understood and I don't know how to mock it. I have done tons of research on Stack Overflow and beyond, but we have found nothing that helps me understand how to solve this issue. This might indicate that I am going the wrong way about this, which is quite possible since I'm new to JavaScript, React Native, and Jest.</p>
",https://stackoverflow.com/questions/58599735/jest-typeerror-response-json-is-not-a-function,"['javascript', 'json', 'react-native', 'jestjs', 'fetch-api']",6981,True,0,2
How to write junit to test concurrency?,"<p>I am fairly new to Junit and Unit testing so please excuse if this qualifies as a bad question. I have to unit test my code for concurrency. I thoroughly understand I cannot ask someone to do code for me but I am in dire need for the test case as I am not getting how to proceed. :(</p>

<p>I have created an API which does money transfer between 2 accounts. We have fromAccountNumber, toAccountNumber which are String fields and amount as BigDecimal. The account details are stored in H2 data base (in memory). </p>

<p>I created an executor service but then it requires runnable type and I can't make my class with the logic for transfer as runnable.</p>

<p>Also in the code the thread safety I have achieved using Select.. for update  (this query : GET_BY_ID_QUERY_FOR_TRANSACTION) statement while fetching the records from DB.</p>

<p>The basic logic for money transfer is as below :</p>

<pre><code>public void transferMoney(String sender, String receiver, BigDecimal amount) throws TransferException {
        Connection conn = null;
        try {
            conn = H2DataBase.getConnection();

            checkIfAccountNumbersAreValid(sender, receiver);

            AccountDetailsDTO fromAccountDto = getAccountByNumber(conn, sender);
            AccountDetailsDTO toAccountDto = getAccountByNumber(conn, receiver);

            if (null != fromAccountDto &amp;&amp; null != toAccountDto) {
                transfer(conn, fromAccountDto, toAccountDto, amount);
            } else {
                rollback(conn);
                throw new TransferException(""Transfer Failed. Please check the account numbers."",
                        Response.Status.BAD_REQUEST);
            }
        } catch (SQLException e) {
            throw new TransferException(""Transfer Failed !"", Response.Status.INTERNAL_SERVER_ERROR);
        } catch (ValidationException e) {
            throw new TransferException(e.getMessage(), e.getStatus());
        } finally {
            closeConnection(conn);
        }
    }

    private void transfer(Connection conn, AccountDetailsDTO fromAccountDto, AccountDetailsDTO toAccountDto,
            BigDecimal transactionAmount) throws TransferException {

        PreparedStatement preparedStatementInsertToTransaction = null;
        PreparedStatement preparedStatementUpdateFromAccount = null;
        PreparedStatement preparedStatementUpdateToAccount = null;

        try {

            checkToAndFromAreDifferent(fromAccountDto, toAccountDto);
            checkAccountBalanceBeforeTransfer(fromAccountDto.getAccountBalance(), transactionAmount);

            fromAccountDto.setAccountBalance(fromAccountDto.getAccountBalance().subtract(transactionAmount));
            toAccountDto.setAccountBalance(toAccountDto.getAccountBalance().add(transactionAmount));

            preparedStatementInsertToTransaction = conn
                    .prepareStatement(DBQueryUtility.INSERT_INTO_TRANSACTION_TABLE_QUERY);
            preparedStatementInsertToTransaction.setString(1, fromAccountDto.getAccountNumber());
            preparedStatementInsertToTransaction.setString(2, toAccountDto.getAccountNumber());
            preparedStatementInsertToTransaction.setBigDecimal(3, transactionAmount);

            preparedStatementInsertToTransaction.executeUpdate();

            preparedStatementUpdateFromAccount = conn.prepareStatement(DBQueryUtility.UPDATE_BANK_ACCOUNT_TABLE_QUERY);
            preparedStatementUpdateFromAccount.setBigDecimal(1, fromAccountDto.getAccountBalance());
            preparedStatementUpdateFromAccount.setString(2, fromAccountDto.getAccountNumber());

            preparedStatementUpdateFromAccount.executeUpdate();

            preparedStatementUpdateToAccount = conn.prepareStatement(DBQueryUtility.UPDATE_BANK_ACCOUNT_TABLE_QUERY);
            preparedStatementUpdateToAccount.setBigDecimal(1, toAccountDto.getAccountBalance());
            preparedStatementUpdateToAccount.setString(2, toAccountDto.getAccountNumber());

            preparedStatementUpdateToAccount.executeUpdate();

            conn.commit();

        } catch (ValidationException e) {
            rollback(conn);
            throw new TransferException(e.getMessage(), Response.Status.BAD_REQUEST);
        } catch (RuntimeException | SQLException e) {
            rollback(conn);
            throw new TransferException(""Transfer Failed"", Response.Status.INTERNAL_SERVER_ERROR);
        } finally {
            closeConnection(conn);
            closePreparedStatement(preparedStatementInsertToTransaction, preparedStatementUpdateFromAccount,
                    preparedStatementUpdateToAccount);

        }
    }

    public void checkIfAccountNumbersAreValid(String sender, String receiver) throws ValidationException {
        if (null == sender || null == receiver || sender.isEmpty() || receiver.isEmpty()) {
            throw new ValidationException(""Account details cannot be null or empty !"", Response.Status.BAD_REQUEST);
        }
    }

    @Override
    public void checkToAndFromAreDifferent(AccountDetailsDTO fromAccountDto, AccountDetailsDTO toAccountDto)
            throws ValidationException {
        if (toAccountDto.getAccountNumber().equals(fromAccountDto.getAccountNumber())) {
            throw new ValidationException(""To and From accounts cannot be same !"", Response.Status.BAD_REQUEST);
        }
    }

    @Override
    public void checkAccountBalanceBeforeTransfer(BigDecimal accountBalance, BigDecimal amount)
            throws ValidationException {
        if (accountBalance.compareTo(BigDecimal.ZERO) &lt; 0 || accountBalance.compareTo(amount) &lt; 0) {
            throw new ValidationException(""Low account balance. Cannot initiate transfer !"",
                    Response.Status.BAD_REQUEST);
        }
    }

    public AccountDetailsDTO getAccountByNumber(Connection conn, String accountNumber) throws TransferException {
        AccountDetailsDTO detailsDTO = null;
        try {
            PreparedStatement preparedStatement = conn.prepareStatement(DBQueryUtility.GET_BY_ID_QUERY_FOR_TRANSACTION);
            preparedStatement.setString(1, accountNumber);

            ResultSet rs = preparedStatement.executeQuery();

            while (rs.next()) {
                detailsDTO = DBQueryUtility.extractAccountDtoFromResultSet(rs);
            }
        } catch (SQLException e) {
            throw new TransferException(""Get by account number failed ! Try again."",
                    Response.Status.INTERNAL_SERVER_ERROR);
        }
        return detailsDTO;
    }


</code></pre>

<p>I want to a testcase in which I can run 100 threads and each thread transfers amount from one account to another. Suppose we have 3 account : 1,2,3 each having balance as 1000$.</p>

<p>so 1 thread should try to tansfer from 1 to 2, then second thread does 2,1, then 3,1 so on. All the permutation combinations.</p>

<p>How to create this test case. Please help.</p>
",https://stackoverflow.com/questions/56268569/how-to-write-junit-to-test-concurrency,"['java', 'multithreading', 'unit-testing', 'junit', 'concurrency']",723,False,0,0
Scala - method X overrides nothing,"<p>I am trying to perform some unit testing over a Spark Streaming application which involves DStreams.</p>

<p>I found it very useful the following suit: <strong>StreamingSuiteBase</strong>. It contains a method named <em>testOperation</em> to which you can pass an input, an operation to test and an expected output. It will verify if your expected output matches with the actual output.</p>

<p>The problem I am facing is during the equality verification I am getting indeed the exact same object, but wrapped into different collections:</p>

<ul>
<li>expected: List(myObject) </li>
<li>actual:   Array(myObject)</li>
</ul>

<p>The testOperation is defined as follows:</p>

<pre><code>  def testOperation[U: ClassTag, V: ClassTag](
      input: Seq[Seq[U]],
      operation: DStream[U] =&gt; DStream[V],
      expectedOutput: Seq[Seq[V]],
      ordered: Boolean
    ) (implicit equality: Equality[V]): Unit = {
    val numBatches = input.size

    withOutputAndStreamingContext(setupStreams[U, V](input, operation)) {
      (outputStream, ssc) =&gt;

      val output: Seq[Seq[V]] = runStreams[V](
        outputStream, ssc, numBatches, expectedOutput.size)
      verifyOutput[V](output, expectedOutput, ordered)
    }
  }
</code></pre>

<p>Which doesn't let me use as expected input a <code>List(Array(myObject))</code></p>

<p>So my second option was to modify the method <code>verifyOutput</code>. I was planing to override it from my code, just adding a few lines to generate the List(Array(myObject)). Like this (<strong>Updated</strong>):</p>

<pre><code>override def verifyOutput[V](output: Seq[Seq[V]],
                             expectedOutput: Seq[Seq[V]],
                             ordered: Boolean)
                             (implicit evidence$1: ClassTag[V], equality: Equality[V]): Unit = {
    super.verifyOutput(output, expectedOutput, ordered)
}

        //These three lines is what I am planning to add
        val sq = expectedOutput(0)
        val ssq = sq(0)
        val newOutput = Seq(Array(ssq))

        logInfo(""--------------------------------"")
        logInfo(""output.size = "" + output.size)
        logInfo(""output"")
        output.foreach(x =&gt; logInfo(""["" + x.mkString("","") + ""]""))
        logInfo(""expected output.size = "" + expectedOutput.size)
        logInfo(""expected output"")
        expectedOutput.foreach(x =&gt; logInfo(""["" + x.mkString("","") + ""]""))
        logInfo(""--------------------------------"")

        // Match the output with the expected output
        assert(output.size === expectedOutput.size, ""Number of outputs do not match"")
        if (ordered) {
          for (i &lt;- output.indices)
            equalsOrdered(output(i), expectedOutput(i))

        } else {
          for (i &lt;- output.indices)
            equalsUnordered(output(i), expectedOutput(i))
        }

        logInfo(""Output verified successfully"")
      }
</code></pre>

<p>The whole StreamingSuiteBase can be found <a href=""https://github.com/holdenk/spark-testing-base/blob/master/src/main/1.3/scala/com/holdenkarau/spark/testing/StreamingSuiteBase.scala"" rel=""nofollow noreferrer"">here</a></p>

<p>But I am getting the following error in Eclipse:</p>

<blockquote>
  <p>method verifyOutput overrides nothing. Note: the super classes of
  class myClass contain the following, non final members named
  verifyOutput: def verifyOutput[V](output: Seq[Seq[V]],expectedOutput:
  Seq[Seq[V]],ordered: Boolean)(implicit evidence$1:
  scala.reflect.ClassTag[V],implicit equality:
  org.scalactic.Equality[V]): Unit</p>
</blockquote>

<p>This is a simplify version of my test case:</p>

<pre><code>import org.scalatest.FunSuite

class myClass extends StreamingSuiteBase with FunSuite {

  test(""ExtCustProfileHbaseAPI"") {

    //Here I would be generating my input and expected output

    val inputData = new myInitialObject()
    val expOutput = new myFinalObject()


    testOperation(inputData, processTest _, expOutput, ordered = false)


  }

  def processTest(input: DStream[myInitialObject]): DStream[(String,myFinalObject)] = {

        //Operation undertes
        val result = operation(input)

        result
    }

    //Here I added the override def verifyOutput[V: ClassTag]...
}
</code></pre>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/54781536/scala-method-x-overrides-nothing,"['scala', 'apache-spark', 'scalatest']",2082,True,0,1
How to deploy symlinked react javascript files to appear in the Docker container,"<p>I have a Django as backend and React as frontend project running inside Docker containers.</p>

<p>Currently, I have all the Django and react code all in the same repo. And the project works as expected when testing at <a href=""http://localhost:8000/frontend"" rel=""nofollow noreferrer"">http://localhost:8000/frontend</a> which will hit the template (<code>index.html</code> under the <code>/frontend/templates/frontend</code> which in turn will reference <code>/frontend/static/dist/main.js</code>)</p>

<p>So as it is right now, the project works with Docker.</p>

<p>The project is structured as thus:</p>

<pre><code>project_root
     |
     |---frontend (this is a Django app which contains the react files)
     |      |--- static
     |      |      |--- dist
     |      |              |--- main.js
     |      |              
     |      |--- templates
     |             |--- frontend
     |                     |--- index.html (this references the static/dist/main.js)
     |
     |
     |---... more Django apps
     |
     |--- compose
             |
             |---local
                   |
                   |---- django
                            |---- Dockerfile
                            |---- start
</code></pre>

<p>Currently, my Dockerfile under the <code>/compose/local/django</code> looks like this:</p>

<pre><code>FROM python:3.6-alpine

ENV PYTHONUNBUFFERED 1

RUN apk update \
  # psycopg2 dependencies
  &amp;&amp; apk add --virtual build-deps gcc python3-dev musl-dev \
  &amp;&amp; apk add postgresql-dev \
  # Pillow dependencies
  &amp;&amp; apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \
  # CFFI dependencies
  &amp;&amp; apk add libffi-dev py-cffi \
  # Translations dependencies
  &amp;&amp; apk add gettext \
  # https://docs.djangoproject.com/en/dev/ref/django-admin/#dbshell
  &amp;&amp; apk add postgresql-client \
  # git
  &amp;&amp; apk add --no-cache git

# Requirements are installed here to ensure they will be cached.
COPY ./requirements /requirements
RUN pip install -r /requirements/project.local.txt

COPY ./compose/production/django/entrypoint /entrypoint
RUN sed -i 's/\r//' /entrypoint
RUN chmod +x /entrypoint

COPY ./compose/local/django/start /start
RUN sed -i 's/\r//' /start
RUN chmod +x /start

WORKDIR /app

ENTRYPOINT [""/entrypoint""]
</code></pre>

<h2>Objective</h2>

<p>I would like to have my react code and my Django code as separate repos. Because it would be easier to have separate CI/CD and unit testing for frontend React code and backend Django code.</p>

<h2>What I tried</h2>

<ol>
<li>have a separate project folder meant just for the frontend react code and therefore it will live as its own git repo</li>
<li>symlink inside the Django project such that <code>/frontend/static/dist</code> points to the React project with the same folder name</li>
</ol>

<p>The complaints I get from the browser is that <code>/frontend/static/dist/main.js</code> is missing.</p>

<p>When I check the symlinked, the main.js is definitely there. So I think somehow when the Docker container is built, the files didn't get copied over? </p>

<p>How do I resolve this?</p>
",https://stackoverflow.com/questions/56537612/how-to-deploy-symlinked-react-javascript-files-to-appear-in-the-docker-container,"['django', 'reactjs', 'docker']",63,False,0,0
Writing unit test with mocks,"<p>I wrote a REST api in it. Now I want to do its unit testing it by isolating different components. </p>

<p>The project structure looks like below and there are two major packages</p>

<pre><code>├── main.go
├── routes
│   ├── routes.go
│   └── routes_test.go
├── db
│   └── db.go
</code></pre>

<p><strong>main.go</strong>: Main entry point for the project</p>

<p><strong>routes/routes.go</strong>: HTTP route handler package</p>

<p><strong>db/db.go</strong>: database handler package</p>

<p>Now when I am testing the http routing I only want to test if the requests are routed to proper handler functions are then they respond accordingly. In real application the handler function would actually insert/update the database but I don't want to do that while testing. So if I can mock a database object and make my handler functions connect/read/write against that, but I am not sure how to do that.</p>

<p>When it comes to testing the database handler package <code>db.go</code>, I think i can't mock that and I have to either set up a test db against which I should make queries.</p>

<p>This is how my files look.</p>

<p>routes/routes.go</p>

<pre><code>    package routes

    import (
        ""cfengine-service/db""
        ""encoding/json""
        ""net/http""
        ""strings""

        log ""github.com/sirupsen/logrus""

        ""github.com/gorilla/mux""
    )

    // Route - struct modal for routes
    type Route struct {
        Name        string
        EndPoint    string
        Methods     []string
        HandlerFunc http.HandlerFunc
    }
    var dbHandler = &amp;db.Mongo{}

    // SetupRouter - returns the mux router
    func SetupRouter() *mux.Router {
        err := dbHandler.Connect()
        if err != nil {
            log.Fatal(err)
        }
        router := mux.NewRouter()
        for _, route := range SetUpRoutes() {
            router.HandleFunc(route.EndPoint, route.HandlerFunc).Methods(route.Methods...)
        }
        return router

    }
    func SetUpRoutes() []Route {
        return []Route{
            {
                ""Host config Management"",
                ""/configs/group"",
                []string{""GET"", ""POST""},
                GroupConfig,
            },
    }

func GroupConfig(w http.ResponseWriter, r *http.Request) {
    reqMethod := r.Method
    if reqMethod == ""GET"" {
        GetGroupConfig(w, r)
    } else if reqMethod == ""POST"" {
        NewGroupConfig(w, r)
    }

}

func GetGroupConfig(w http.ResponseWriter, r *http.Request) {
    w.Header().Set(""Content-Type"", ""application/json"")
    // g := r.URL.Query().Get(""groupname"")
    g := r.FormValue(""groupname"")
    if g == """" {
        if data, err := dbHandler.ReadAllGroups(); StatusWriter(w, err) {
            _ = json.NewEncoder(w).Encode(data)
        }
    } else {
        if data, err := dbHandler.ReadOneGroup(g); StatusWriter(w, err) {
            _ = json.NewEncoder(w).Encode(data)
        }
    }

}

// NewGroupConfig - end point for creating new config group
func NewGroupConfig(w http.ResponseWriter, r *http.Request) {
    w.Header().Set(""content-type"", ""application/json"")
    var group db.GroupConfig
    err := json.NewDecoder(r.Body).Decode(&amp;group)
    StatusWriter(w, err)

    err = dbHandler.CreateGroupConfig(&amp;group)
    StatusWriter(w, err)
}
</code></pre>

<p><strong>db/db.go</strong></p>

<pre><code>    package db

    import (
        ""cfengine-service/config""
        ""cfengine-service/helpers""
        ""context""
        ""fmt""
        ""time""

        log ""github.com/sirupsen/logrus""
        ""go.mongodb.org/mongo-driver/bson""
        ""go.mongodb.org/mongo-driver/mongo""
        ""go.mongodb.org/mongo-driver/mongo/options""
    )

    type HostConfig struct {
        Hostname  string            `bson:""_id"" json:""hostname""`
        Type      string            `bson:""type"" json:""type""`
        Groups    []string          `bson:""groups"" json:""groups""`
        Overrides map[string]string `bson:""overrides"" json:""overrides""`
        Excludes  []string          `bson:""excludes"" json:""excludes""`
        Data      map[string]string `bson:""data"" json:""data""`
    }


    // Mongo collection
    type Mongo struct {
        collection *mongo.Collection
    }

    // Storage is interface for db operations
    type Storage interface {
        Connect() error
        ReadAll() ([]HostConfig, error)
        ReadOne() (*HostConfig, error)
        CreateHostConfig(h *HostConfig) error
        CreateGroupConfig(g *GroupConfig) error
        DeleteHostConfig(h *HostConfig) error
        UpdateHostGrops(h string, g string, opr string) error
        validateGroup(ctx context.Context, val string) error
    }

    func (m *Mongo) Connect() error {
        ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
        defer cancel()
        //client, err := mongo.NewClient(config.Config.MongoURI)
        client, err := mongo.Connect(ctx, options.Client().ApplyURI(config.Config.MongoURI))
        if err != nil {
            return err
        }

        log.Info(""Connected to MongoDB....."")
        m.collection = client.Database(config.Config.MongoDbName).Collection(config.Config.MongoCollectionName)
        return nil
    }
func (m *Mongo) CreateGroupConfig(g *GroupConfig) error {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    data, err := bson.Marshal(g)
    if err != nil {
        log.Error(err.Error())
        return err
    }
    _, err = m.collection.InsertOne(ctx, data)
    if err != nil {
        return err
    }
    return nil
}

func (m *Mongo) ReadOneGroup(g string) (GroupConfig, error) {
    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
    defer cancel()
    var group GroupConfig
    err := m.collection.FindOne(ctx, bson.M{""_id"": g}).Decode(&amp;group)
    if err != nil {
        return GroupConfig{}, err
    }

    return group, nil
}

func (m *Mongo) ReadAllGroups() ([]GroupConfig, error) {
    var configs []GroupConfig
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    cur, err := m.collection.Find(ctx, bson.M{""type"": ""group""})
    if err != nil {
        return nil, err
    }
    defer cur.Close(ctx)
    for cur.Next(ctx) {
        var record GroupConfig
        if err = cur.Decode(&amp;record); err != nil {
            return nil, err
        }
        configs = append(configs, record)
    }
    return configs, nil
}
</code></pre>

<p>So using the <code>mockgen</code> package i generated the mocks for <code>Storage</code> interface in my <code>db.go</code> but I am not sure how do I start using that. Here is how mock_db.go looks.</p>

<p><strong>mock_db.go</strong></p>

<pre><code>type MockStorage struct {
    ctrl     *gomock.Controller
    recorder *MockStorageMockRecorder
}

// MockStorageMockRecorder is the mock recorder for MockStorage
type MockStorageMockRecorder struct {
    mock *MockStorage
}

// NewMockStorage creates a new mock instance
func NewMockStorage(ctrl *gomock.Controller) *MockStorage {
    mock := &amp;MockStorage{ctrl: ctrl}
    mock.recorder = &amp;MockStorageMockRecorder{mock}
    return mock
}

// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockStorage) EXPECT() *MockStorageMockRecorder {
    return m.recorder
}

// Connect mocks base method
func (m *MockStorage) Connect() error {
    m.ctrl.T.Helper()
    ret := m.ctrl.Call(m, ""Connect"")
    ret0, _ := ret[0].(error)
    return ret0
}

// Connect indicates an expected call of Connect
func (mr *MockStorageMockRecorder) Connect() *gomock.Call {
    mr.mock.ctrl.T.Helper()
    return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, ""Connect"", reflect.TypeOf((*MockStorage)(nil).Connect))
}
func (m *MockStorage) CreateGroupConfig(arg0 *db.GroupConfig) error {
    m.ctrl.T.Helper()
    ret := m.ctrl.Call(m, ""CreateGroupConfig"", arg0)
    ret0, _ := ret[0].(error)
    return ret0
}

// CreateGroupConfig indicates an expected call of CreateGroupConfig
func (mr *MockStorageMockRecorder) CreateGroupConfig(arg0 interface{}) *gomock.Call {
    mr.mock.ctrl.T.Helper()
    return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, ""CreateGroupConfig"", reflect.TypeOf((*MockStorage)(nil).CreateGroupConfig), arg0)
}
</code></pre>

<p>So can anyone please guide me here or give me some hints to move in right direction.</p>
",https://stackoverflow.com/questions/56187049/writing-unit-test-with-mocks,"['go', 'mocking']",1228,False,-1,1
expect middleware functin to call next function or send a http 400 code,"<p>I would like to get into unit testing and want to test my Node API. I use Express with Typescript, for tests I use Jest. Before calling the controller middleware I call the route input validation middleware to check if the params and body variables are valid. Otherwise I will send a 400 error code.</p>

<pre><code>this.router.route('/')
    .post(userValidations.validateCreateUser, userController.createUser);
</code></pre>

<p>This validation creates a schema to validate</p>

<pre><code>import { Request, Response, NextFunction } from 'express';
import joi, { SchemaLike } from '@hapi/joi';

import { validateRequest } from '../validator';

export function validateCreateUser (request: Request, response: Response, next: NextFunction) {
    const validationSchema: SchemaLike = joi.object().keys({
        body: joi.object().keys({
            username: joi.string().required(),
            password: joi.string().required(),
        }).unknown(true)
    }).unknown(true);

    validateRequest(validationSchema, request, response, next);
}
</code></pre>

<p>and calls the <code>valdateRequest</code> method. This method validates the <code>request</code> object against the <code>validationSchema</code> and calls the next function if the request input is valid. Otherwise it will respond with a 400 error code and send back the error details.</p>

<pre><code>import { Request, Response, NextFunction } from 'express';
import joi, { SchemaLike, ValidationResult, ValidationError } from '@hapi/joi';

export function validateRequest(validationSchema: SchemaLike, request: Request, response: Response, next: NextFunction) {
    const validationResult: ValidationResult&lt;Request&gt; = joi.validate(request, validationSchema, {
        abortEarly: false
    });

    const validationError: ValidationError = validationResult.error;

    if (validationError) {
        response.status(400).json({
            message: 'The route validation failed.',
            details: validationError.details,
        });
    } else {
        next();
    }
}
</code></pre>

<p>I would like to test the <code>validateRequest</code> function first. I want to pass in a predefined <code>request</code> object and a <code>validationSchema</code> and want to check if the next function gets called or the error response on invalid inputs.</p>

<p>Is it even possible to assume something? I have to create an Express <code>request</code> and <code>response</code> object. Further I have to check if the <code>nextFunction</code> was called. I started with this code</p>

<pre><code>import { Request, Response, NextFunction } from 'express';
import joi, { SchemaLike } from '@hapi/joi';

import { validateRequest } from '../../../src/interfaceAdapters/routeInputValidation/validator';

describe('The route input validator', () =&gt; {
    let nextFunction: NextFunction;
    let response: Response;

    beforeEach(() =&gt; {
        nextFunction = ():void =&gt; {
            console.log('Next function was called successfully.');
        }

        response = new Response();
    });

    it('calls the next middleware on a valid request', () =&gt; {
        const request: Request = new Request();
        request.params = {
            id: 'C56A4180-65AA-42EC-A945-5FD21DEC0538'
        };
        request.body = {};

        const validationSchema: SchemaLike = joi.object().keys({
            params: joi.object().keys({
                id: joi.string().guid().required(),
            }).unknown(true)
        }).unknown(true);

        // expect calling next function
        // validateRequest(validationSchema, request, response, nextFunction);
    });

    it('sends a HTTP 400 error on a invalid request', () =&gt; {
        const request: Request = new Request();
        request.params = {
            id: '12345'
        };
        request.body = {};

        const validationSchema: SchemaLike = joi.object().keys({
            params: joi.object().keys({
                id: joi.string().guid().required(),
            }).unknown(true)
        }).unknown(true);

        // expect calling res.status(400).json({})
        // validateRequest(validationSchema, request, response, nextFunction);
    });
});
</code></pre>

<p>I'm struggling with 3 problems. </p>

<ul>
<li>How to create an instance of <code>Request</code></li>
<li>How to create an instance of <code>Response</code></li>
<li>What do I have to expect? <code>expect(validateRequest(validationSchema, request, response, next)).to...</code></li>
</ul>

<p>It would be awesome if someone could explain how to test this properly. Maybe I have to restructure my business code but I tried to write it testable...</p>
",https://stackoverflow.com/questions/57440046/expect-middleware-functin-to-call-next-function-or-send-a-http-400-code,"['javascript', 'node.js', 'typescript', 'express', 'jestjs']",431,True,0,1
How can I fix my test suites failure to run because of the tcomb-form-native library for React Native?,"<p>I am trying to perform unit testing and integration testing for a React Native application. When running <code>yarn test --coverage</code> several of my test suites fail to run because of the tcomb-form-native library.</p>

<p>I receive this specific error: </p>

<p><code>({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){import t from ""./lib"";
</code>                                                                                             </p>

<pre><code>SyntaxError: Unexpected identifier

  13 | // import { gray } from 'ansi-colors';
  14 |
&gt; 15 | import t from 'tcomb-form-native';
     | ^
  16 |
  17 | const Form = t.form.Form;
  18 |

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.&lt;anonymous&gt; (screens/ReservationScreen.js:15:1)
</code></pre>

<p>I updated the <code>package.json</code> file following the Tests section from the library's GitHub, <a href=""https://github.com/gcanti/tcomb-form-native"" rel=""nofollow noreferrer"">https://github.com/gcanti/tcomb-form-native</a>, but continue to get the same error. </p>

<p>I'm confused by this line from the tcomb-form-native ReadMe Tests description:</p>

<pre><code>  ""ios.js""    &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; this needs to be defined!
</code></pre>

<p>I created the React Native app using Expo so I don't have an ios.js file. The only difference under the <code>""jest"":</code> from the example code in the GitHub is that I also have <code>""preset"": ""jest-expo"",</code> defined.</p>

<p><strong>What changes do I need to make to my <code>package.json</code> file or my test suites in order for my test suites to run?</strong> (They don't have to pass, just simply run.)</p>

<hr>

<p><em>Edit:</em> </p>

<p>I tried adding the following code to <code>package.json</code> based on the top answer from <a href=""https://github.com/gcanti/tcomb-form-native/issues/443"" rel=""nofollow noreferrer"">https://github.com/gcanti/tcomb-form-native/issues/443</a>: </p>

<pre><code>""transformIgnorePatterns"": [
  ""node_modules/(?!react-native|tcomb-form-native)""
]`
</code></pre>

<p>I added the code without the original suggested edits from the library's GitHub ReadMe and added it IN ADDITION to the suggested edits. I am still receiving <code>SyntaxError: Unexpected identifier</code> when I run tests.</p>

<hr>

<p><em>Edit #2:</em> </p>

<p>I changed changed <code>import t from 'tcomb-form-native';</code> to <code>var t = require('tcomb-form-native');</code> and I'm still receiving <code>SyntaxError: Unexpected identifier.</code></p>
",https://stackoverflow.com/questions/55523157/how-can-i-fix-my-test-suites-failure-to-run-because-of-the-tcomb-form-native-lib,"['reactjs', 'react-native', 'jestjs', 'expo', 'tcomb-form-native']",266,False,0,0
How to create one &quot;unit&quot; test per query to display the result in the Test Explorer,"<p>Right now my job is to test all the queries stored in a database, and display the result in the <em>Test Explorer</em>, I've managed to test every query (I just run it, check for errors and store a custom error message for each error in a text file so it work for now but the output is not as I want it to be).</p>

<p><strong>DISCLAMER</strong><br>
I guess unit testing may not be the smartest way to test the queries but that is the way i was asked to do it so I'm giving it a try.</p>

<p>The thing is that I test all queries within one <code>[TestMethod]</code> and the result look like this : (only one test method in the <em>Test Explorer</em>)</p>

<p><a href=""https://i.stack.imgur.com/cCFrK.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/cCFrK.png"" alt=""Test explorer result""></a></p>

<p>But I would want to know if it is possible to have multiple <code>[TestMethod]</code>, so we can see which methods work and which don't within the <em>Test Explorer</em>.</p>

<p><a href=""https://i.stack.imgur.com/ARRj8.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ARRj8.png"" alt=""Test explorer result 2""></a></p>

<p>My researches led me to this code :</p>

<pre><code>[TestMethod]
[DataSource(""System.Data.SqlClient"",
            @""Data Source=****;Initial Catalog=****;Persist Security Info=True;User ID=sa;Password=****;Pooling=False"",
            ""Query"",
            DataAccessMethod.Sequential)]    // My DataSource works
public void MyTestMethod()
{
        var q = new QueryDto
        {
            // Create my query with the Id, Name, Query, Parameters...
        };

        ExecTest(q);
}

public void ExecTest(QueryDto query)
{
       // my testing here
}
</code></pre>

<p>I've tried adding <code>[TestMethod]</code> to the <code>ExecTest()</code> method but it did not helped very much with what I'm trying to achieve.</p>

<p>So please tell me if what I'm looking for is <strong>possible</strong>, and if it is, how to do it.</p>

<p>Feel free to ask questions \ edit I'll stay tuned so you don't have to wait if you try to help me.</p>

<h2>EDIT</h2>

<p>I'm posting another question because this one have some mistakes
Thanks for the help btw ^^.</p>
",https://stackoverflow.com/questions/56337404/how-to-create-one-unit-test-per-query-to-display-the-result-in-the-test-explor,"['c#', 'visual-studio', 'unit-testing']",180,True,1,1
Why are the bit patterns not matching with the use of std::bitset,"<p>While I was unit testing my class and its constructors I noticed something peculiar with my outputs. </p>

<pre><code>#include &lt;bitset&gt;
#include &lt;cstdint&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;

typedef std::uint8_t u8;
typedef std::uint16_t u16;
typedef std::uint32_t u32;
typedef std::uint64_t u64;

struct Reg8 {
    std::bitset&lt;8&gt; bits;
    u8 value;

    Reg8() : value{0}, bits{value} {}

    explicit Reg8( u8 val) : value{val}, bits{value} {}
    explicit Reg8(u16 val) : value{static_cast&lt;u8&gt;(val)}, bits{value} {}
    explicit Reg8(u32 val) : value{static_cast&lt;u8&gt;(val)}, bits{value} {}
    explicit Reg8(u64 val) : value{static_cast&lt;u8&gt;(val)}, bits{value} {}    
};

int main() {
    u8  val8  = 24;
    u16 val16 = 24;
    u32 val32 = 24;
    u64 val64 = 24;

    Reg8 r8a(val8);
    Reg8 r8b(val16);
    Reg8 r8c(val32);
    Reg8 r8d(val64);

    std::cout &lt;&lt; ""Reg8(u8)  r8a value = "" &lt;&lt; +r8a.value &lt;&lt; '\n';
    std::cout &lt;&lt; ""Reg8(u8)  r8a bits  = "" &lt;&lt; r8a.bits &lt;&lt; ""\n\n"";

    std::cout &lt;&lt; ""Reg8(u16) r8b value = "" &lt;&lt; +r8b.value &lt;&lt; '\n';
    std::cout &lt;&lt; ""Reg8(u16) r8b bits  = "" &lt;&lt; r8b.bits &lt;&lt; ""\n\n"";

    std::cout &lt;&lt; ""Reg8(u32) r8c value = "" &lt;&lt; +r8c.value &lt;&lt; '\n';
    std::cout &lt;&lt; ""Reg8(u32) r8c bits  = "" &lt;&lt; r8c.bits &lt;&lt; ""\n\n"";

    std::cout &lt;&lt; ""Reg8(u64) r8d value = "" &lt;&lt; +r8d.value &lt;&lt; '\n';
    std::cout &lt;&lt; ""Reg8(u64) r8d bits  = "" &lt;&lt; r8d.bits &lt;&lt; ""\n\n"";

    std::bitset&lt;8&gt; bitsA{ val8 };
    std::cout &lt;&lt; ""bits value  = "" &lt;&lt; bitsA.to_ullong() &lt;&lt; '\n';
    std::cout &lt;&lt; ""bits binary = "" &lt;&lt; bitsA &lt;&lt; ""\n\n"";

    std::bitset&lt;8&gt; bitsB{ val16 };
    std::cout &lt;&lt; ""bits value  = "" &lt;&lt; bitsB.to_ullong() &lt;&lt; '\n';
    std::cout &lt;&lt; ""bits binary = "" &lt;&lt; bitsB &lt;&lt; ""\n\n"";

    std::bitset&lt;8&gt; bitsC{ val32 };
    std::cout &lt;&lt; ""bits value  = "" &lt;&lt; bitsC.to_ullong() &lt;&lt; '\n';
    std::cout &lt;&lt; ""bits binary = "" &lt;&lt; bitsC &lt;&lt; ""\n\n"";

    std::bitset&lt;8&gt; bitsD{ val64 };
    std::cout &lt;&lt; ""bits value  = "" &lt;&lt; bitsD.to_ullong() &lt;&lt; '\n';
    std::cout &lt;&lt; ""bits binary = "" &lt;&lt; bitsD &lt;&lt; ""\n\n"";

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

<p>Here is my output coming from a little endian machine and
Intel Quad Core Extreme running Windows 7 x64 and using 
Visual Studio 2017 CE in x64 debug mode with compiler language options set to c++ latest draft standard. All other compiler flags - optimizations etc Visual Studio's defaults.</p>

<pre><code>Reg8(u8)  r8a value = 24
Reg8(u8)  r8a bits  = 11001100

Reg8(u16) r8b value = 24
Reg8(u16) r8b bits  = 11001100

Reg8(u32) r8c value = 24
Reg8(u32) r8c bits  = 11001100

Reg8(u64) r8d value = 24
Reg8(u64) r8d bits  = 11001100

bits value  = 24
bits binary = 00011000

bits value  = 24
bits binary = 00011000

bits value  = 24
bits binary = 00011000

bits value  = 24
bits binary = 00011000
</code></pre>

<p>So why do the bit patterns from the class construction not match that of the ones declared in main?</p>

<p>I'm using the same variable types and values to initialize the bitset that is in main as well as the one in my class yet their bit patterns don't match up. All of the ones in the class are the same, all the ones outside of the class are the same. </p>

<p>What I'm expecting to see and my desired values should be that of the ones seen in main. When I look at the bottom half of the output these bitset variables in main have the value of 24
and their bit patterns match that of 24 for 8 bits.</p>

<pre><code>0001 1000 = 24
</code></pre>

<p>However the bit pattern that is stored in the bitset within my class does not match but contains the appropriate value. The bitset stored in my class has bitt pattern</p>

<pre><code>1100 1100  ... doesn't = 24 in binary
</code></pre>

<p>What is going on here?</p>
",https://stackoverflow.com/questions/56100474/why-are-the-bit-patterns-not-matching-with-the-use-of-stdbitset,"['c++', 'output', 'c++17', 'std-bitset']",154,True,1,1
Mockito JUnit test for simple api call,"<p>I consider myself a novice at unit-testing, completely new to Mockito and junit. I have to write unit-tests for some simple api-calls. But my test seems somewhat pointless to me, I can't tell where I am going wrong. I have added a method to an existing web-service, ManagerWS.java , See Below.</p>

<p><strong>ManagerWS.java Method:</strong></p>

<pre><code>public String healthCheck(String userId) { 
    String healthCheckUrlEndpoint  = this.baseUrl()+""/health"";
    logger.debug(""Calling health check: {}"", healthCheckUrlEndpoint);
    HttpHeaders healthCheckHeaders = new HttpHeaders();
    healthCheckHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
    healthCheckHeaders.add(USER_KEY, userId);
    healthCheckHeaders.add(TOKEN_NAME, TOKEN_VALUE);
    healthCheckHeaders.add(Constants.ACCEPT_LANGUAGE_HEADER, LocaleContextHolder.getLocale().toString());
    healthCheckHeaders.add(CORRELATION_HEADER, myService.get(AppLoggingMDCService.LOG_KEY_REQUEST_ID));
    HttpEntity&lt;Object&gt; request = new HttpEntity&lt;Object&gt;(healthCheckHeaders);
    ResponseEntity&lt;String&gt; response;        
    try {
        response = makeRequest(HttpMethod.GET, healthCheckUrlEndpoint, request, String.class); 
    } catch (Exception e) {
        logger.error(""Exception encountered during health check"", e);
        throw e;
    }       
    logger.debug(""RESPONSE : http status: {} - body: {}"", response.getStatusCode(), response.getBody());
    return response.getStatusCode().toString();
}
</code></pre>

<p>The logic is simple. Construct the url, create headers and add headers to the request. make the request and extract the status-code from the response. Here is my test. NOTE: the class is using <strong>@RunWith(SpringRunner.class)</strong> and I am using <strong>@Mock for dependencies</strong> and <strong>@InjectMocks for the local instance ManagerWS</strong>. ManagerWS.java is the service calss being tested.</p>

<p><strong>TEST-CLASS TEST-Method:</strong></p>

<pre><code>    @Test
    public void testHealthCheck() throws Exception {
    //Given
    managerWS = new ManagerWS(templateFactory, configParamService, mdcService, env);    
    String url = ""http://baseurl/health"";
    HttpHeaders headers = new HttpHeaders();    
    HttpEntity&lt;Object&gt; request = new HttpEntity&lt;Object&gt;(headers);   
    ResponseEntity&lt;String&gt; response = new ResponseEntity&lt;&gt;(HttpStatus.OK);
    //when
    when(managerWS.makeRequest(HttpMethod.GET, url, request, String.class)).thenReturn(response);
    String actualStatus = response.getStatusCode().toString();  
    //then
    Assert.assertEquals(""200"",actualStatus);
}
</code></pre>

<p>To me this test seems stupid (<em>for want of a batter word</em>). I basicall set the status to give a ""200"" and assert that what i set is ""200"". That is not really making much sense.To me it literally does nothing. I tried using spy(ManagerWS.class). But I am literally grasping at straws without the full understanding. </p>

<p>SonarQube still complains with ""Not covered by unit tests"". I cam completely stumped as to how else to write this test. I also have to do similar tests for three other calls.</p>

<p>I am a total novice to testing and I cannot see my mistake. Please advise.</p>
",https://stackoverflow.com/questions/57542316/mockito-junit-test-for-simple-api-call,"['java', 'unit-testing', 'junit', 'sonarqube', 'mockito']",3268,True,1,1
How to fake service injected in a component that makes HTTP calls?,"<p>I am new to Angular and trying to learn unit testing. I have a very simple component, that depends on a service (<strong>UserService</strong>). In the <strong>ngOnInit()</strong> life cycle hook, I am calling a method of the service and storing the data it returns in a property. In my view, I have a list bound to this property. </p>

<p>This is the code of my component.</p>

<pre><code>import { Component, OnInit } from ""@angular/core"";
import { UserService } from ""../services/user.service"";
import { User } from ""./models/user"";

@Component({
 selector: ""app-home"",
 templateUrl: ""./home.component.html"",
 styleUrls: [""./home.component.css""]
})
export class HomeComponent implements OnInit {
 users: User[] = [];
 constructor(private userService: UserService) {}

 ngOnInit() {
   this.userService.getUsers().subscribe(x =&gt; {
     this.users = x;
   });
 }
}
</code></pre>

<p>This is the HTML</p>

<pre><code>&lt;ul&gt;
  &lt;li *ngFor=""let user of users"" class=""user-item""&gt;{{ user.name }}&lt;/li&gt;
&lt;/ul&gt;
</code></pre>

<p>User service looks like this</p>

<pre><code>import { Injectable } from ""@angular/core"";
import { HttpClient } from ""@angular/common/http"";
import { User } from ""../home/models/user"";

@Injectable({
  providedIn: ""root""
})
export class UserService {
  private baseUrl = ""https://jsonplaceholder.typicode.com"";
  constructor(private http: HttpClient) {}

  getUsers() {
    return this.http.get&lt;User[]&gt;(`${this.baseUrl}/users`);
  }
}
</code></pre>

<p>Everything works as expected. I am trying to write some unit tests for this component. I have created some fake data</p>

<pre><code>import { User } from ""../home/models/user"";

export const FakeData = {
  users: &lt;User[]&gt;[
    {
      id: 1,
      name: ""User 1"",
      username: ""User1"",
      email: ""User1@fakemail.com"",
      phone: ""123 456 789"",
      website: ""afraz.com""
    },
    {
      id: 1,
      name: ""User 2"",
      username: ""User2"",
      email: ""User2@fakemail.com"",
      phone: ""123 456 789"",
      website: ""afraz.com""
    }
  ]
};
</code></pre>

<p>These are the tests that I have added</p>

<pre><code>import {
  async,
  ComponentFixture,
  TestBed,
  fakeAsync,
  flush
} from ""@angular/core/testing"";
import { HttpClientModule } from ""@angular/common/http"";

import { HomeComponent } from ""./home.component"";
import { UserService } from ""../services/user.service"";
import { of } from ""rxjs"";
import { FakeData } from ""../fakes/fake-data"";
import { By } from ""@angular/platform-browser"";

describe(""HomeComponent"", () =&gt; {
  let component: HomeComponent;
  let fixture: ComponentFixture&lt;HomeComponent&gt;;
  let userService: UserService;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientModule],
      declarations: [HomeComponent],
      providers: [UserService]
    }).compileComponents();
  }));

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

    // Mock the user service
    userService = TestBed.get(UserService);
    spyOn(userService, ""getUsers"").and.returnValue(of(FakeData.users));
  });

  afterEach(() =&gt; {
    fixture.destroy();
    component = null;
  });

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

  it(""should get 'Users' from the service"", fakeAsync(() =&gt; {
    fixture.whenStable().then(() =&gt; {
      expect(component.users.length).toEqual(2);
    });
  }));

  it(""should bind 'Users' to the view"", fakeAsync(() =&gt; {
    fixture.whenStable().then(() =&gt; {
      const userList = fixture.debugElement.queryAll(By.css("".user-item""));
      expect(userList.length).toEqual(2);
    });
  }));
});
</code></pre>

<p>Now here is where I am confused, I am getting following error in the output</p>

<p><em>'Spec 'HomeComponent should bind 'Users' to the view' has no expectations.'</em></p>

<p><em>'Spec 'HomeComponent should get 'Users' from the service' has no expectations.'</em></p>

<p>The problem is that if I use <strong>Async</strong> instead of <strong>fakeAsync</strong> then the actual User Service is called, and I do not want to do that. My expectation is that since I have the following line of code </p>

<p><code>spyOn(userService, ""getUsers"").and.returnValue(of(FakeData.users));</code></p>

<p>in the <strong>beforeEach()</strong> block, therefore the actual code should not be executed and instead this hard coded data should be returned. Can anyone please help and explain what am I missing?</p>

<p><strong>UPDATE: Here is my final working code of the tests.</strong> Thanks for the quick help! Hopefully it will help someone else as well :)</p>

<pre><code>import { async, ComponentFixture, TestBed } from ""@angular/core/testing"";

import { HomeComponent } from ""./home.component"";
import { UserService } from ""../services/user.service"";
import { of } from ""rxjs"";
import { FakeData } from ""../fakes/fake-data"";
import { By } from ""@angular/platform-browser"";

describe(""HomeComponent"", () =&gt; {
  let component: HomeComponent;
  let fixture: ComponentFixture&lt;HomeComponent&gt;;
  let userServiceSpy: jasmine.SpyObj&lt;UserService&gt;;

  beforeEach(async(() =&gt; {
    userServiceSpy = jasmine.createSpyObj([""getUsers""]);

    TestBed.configureTestingModule({
      imports: [],
      declarations: [HomeComponent],
      providers: [{ provide: UserService, useValue: userServiceSpy }]
    }).compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    userServiceSpy.getUsers.and.returnValue(of(FakeData.users));
    fixture.detectChanges();
  });

  afterEach(() =&gt; {
    fixture.destroy();
    component = null;
  });

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

  it(""should have 'Users' populated"", () =&gt; {
    expect(component.users.length).toEqual(2);
  });

  it(""should bind 'Users' to the view"", () =&gt; {
    const userList = fixture.debugElement.queryAll(By.css("".user-item""));
    expect(userList.length).toEqual(2);
  });
});
</code></pre>
",https://stackoverflow.com/questions/58297362/how-to-fake-service-injected-in-a-component-that-makes-http-calls,"['angular', 'typescript', 'jasmine', 'angular8']",1268,True,1,1
How to add random ticks on a line chart at a specific position,"<p>I am trying a plot a highchart with single series and add some points which are marked in different style on the same line.</p>

<p>For example : </p>

<p>I am trying to plot a week (date &amp; time) on x-axis and number of available hours in that week(5 days).</p>

<p>Available Hours : </p>

<ul>
<li>01/01/2019 08:00 to 10:00 </li>
<li>01/01/2019 18:00 to 21:00</li>
<li>01/02/2019 05:00 to 08:00 </li>
<li>01/02/2019 19:00 to 21:00</li>
<li>01/03/2019 21:00 to 23:00</li>
<li>01/04/2019 19:00 to 20:00</li>
<li>01/05/2019 08:00 to 21:00</li>
</ul>

<p>Reminders :</p>

<ul>
<li>01/01/2019 09:30 - Send an email with Targeted Items</li>
<li>01/03/2019 22:30 - Send the list of remaining tasks for the week</li>
<li>01/04/2019 19:30 - Complete The Pending items targeted for the week</li>
<li>01/05/2019 12:00 - Unit Testing Completed Tasks</li>
<li>01/05/2019 20:30 - Send out an email of this week's working status</li>
</ul>

<p>I am trying to plot a time series line chart and trying to add a marker for the reminder to the existing line chart at random places which has a tooltip with some information linked to it.</p>

<p>I tried to plot the line chart with 2 series but not able to achieve the expected output.
<a href=""https://jsfiddle.net/2vtyrc9q/3/"" rel=""nofollow noreferrer"">https://jsfiddle.net/2vtyrc9q/3/</a></p>

<pre><code>[JSFiddle Demo][1]
</code></pre>

<p><a href=""https://i.stack.imgur.com/CU9O9.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/CU9O9.jpg"" alt=""expected output""></a></p>
",https://stackoverflow.com/questions/55950032/how-to-add-random-ticks-on-a-line-chart-at-a-specific-position,"['javascript', 'angular', 'highcharts', 'highcharts-ng']",101,True,1,1
Create sub functions that can be called by dot notation,"<p><strong>Background:</strong>
Building on this question about <a href=""https://stackoverflow.com/questions/55268087/how-to-expose-external-library-in-browser-so-jest-unit-tests-can-see-it"">how to expose a library for unit testing with Jest</a>.  I would now like to create a class of functions that can be called with dot notation inside of dot notation (<em>this may not even be possible</em>).  First a bit of methodology that I'm currently using:</p>

<p>Here's an example of how I've been modifying the JavaScript Math functions:</p>

<pre><code>Math.mean = function(numericArray){
    if(Math.isNumericArray(numericArray)){
        return math.mean(numericArray);
    }
    return false;
}
</code></pre>

<p>FYI, The lowercase math.mean() call is to the math library: <a href=""https://mathjs.org/"" rel=""nofollow noreferrer"">https://mathjs.org/</a>, and isNumericArray is just a validator to make sure what's passed in is a numeric array.</p>

<p>And then I export it like this:</p>

<pre><code>module.exports.mean = exports = Math.mean;
</code></pre>

<p>So Jest can see it for my unit tests.</p>

<p><strong>My actual question:</strong>
What I want to do is create an upper level ""class"" called Math.acs, so you'd make the call into it with Math.acs.  Then it would have sub-functions (EG: foo() &amp; bar()) so you'd call them like this:  Math.acs.foo(data); or Math.acs.bar(data);  </p>

<p>I've tried to <a href=""https://stackoverflow.com/questions/10204420/define-function-within-another-function-in-javascript"">encapsulate them into an IIFE</a>:</p>

<pre><code>Math.acs = (function(data) {
    function foo(data){
        console.log('hi mom');
    };
    function bar(data){
        console.log(""hi dad"");
    }
    return bar;
})();
</code></pre>

<p>Which didn't work (the CLI can't see anything below Math.acs), I've also tried straight functions inside of functions which also didn't work.  </p>

<p>I'm not going to die if this isn't possible, but it would make the half dozen or so functions required in the acs module centralized and easier to maintain.  If it's not possible, I can write the individual math modules the same way I've shown above.</p>
",https://stackoverflow.com/questions/55857281/create-sub-functions-that-can-be-called-by-dot-notation,"['javascript', 'function']",170,True,1,1
How to unittest specific implementation,"<p>I am reading a lot about (unit)testing and I try to implement as much as possible in my day-to-day workflow, but somehow I have the feeling I am doing something wrong.</p>

<p>Let's say I have a function which takes a path and based on some elements of this path it creates a name for a new log file. The path could be <code>C:/my_project/dir_1/message01</code> and it should convert this to <code>dir_1_log_01.txt</code>. The name of the function is <code>convertPathToLogfileName</code>.</p>

<p>If I would want to write a unittest for this function it could look like:</p>

<pre class=""lang-python prettyprint-override""><code>def test_convertPathToLogfileName():   
    path = ""C:/my_project/dir_1/message01""

    expected = ""dir_1_log_01.txt""
    actual = convertPathToLogFileName(path)

    assertEqual(expected, actual)
</code></pre>

<p>Now I could write a bunch of tests like these to check for all different kinds of inputs if the output is what I expect it to be.</p>

<p>But what if at one point I decide that the naming convention for the logfile I chose is not what I want anymore: I would change the function to make it implement my new requirement and all the tests would fail.</p>

<p>This is just a simple example, but I feel that often this is the case. While I'm programming I come up with a new way of doing something and then my test fail.</p>

<p>Is there something I am missing here, am I testing the wrong thing? And if so, how would you approach this situation? Or is this just the way it is and should I accept this? </p>
",https://stackoverflow.com/questions/58289696/how-to-unittest-specific-implementation,"['unit-testing', 'testing', 'tdd', 'software-design', 'software-quality']",64,True,0,2
How Do You Test Method For Thread Safety With JUnit,"<p>I have a implemented a class that acts as a Cache for objects. It has a DelayQueue for removing objects from cache. </p>

<pre><code>class mySingletonClass {
  ConcurrentHashMap map&lt;String,MyObject&gt;();
  DelayQueue queue &lt;MyObject&gt;(); 

  boolean alreadySeen(MyObject myObject) {
    MyObject obj = map.putIfAbsent(myObject.getID(),myObject);
    if(obj != null) return true;
    queue.add(myObject);
    return false;
}
</code></pre>

<p>It works fine for single threaded. I am trying to test it with multiple threads concurrently. I have tried to reason about if this method is thread safe but I am unsure. I have tried the static analyzer FindBugs plugin. I am unsure how to unit test this. I have never used java.util.concurrent nor worked with threads so I am trying to learn it all relatively quickly. </p>

<p>My thoughts for unit testing were create an AtomicInteger and run multiple threads trying to add the same object to the map. If the method returns true increment the integer. This integer should equal one if successful.
As my second test I was thinking similarly with AtomicInteger try to have maybe 10? threads with each thread adding a list of 5 unique objects and ensure the total after all threads are done is 5.</p>

<p>I have been playing with Executors and creating Runnable methods but I am getting NullPointerExceptions and I am not sure exactly what I am doing.</p>

<p>I'm looking for:</p>

<ol>
<li><p>Is this method thread safe? If not is there a way to make it thread safe (other than just making the method synchronized)?</p></li>
<li><p>How to I implement the two unit tests with multiple threads in junit4?</p></li>
</ol>
",https://stackoverflow.com/questions/54404349/how-do-you-test-method-for-thread-safety-with-junit,"['java', 'multithreading', 'junit', 'concurrency']",56,False,0,0
Extending AutoDerivation in Circe does not work,"<p>My question concerns the second solution offered by mixel here: <a href=""https://stackoverflow.com/questions/39648511/scala-circe-with-generics"">Scala Circe with generics</a></p>

<p>Note that the trait named Auto in Circe has been renamed to AutoDerivation in the current version of Circe.</p>

<p>I am using the solution mixel provides in his StackOverflow solution but have not been able to get it to work. I have tried things like updating my Circe version to the most recent one and making sure the Macro Paradise plugin is imported, but still no luck.</p>

<p>Here is my code. The first is its own file, called CirceGeneric.</p>

<pre><code>import io.circe._
import io.circe.parser._
import io.circe.generic.extras._

object CirceGeneric {
  trait JsonEncoder[T] {
    def apply(in: T): Json
  }

  trait JsonDecoder[T] {
    def apply(s: String): Either[Error, T]
  }

  object CirceEncoderProvider {
    def apply[T: Encoder]: JsonEncoder[T] = new JsonEncoder[T] {
      def apply(in: T) = Encoder[T].apply(in)
    }
  }

  object CirceDecoderProvider {
    def apply[T: Decoder]: JsonDecoder[T] = new JsonDecoder[T] {
      def apply(s: String) = decode[T](s)
    }
  }
}

object Generic extends AutoDerivation {
  import CirceGeneric._

  implicit def encoder[T: Encoder]: JsonEncoder[T] = CirceEncoderProvider[T]
  implicit def decoder[T: Decoder]: JsonDecoder[T] = CirceDecoderProvider[T]

}
</code></pre>

<p>The second is a method for unit testing that uses the Akka function responseAs. The method appears in a class called BaseServiceTest.</p>

<pre><code>  def responseTo[T]: T = {
    def response(s: String)(implicit d: JsonDecoder[T]) = {
      d.apply(responseAs[String]) match {
        case Right(value) =&gt; value
        case Left(error) =&gt; throw new IllegalArgumentException(error.fillInStackTrace)
      }
    }
    response(responseAs[String])
  }
</code></pre>

<p>The idea is to convert the result of responseAs[String] (which returns a string) into a decoded case class.</p>

<p>The code is not behaving as expected. Intellij does not detect any missing implicits, but when compilation time comes around, I am getting problems. I should mention that the BaseServiceTest file contains imports for CirceGeneric._ and Generic._, so a missing import statement is not the problem.</p>

<p>[error] [...]/BaseServiceTest.scala:59: could not find implicit value for parameter d: [...]CirceGeneric.JsonDecoder[T]
[error]     response(responseAs[String])</p>

<p>Either the implicit conversion from Decoder[T] to JsonDecoder[T] is not happening, or the Decoder[T] instance is not being created. Either way, something is wrong.</p>
",https://stackoverflow.com/questions/56961864/extending-autoderivation-in-circe-does-not-work,"['json', 'scala', 'circe']",324,True,0,1
How to cleanly unit test a control flow method,"<p>I have a validation method that returns true if a callback should be skipped after save on a record, otherwise it returns false. </p>

<p>The method is complex with multiple return statements if curtain conditions are true. I am lost on how to cleanly test the method and confirm that each test is testing a different condition.</p>

<p>I am using Rails and Minitest, but believe that this is a general question about unit testing that could apply to other languages and/or test frames.</p>

<p>I have tried testing the method and ended up with a mess.</p>

<ul>
<li>return true if no fields of interest have changed and not a bulk_association</li>
<li>return true if bulk association but no associated user</li>
<li>return true if  bulk association, and associated user, but not active</li>
<li>return false if bulk association and associated active user</li>
<li>return false if attribute_a has changed and associated active user</li>
<li>return false if attribute_b has changed and associated active user</li>
<li>return false if attribute_c has changed and associated active user</li>
</ul>

<p>Each test required more setup, and there was no way for me to prove that they where not all returning true on the same line.</p>

<pre><code>def skip_callback
  return true unless (self.attribute_a_changed? || self.attribute_b_changed? || self.attribute_c_changed? || self.bulk_association == true)

  user = self.user
  return true if user.blank?
  return true unless user.active
  false
end
</code></pre>

<p>How should a method like this be tested? I am trying to write good unit tests that are readable, independent, and truthful so if I comment a return out the correct test should fail.</p>
",https://stackoverflow.com/questions/55981816/how-to-cleanly-unit-test-a-control-flow-method,"['ruby', 'unit-testing', 'minitest']",459,False,0,2
Is MOCKING really useful apart from isolating dependent component testing?,"<p>So i am developing a security library for Wordpress. Basically building on top of a wordpress core component called <a href=""https://codex.wordpress.org/WordPress_Nonces"" rel=""nofollow noreferrer"">Wordpress nonces</a><br>
Everything seems to be fine.<br>
Come back to the best practices, i have written a unit testing suite along with the library.<br>
Since my library extends the wordpress noces api, <code>wordpress</code> is clearly a dependency in my library.</p>

<p>To achieve isolation when testing my library i used <code>PHPUnit's mockBuilder</code> so i can instantiate my dependency class instead of actually instantiating it because it calls an external dependency(<code>wordpress nonce api</code>).<br>
Below is my Test class, </p>

<pre><code>&lt;?php
namespace nonces;

/**
 * TestWpNonce
 * Test suite for wp-clean-nonces library
 *
 * Wp-clean-nonces is A clean OOP implementation of the Wordpress Nonce library.
 * Copyright (C) 2019  Salim Said.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * For the complete terms of the GNU General Public License, please see this URL:
 * http://www.gnu.org/licenses/gpl-2.0.html

 * @category  NA
 * @package   NA
 * @author    Salim Said &lt;saliimsaid@gmail.com&gt;
 * @copyright 2019 Salim Said
 * @license   GPL-2.0+ &lt;http://www.gnu.org/licenses/gpl-2.0.html&gt;
 * @link      ****
 */

if(file_exists('../vendor/autoload.php'))
require_once '../vendor/autoload.php';

use PHPUnit\Framework\TestCase;
class TestWpNonce extends TestCase
{
    /**
     * This test will create a nonce for a url and verify if a correct
     * url is returned
     *
     * The method asserts for the result returned by createTokenUrl()
     * against a predefined expected return value containing a nonce
     * protected string url
     *
     * @return void
     */
    public function testCreateTokenUrl()
    {
        $wpNonce = $this-&gt;getMockBuilder(WPNonce::class)
            -&gt;getMock();

        $wpNonce-&gt;expects($this-&gt;once())
            -&gt;method('createTokenUrl')
            -&gt;with($this-&gt;equalTo(""inpsyde.com?action=publish_postid=2""))
            -&gt;will($this-&gt;returnValue('inpsyde.com?action=publish_postid=2&amp;token=297d58f6ae'));

        $this-&gt;assertEquals(
            ""inpsyde.com?action=publish_postid=2&amp;token=297d58f6ae"",
            $wpNonce-&gt;createTokenUrl(""inpsyde.com?action=publish_postid=2"")
        );
    }
}
</code></pre>

<p>Look at the <code>testCreateTokenUrl()</code> method; it creates a mock for the <code>WPNonce</code> class, and calls the class method <code>createTokenUrl()</code> . This is where things starts to get interesting.  </p>

<p>I am defining the input parameter like so <code>with($this-&gt;equalTo(""inpsyde.com?action=publish_postid=2""))</code> and also explicitly expecting a return value as in <code>-&gt;will($this-&gt;returnValue('inpsyde.com?action=publish_postid=2&amp;token=297d58f6ae'));</code>  </p>

<p>The <code>assertEquals()</code> method will check if the returned value is what i set in the preceding code. </p>

<p>This code helps me test the <code>createTokenUrl()</code> in isolation, it doesn't require wordpress(my library's dependency in this case). I can successfully get passing tests without having wordpress installed. That's fine but really what is the whole point of mocking project dependencies if the mock is actually a dummy test that is hard coded with arguments and return types ?</p>

<p>Is there a point of mocking that i am missing or i don't understand ? </p>
",https://stackoverflow.com/questions/59509585/is-mocking-really-useful-apart-from-isolating-dependent-component-testing,"['php', 'wordpress', 'unit-testing', 'testing', 'phpunit']",52,False,0,1
When is it a good idea to define a static ruby class?,"<p>Are there some governing rules around when it makes sense to define a static class as opposed to a class that is instantiated?</p>

<p>Still puzzling over idiomatic ruby initialization vs static class definition.</p>

<p>From what I've found.</p>

<p>Static classes seem very effective.</p>

<ol>
<li>ruby is both a functional and object orientated language. it’s very possible to write both styles. a functional style is super useful for ‘functional’ things.</li>
<li>i regularly observe classes going from static to instantiated and then very quickly bloating. “now we have all this stuff.. why not do more?!“. i see instantiated classes have a natural tendency to unfortunately take expanding responsibilities.</li>
<li>i see that when a class transitions from static to instantiated we arrive at less unit testing confidence, given things at run time might change in regards to memory allocation / assignment (as in, someone could accidentally get in between instantiation and call).</li>
<li>i find that static classes are easier to read because we don’t have to juggle potential state change considerations. less mutation = less complexity.</li>
</ol>

<p>For me. The big issues are:</p>

<ol>
<li>Classes doing more than one thing.</li>
<li>Instability in patterns across large old ruby code bases. </li>
</ol>

<p>To address these 2 concerns, I’m thinking a static approach (where possible) seems to put a healthy amount of pressure on the code to adhere to SOLID principles.</p>

<p>Static</p>

<pre><code>Serializer.transform(fruit:)
</code></pre>

<p>Instantiated</p>

<pre><code>Serializer.new(fruit:).transform
</code></pre>

<p>What drives you to go static in ruby?</p>
",https://stackoverflow.com/questions/56452307/when-is-it-a-good-idea-to-define-a-static-ruby-class,"['ruby', 'ruby-on-rails-3', 'static', 'backend']",306,True,-1,3
Spring - Integration test - cant connect to secured Websocket,"<p>I have a Spring Boot 2.2 MVC application with Spring-Security / Session and Spring-Websocket.<br>
It's configured to only allow websocket connections when authenticated.  </p>

<p>Following is the recommended way to create a Websocket Client in unit testing. (At least i have seen this in the spring docs)</p>

<pre class=""lang-java prettyprint-override""><code>private StompSession createWebsocket() throws InterruptedException, ExecutionException, TimeoutException {

    List&lt;Transport&gt; transports = new ArrayList&lt;&gt;(1);
    transports.add(new WebSocketTransport(new StandardWebSocketClient()));
    WebSocketStompClient stompClient = new WebSocketStompClient(new SockJsClient(transports));
    stompClient.setMessageConverter(new MappingJackson2MessageConverter());

    StompSession stompSession = stompClient.connect(""ws://localhost:"" + port + ""/app"",  new  StompSessionHandlerAdapter() {}).get(1, SECONDS);
    return stompSession;
}

</code></pre>

<h2>The Problem</h2>

<p>But, this way i get the exception in the logs, because Spring redirects to the Login page, which is in general ok and desired, because the Websocket Request was unauthenticated.<br>
The logs confirm:</p>

<pre><code>
2019-11-12 18:03:32.487 DEBUG 19592 --- [o-auto-1-exec-3] o.s.s.w.u.m.AndRequestMatcher            : All requestMatchers returned true
2019-11-12 18:03:32.487 DEBUG 19592 --- [o-auto-1-exec-3] o.s.s.w.DefaultRedirectStrategy          : Redirecting to 'http://localhost:51599/login'
...
2019-11-12 18:03:32.513 DEBUG 19592 --- [o-auto-1-exec-4] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2019-11-12 18:03:32.514 ERROR 19592 --- [cTaskExecutor-1] o.s.w.s.s.c.DefaultTransportRequest      : No more fallback transports after TransportRequest[url=ws://localhost:51599/app/299/6928331c14b94beba4315294661970c3/websocket]
javax.websocket.DeploymentException: The HTTP response from the server [200] did not permit the HTTP upgrade to WebSocket
    at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServerRecursive(WsWebSocketContainer.java:437) ~[tomcat-embed-websocket-9.0.27.jar:9.0.27]
    at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServerRecursive(WsWebSocketContainer.java:395) ~[tomcat-embed-websocket-9.0.27.jar:9.0.27]
    at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:197) ~[tomcat-embed-websocket-9.0.27.jar:9.0.27]
    at org.springframework.web.socket.client.standard.StandardWebSocketClient.lambda$doHandshakeInternal$0(StandardWebSocketClient.java:151) ~[spring-websocket-5.2.0.RELEASE.jar:5.2.0.RELEASE]
    at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264) [?:?]
    at java.util.concurrent.FutureTask.run(FutureTask.java) [?:?]
    at java.lang.Thread.run(Thread.java:844) [?:?]

</code></pre>

<p>While nowhere is documented how to authenticate a websocket client, other then with session header, I tried to manually login, retrieve the session cookie to set it in the WS Connection / Handshake Headers, with no luck, because it seems the MockMvc does not store or set any cookies in the headers.</p>

<pre class=""lang-java prettyprint-override""><code>
@Test
public void test() throws Exception {
    MockMvc mockMvc = MockMvcBuilders
        .webAppContextSetup(wac)
        //.addFilters(springSecurityFilterChain) // same result
        .apply(springSecurity())
        .build();

    MvcResult response = mockMvc.perform(formLogin(""/perform_login"")
        .user(""email"", ""user@test.com"")
        .password(""pw"", ""test123""))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(cookie().exists(""JSESSIONID"")) // Test is failing here
        .andReturn();
}

</code></pre>

<p>Output from request print:  </p>

<pre><code>
MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /perform_login
       Parameters = {email=[user@test.com], pw=[test123], _csrf=[933cd6ad-0c81-4539-82a5-b184babcad84]}
          Headers = [Accept:""application/x-www-form-urlencoded""]
             Body = &lt;no character encoding set&gt;
    Session Attrs = {userid=88, SPRING_SECURITY_CONTEXT=org.springframework.security.core.context.SecurityContextImpl@c08a487f: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@c08a487f: Principal: com.package.UserDetails@7ca802e3; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: FULL_AUTH, username=user@test.com}

Handler:
             Type = null

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 = [X-Redirect:""/"", Content-Type:""application/json"", X-Content-Type-Options:""nosniff"", X-XSS-Protection:""1; mode=block"", Cache-Control:""no-cache, no-store, max-age=0, must-revalidate"", Pragma:""no-cache"", Expires:""0"", X-Frame-Options:""DENY""]
     Content type = application/json
             Body = {""code"":200, ""status"":""ok""}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

</code></pre>

<p>The Application works like a charm, Login is working and websocket is working too.<br>
The normal Login responds with a cookie and everything is fine.</p>

<h2>Questions</h2>

<ol>
<li>How can i authenticate the websocket client in an JUnit Test scenario with a given user in an elegant (spring) way?</li>
<li>How can i get the session id from MockMVC result to successfully connect with websocket (by inserting cookie in handshake/upgrade headers)?</li>
<li>Is there an other way testing secured websocket?  </li>
</ol>

<h2>Known related SO-Topics:</h2>

<p><a href=""https://stackoverflow.com/questions/53105701/the-http-response-from-the-server-200-did-not-permit-the-http-upgrade-to-webso"">Same exception with Websocket connection (but no answers)</a><br>
<a href=""https://stackoverflow.com/questions/28231336/unit-testing-login-in-spring-mvc-using-mockmvc"">Same behaviour with MockMVC-Cookies (none of the answers worked)</a></p>
",https://stackoverflow.com/questions/58825489/spring-integration-test-cant-connect-to-secured-websocket,"['java', 'spring', 'unit-testing', 'session-cookies', 'spring-websocket']",777,False,6,0
Testing Django Apps On Heroku With Cypress,"<p>I'm a hobby web developer looking to build my first product with the django web framework which I will host on Heroku.  Cypress looks like a great modern tool for UI testing which I certainly want to use.  In local development I am using it within django testing so that the django staticliveservertestcase runs first - which creates a separate development server process, and a test database, if one hasn't been created already.  Within this test I then call a bash script which executes a cypress UI test.  See the example below.</p>

<p><strong>Bash Script -</strong></p>

<pre><code>#!/bin/bash

echo $1 # the 1st command line argument
echo $2 # the 2nd command line argument

./node_modules/.bin/cypress run --env baseUrl=$1 --spec $2
</code></pre>

<p><strong>Django Test Code -</strong></p>

<pre><code>class ExampleTest(StaticLiveServerTestCase):

    def test_view_url(self):
        from subprocess import run
        exit_code = run([
            './cypress/run.sh',
            f'http://{self.server_thread.host}:{self.server_thread.port}',
            'cypress/integration/sample_spec.js'
        ])
        self.assertEqual(0, exit_code.returncode)
</code></pre>

<p>From my understanding this is the opposite to the standard cypress approach.  Normally cypress runs outside of the app independently and simply runs through all the tests which interact with the app.  Here the cypress tests are called by the django process.  Unless I am mistaken there are obvious advantages to this approach.  I can test the UI and whether objects where created in the database after the UI test has run.</p>

<p>Is it possible, and if this how, to do this within Heroku?  So Heroku would simply call the test script -</p>

<pre><code>python manage.py test
</code></pre>

<p>And I get UI testing and unit testing all done in one go.  It would also be nice to see the tests running in interactive mode.  Which may be a challenge because Heroku obviously runs everything in a linux container - I don't plan on using Docker incidentally because I think that limits a lot of the features Heroku offers.</p>
",https://stackoverflow.com/questions/59519944/testing-django-apps-on-heroku-with-cypress,"['django', 'testing', 'heroku', 'integration-testing', 'cypress']",488,False,4,0
How to resolve circular dependencies inside of the service layer,"<p>I know that others already had this very same issue, but I cannot find any statisfying solution, so I'm asking here for other ideas.</p>

<p>My business logic is contained in a service layer like that:</p>

<pre><code>public class RoomService : IRoomService
{
    private readonly IRoomRepository _roomRepository;
    private readonly ICourseService _courseService;

    public RoomService(IRoomRepository roomRepository, ICourseService courseService)
    {
        _roomRepository = roomRepository ?? throw new ArgumentNullException(nameof(roomRepository));
        _courseService = courseService ?? throw new ArgumentNullException(nameof(courseService));
    }

    public Task DeleteRoomAsync(string id)
    {
        // Check if there are any courses for this room (requires ICourseService)
        // Delete room
    }
}

public class CourseService : ICourseService
{
    private readonly ICourseRepository _courseRepository;
    private readonly IRoomService _roomService;

    public CourseService(ICourseRepository courseRepository, IRoomService roomService)
    {
        _courseRepository = courseRepository ?? throw new ArgumentNullException(nameof(courseRepository));
        _roomService = roomService ?? throw new ArgumentNullException(nameof(roomService));
    }

    public Task GetAllCoursesInBuilding(string buildingId)
    {
        // Query all rooms in building (requires IRoomService)
        // Return all courses for these rooms
    }
}
</code></pre>

<p><em>This is just an example. There might be workarounds to avoid that the services depend on each other in this case, but I had multiple other situations in the past, where there wasn't any clean workaround.</em></p>

<p>As you can see, these two services depend on each other and dependency injection will fail because of the circular dependency.</p>

<p>Now I can imagine two ways to resolve this:</p>

<h2>Solution 1</h2>

<p>I could resolve the service-dependencies inside of the service methods that require them instead of injecting the service dependencies into the service constructor:</p>

<pre><code>public class RoomService : IRoomService
{
    private readonly IRoomRepository _roomRepository;
    private readonly IServiceProvider _serviceProvider;

    public RoomService(IRoomRepository roomRepository, IServiceProvider serviceProvider)
    {
        _roomRepository = roomRepository ?? throw new ArgumentNullException(nameof(roomRepository));
        _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
    }

    public Task DeleteRoomAsync(string id)
    {
        ICourseService courseService = _serviceProvider.GetRequiredService&lt;ICourseService&gt;();

        // Check if there are any courses for this room (requires ICourseService)
        // Delete room
    }
}
</code></pre>

<p><strong>Problem:</strong> This makes unit testing harder because I need to inject a mocked <code>IServiceProvider</code> that is able to resolve my <code>ICourseService</code> into the class constructor. Also it's not very clear when writing the unit tests, which services are required by each service method because that's completely implementation dependant.</p>

<h2>Solution 2</h2>

<p>The service method could require that the <code>ICourseService</code> is passed in from the controller as a method parameter:</p>

<pre><code>public Task DeleteRoomAsync(ICourseService courseService, string id)
{
    // Check if there are any courses for this room (requires ICourseService)
    // Delete room
}
</code></pre>

<p><strong>Problem:</strong> Now my controller needs to know about an implementation detail of the service method: <em><code>DeleteRoomAsync</code> requires an <code>ICourseService</code> object to do it's work.</em>
I think that's not very clean because the requirements of <code>DeleteRoomAsync</code> might change in future, but the method signature should not.</p>

<p><strong>Can you think of any alternative, cleaner solutions?</strong></p>
",https://stackoverflow.com/questions/57965397/how-to-resolve-circular-dependencies-inside-of-the-service-layer,"['c#', 'asp.net', 'asp.net-core', 'dependency-injection']",6442,True,4,3
Cloud Firestore security rules development mode,"<p>We are developing an Android app based on Cloud Firestore.</p>

<p>Now, we have released the app to production and we continue to add more features, the changes force us to add/change the Firestore security rules.</p>

<p>The question is how to test the app with new security rules but before publishing the rules to all users?</p>

<p>I see in docs that Firestore has some emulator, but I don't understand if he can help or it used only for unit testing, there are also an simulator to test single request in draft mode, but in the end of the day we need to test the functionality of the app <strong>manually</strong>.</p>

<p>In other words, is there a way to change the security rules and test the app before apply it to all users?</p>

<p>Also i have some question to those who using Firebase in production:</p>

<ol>
<li>I guess your database splitted for development and production, do you split it in same project or create 2 projects with 2 google-services.json files, if you using in same project how do you handle changes in security rules for both versions?</li>
<li>There may be changes between the app releases and data structures, but there are only one version of rules, some rules will be not compatible with another app releases, how do you handle this situation? is there way to match specific app release to specific security rules?</li>
</ol>

<p>Maybe i missing something important about Firestore.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/57972089/cloud-firestore-security-rules-development-mode,"['android', 'firebase', 'firebase-security']",2206,True,3,4
"kubernetes go-client PersistentVolumeClaim not provisioned on request, stuck in Pending state","<p>While using the go-client API after I use the <code>api.PersistentVolumeClaims(namespace).Create(createOpts)</code> call the PersistentVolumeClaim appears as a resource but stays in the Pending state.  I do not see any events when using <code>kubectl describe pvc</code>, I also don't see any Volumes being created etc.</p>

<pre><code>$ kubectl describe pvc --namespace=test -R
Name:          93007732-9d8c-406e-be99-f48faed3a061
Namespace:     test
StorageClass:  microk8s-hostpath
Status:        Pending
Volume:        93007732-9d8c-406e-be99-f48faed3a061
Labels:        &lt;none&gt;
Annotations:   &lt;none&gt;
Finalizers:    [kubernetes.io/pvc-protection]
Capacity:      0
Access Modes:  
VolumeMode:    Filesystem
Events:        &lt;none&gt;
Mounted By:    &lt;none&gt;
</code></pre>

<p>The code I am using is as follows:</p>

<pre><code>
        volume, errGo := uuid.NewRandom()                                                                                                                                                 
        if errGo != nil {                                                                                                                                                                 
                job.failed = kv.Wrap(errGo).With(""stack"", stack.Trace().TrimRuntime())                                                                                                    
                return job.failed                                                                                                                                                         
        }                                                                                                                                                                                 
        job.volume = volume.String()

        fs := v1.PersistentVolumeFilesystem
        createOpts := &amp;v1.PersistentVolumeClaim{
                ObjectMeta: metav1.ObjectMeta{
                        Name:      job.volume,
                        Namespace: job.namespace,
                        UID:       types.UID(job.volume),
                },
                Spec: v1.PersistentVolumeClaimSpec{
                        AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce},
                        Resources: v1.ResourceRequirements{
                                Requests: v1.ResourceList{
                                        v1.ResourceName(v1.ResourceStorage): resource.MustParse(""10Gi""),
                                },
                        },
                        VolumeName: job.volume,
                        VolumeMode: &amp;fs,
                },
                Status: v1.PersistentVolumeClaimStatus{
                        Phase:       v1.ClaimBound,
                        AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce},
                        Capacity: v1.ResourceList{
                                v1.ResourceName(v1.ResourceStorage): resource.MustParse(""10Gi""),
                        },
                },
        }

        api := Client().CoreV1()
        if _, errGo = api.PersistentVolumeClaims(namespace).Create(createOpts); errGo != nil {
                job.failed = kv.Wrap(errGo).With(""stack"", stack.Trace().TrimRuntime())
                return job.failed
        }

</code></pre>

<p>I have tried to find good examples for using the Create API with persistent volumes but most examples appear to be for watchers etc and so I spent quite sometime trying to reverse engineer code leading me explicitly setting the <code>Status</code> but this appears to have had zero impact.  I also tried defaulting the VolumeMode within the Spec which did not help.</p>

<p>The examples I have read come from:</p>

<p><a href=""https://github.com/kubernetes/kubernetes/blob/master/pkg/controller/volume/persistentvolume/framework_test.go"" rel=""nofollow noreferrer"">https://github.com/kubernetes/kubernetes/blob/master/pkg/controller/volume/persistentvolume/framework_test.go</a>
<br>
<a href=""https://godoc.org/k8s.io/api/core/v1#PersistentVolumeSpec"" rel=""nofollow noreferrer"">https://godoc.org/k8s.io/api/core/v1#PersistentVolumeSpec</a>
<br>
<a href=""https://github.com/vladimirvivien/k8s-client-examples/tree/master/go/pvcwatch"" rel=""nofollow noreferrer"">https://github.com/vladimirvivien/k8s-client-examples/tree/master/go/pvcwatch</a>
<br>
<a href=""https://medium.com/programming-kubernetes/building-stuff-with-the-kubernetes-api-part-4-using-go-b1d0e3c1c899"" rel=""nofollow noreferrer"">https://medium.com/programming-kubernetes/building-stuff-with-the-kubernetes-api-part-4-using-go-b1d0e3c1c899</a>
<br></p>

<p>Does anyone know of actually example code for these APIs that goes beyond unit testing within the _test.go files, or can anyone provide any hints as to how to get the creation process actually rolling within the cluster ?  I have assumed that the downstream resources needed for example the Volume etc are automatically provisioned when I attempt to create the Claim resource.</p>

<p>Many Thanks for taking a look if you got this far...</p>
",https://stackoverflow.com/questions/55367948/kubernetes-go-client-persistentvolumeclaim-not-provisioned-on-request-stuck-in,"['kubernetes', 'persistent-volume-claims', 'kubernetes-go-client']",2407,True,2,1
Allowing &quot;overriding&quot; zero-initialized object with internal linkage,"<p>I'm designing a micro-framework for unit testing and want to be able to provide an ability for client to define a ""test suite name"". So I have the following header file called <code>test_suite.h</code>:</p>

<pre><code>static const char *const test_suite_name;

static inline void run_all_tests(void){
    printf(""Running "");
    if(!test_suite_name){
        printf(""unnamed suite"");
    } else {
        printf(""%s suite"", test_suite_name);
    }
    //run tests
}
</code></pre>

<p>The intention of this is to allow clients to ""override"" the <code>test_suite_name</code> as follows:</p>

<pre><code>#include ""test_suite.h""

extern const char *const test_suite_name = ""suite1"";
</code></pre>

<p>I think <strong><em>the behavior of such usage is well-defined</em></strong> since <code>static const char *const test_suite_name;</code> constitutes a tentative-definition and then <code>extern const char *const test_suite_name = ""suite1"";</code> constitutes an external definition. There is no linkage disagreement since <code>6.2.2(p4)</code>:</p>

<blockquote>
  <p>For an identifier declared with the storage-class specifier <code>extern</code> in a
  scope in which a prior declaration of that identifier is visible,31) if
  the prior declaration specifies internal or external  linkage,  the 
  linkage  of  the  identifier  at  the  later  declaration  is  the 
  same  as  the linkage specified at the prior declaration.</p>
</blockquote>

<p>I ran some experiments:</p>

<ol>
<li><a href=""https://coliru.stacked-crooked.com"" rel=""nofollow noreferrer"">https://coliru.stacked-crooked.com</a>:</li>
</ol>

<p>Prints the following error message:</p>

<pre><code>error: redefinition of 'const char* const suite_name'
 extern const char *const suite_name = ""some suite"";
</code></pre>

<p><a href=""https://coliru.stacked-crooked.com/a/aa1464f186490bf5"" rel=""nofollow noreferrer"">DEMO</a></p>

<ol start=""2"">
<li><a href=""https://ideone.com/"" rel=""nofollow noreferrer"">https://ideone.com/</a>: </li>
</ol>

<p>Works completely fine with no warnings produced</p>

<p><a href=""https://ideone.com/awC5KJ"" rel=""nofollow noreferrer"">DEMO</a></p>

<ol start=""3"">
<li><code>gcc7.4.0</code> on my machine.</li>
</ol>

<p>Produces warning:</p>

<pre><code>warning: ‘test_suite_name’ initialized and declared ‘extern’
</code></pre>

<p><strong><em>Question:</em></strong> Is the behavior of the code shown above well-defined?</p>

<p>I'm pretty sure that the behavior would be undefined if write the following:</p>

<pre><code>#include ""test_suite.h""

const char *const test_suite_name = ""suite1""; //without extern
</code></pre>

<p>because of <code>6.2.2(p5)</code>(emphasize  mine):</p>

<blockquote>
  <p>If the declaration of an identifier for a function has no
  storage-class specifier, its linkage is  determined  exactly  as  if 
  it  were  declared  with  the  storage-class  specifier <code>extern</code>. <strong>If the
  declaration of an identifier for an object has file scope and no
  storage-class specifier, its linkage is external.</strong></p>
</blockquote>

<p>So we would have linkage disagreement between <code>static const char *const test_suite_name;</code> with internal linkage and <code>const char *const test_suite_name = ""suite1"";</code> with external linkage.</p>
",https://stackoverflow.com/questions/56365581/allowing-overriding-zero-initialized-object-with-internal-linkage,"['c', 'static', 'language-lawyer', 'extern', 'linkage']",121,True,2,1
How can I vendor a 3rd party js lib via a script tag in Ember?,"<p>I'm trying to integrate Plaid with an Ember app and am following the instructions on their site. It should be simple, the instructions say to just add</p>

<pre class=""lang-html prettyprint-override""><code>&lt;script src=""https://cdn.plaid.com/link/v2/stable/link-initialize.js"" /&gt;
</code></pre>

<p>and it'll give you a <code>Plaid</code> class that can be used to interface with Plaid.</p>

<p>That works fine, but ideally I'd like to vendor this script and import it in a service where I can do my work on it. This does not work out of the box. Unfortunately, this script <em>relies on being embedded with a script tag.</em> If you unminify the thing, there's a line where it very explicitly tries to find the script tag that embedded it, and it throws an error if it can't find it.</p>

<p>From the unminified code:</p>

<pre><code>findScriptTag: function() {
  for (var t = document.getElementsByTagName(""script""), n = 0, e = t.length; n &lt; e; n += 1)
    if (/link-initialize(\..*?)?\.js$/.test(t[n].src)) return t[n];
  throw new Error(""Failed to find script"")
</code></pre>

<p>My question is, can I configure ember to load certain vendored scripts separately from everything else, in its own script tag? I'd also need to control the name of the file, since the above expects the name to be link-initialize.js. Or is there another way around this?</p>

<p>My current workaround is to just add the script tag to index.html, but I'd really like to be able to say <code>import Plaid from 'plaid';</code>, or something close to that... Unit testing is impossible without this.</p>

<hr>

<p>To clarify: As far as I know, <strong>there is no npm package for this</strong>.
<a href=""https://www.npmjs.com/package/plaid"" rel=""nofollow noreferrer"">https://www.npmjs.com/package/plaid</a> is a backend lib that <strong>does not handle</strong> embedding Plaid on the page. It is entirely different from the link-initialize.js script the plaid docs say to embed.</p>
",https://stackoverflow.com/questions/57810778/how-can-i-vendor-a-3rd-party-js-lib-via-a-script-tag-in-ember,"['javascript', 'ember.js', 'configuration', 'plaid']",295,True,1,2
What&#39;s the Pythonic way to add a parameter to many of the function calls in my code?,"<p>I have a Python (3.6) web server using aiohttp with a lot of routes in it.  The handler in my routes usually looks like this:</p>

<pre><code>async def __call__(self, request):
    response1 = await call_service_1('aaa')
    response2 = await call_service_2('bbb')
    response3 = await call_service_3('ccc')
    return [response1, response2, response3]
</code></pre>

<p>And a service call looks like:</p>

<pre><code>async def call_service1(self, arg):
    url = 'http://localhost/' + arg
    headers = {'Content-Type': 'application/json'}
    async with self.client_session.get(url, headers=headers) as response:
        return response
</code></pre>

<p>I have a new requirement in which I need to read a header value in the request, and pass that on as a header in my subsequent service requests.  I have this requirement for all of my routes and all of my service calls.  My initial attempt to fulfil this requirement would be to change the routes to this:</p>

<pre><code>async def __call__(self, request):
    my_header_value = request.headers['my_header_value']  # new header value
    response1 = call_service_1('aaa', my_header_value)
    response2 = call_service_2('bbb', my_header_value)
    response3 = call_service_3('ccc', my_header_value)
</code></pre>

<p>And to change the service request to this:</p>

<pre><code>async def call_service1(self, arg, my_header_value):  # new parameter
    url = 'http://localhost/' + arg
    headers = {
               'Content-Type': 'application/json',
               'my_header_value': my_header_value  # new header value
    }
    async with self.client_session.get(url, headers=headers) as response:
        return response
</code></pre>

<p>I don't think this is the Pythonic way to make a change like this.  I think it's a bad design to pass this parameter around like this, from endpoint to endpoint.  I know that this is a cross-cutting concern, but I don't know the proper way to design something to handle this in Python.  I'd ultimately be copying and pasting code all over the place.  There's got to be a better way, but I don't know it and my Python isn't that strong.</p>

<p>For instance, is there some way I can decorate the service calls so that I don't have to add a new parameter all over the place?  I don't think I have access to some session variables that I can set so that I don't have to add parameters at all.  If I did however, I'd be worried about unit testing.</p>

<p>What do you recommend?</p>
",https://stackoverflow.com/questions/54875350/whats-the-pythonic-way-to-add-a-parameter-to-many-of-the-function-calls-in-my-c,['python-3.x'],24,False,1,0
ANTLR4 grammar testing methods,"<p>I am writing antlr4 grammar for a closed programming language. The application code i would be writing in python.</p>

<p>Now, i would like to unit/integration test all the grammar rules against the possible combinations of the language. For unit testing i am thinking of the below approaches. If anyone has worked on something similar can you give me directions on which method would be suitable ?</p>

<ol>
<li>Files with lots of possible combination and their respective tree output in another file.So in python i would be reading all the files generating parse tree and then comparing the tree result with the output file.</li>
<li>For every grammar rule creating a test file in that writing many methods which would give the input in string and match the tree output with string. But i am thinking this would be becoming too complex for rules supporting many combinations.It would too many test function calls and in that creating parse tree.</li>
<li>In this method it would be similar to method 2 but instead of comparing the tree strings to the output i would be checking whether each token/subrule in the grammar is identified as per the expectations or not. But over here it would be complicated for rules which are  supporting multiple options as i would need to check which option passed and then again test accordingly.</li>
</ol>

<p>Any help for this would be very much appreciated.</p>
",https://stackoverflow.com/questions/56061330/antlr4-grammar-testing-methods,"['python-3.x', 'antlr4']",669,True,1,1
Using FluentValidation in .NET Core with Dependency Injection,"<p>I have a .NET Core Web Api Application which is arranged in the following manner - </p>

<ol>
<li>Controller layer which injects Business Service</li>
<li>Business Service which injects Unit Of Work (to interact with database)</li>
<li>Business Service might also make a call to a FluentValidation class</li>
<li>FluentValidation will inject the Unit Of Work to perform database checks (Exists, etc.)</li>
</ol>

<p>So having said all of that here is an example.  If I want to create a User in the system I have a route/method called ""PostUser"" located inside of the ""UsersController"".  The ""UsersController"" injects the ""UserService"".  The ""UserService"" has a method called ""CreateUser"".  So inside of the ""PostUser"" method of the controller it looks like this - </p>

<pre><code>var user = _userService.CreateUser(user);
</code></pre>

<p>Now inside of the ""CreateUser"" method it looks like this - </p>

<pre><code>UserValidation validation = new UserValidation(UnitOfWork, DatabaseOperation.Create);
ValidationResult validationResult = await validation.ValidateAsync(user);
</code></pre>

<p>So the UnitOfWork is passed into the UserService via dependency injection and then passed along to the FluentValidation class ""UserValidation"" so the validation class can perform database checks.  I also pass an enum into the UserValidation class to specify whether or not the validation is intended for an Update or a Create.</p>

<p>The User object I am trying to validate will have properties such as ""Role"" and ""Company"" and I also have separate validation classes for each (RoleValidation and CompanyValidation).  Both of these validation classes will also pass in a UnitOfWork and whether or not this is a create or an update.</p>

<p>Here is an example of my UserValidation Class - </p>

<pre><code>public class UserValidation : AbstractValidator&lt;UserDTO&gt; 
{
     private IUnitOfWork _unitOfWork;
     public UserValidation(IUnitOfWork unitOfWork, DatabaseOperation databaseOperation)
     {
         _unitOfWork = unitOfWork;

         if (databaseOperation == DatabaseOperation.Create)
         {
              // Do Create specific validation
         }

         RuleFor(x =&gt; x.Company)
            .SetValidator(new CompanyValidator(_unitOfWork, databaseOperation));

     }
}
</code></pre>

<p>Now understanding all of this I wanted to create Unit Tests for my ""UserService"" class. But I believe in order to properly do this I would need to Mock out the FluentValidation class in some cases and as you can see in my ""UserService"" CreateUser method I instantiate the concrete class for my Validation.  So in order to do this I would have to create an interface for each of my fluentvalidation classes and inject them into the business services that use them.  So I did the following in my Startup.cs file - </p>

<pre><code>services.AddScoped&lt;IValidator&lt;User&gt;&gt;(x =&gt; new UserValidation(x.GetRequiredService&lt;IUnitOfWork&gt;()));
</code></pre>

<p>So now after doing that I can inject the IValidator into my UserService Constructor and use that instead of instatiating a Concrete class inside of my UserService methods.</p>

<p>So with this brings me to ask the following questions.</p>

<ol>
<li>In your opinion, the way I already have my project structured, is this the best way to use dependency injection with FluentValidation and allow for unit testing of the service method along with unit testing of the FluentValidation class?</li>
<li>Is there a better way using dependency injection with FluentValidation to do all of this, and at the same time let the FluentValidation class know if it is a ""Create"" or an ""Update"", instead of creating one class called ""UserCreateValidation"" and ""UserUpdateValidation"" or passing in a variable ""DatabaseOperation"" to the constructor of the Validator?  </li>
<li>Appending to (2) when trying to setup the FluentValidation DependencyInjection I am having trouble passing in the ""DatabaseOperation"" variable<code>services.AddScoped&lt;IValidator&lt;User&gt;&gt;(x =&gt; new UserValidation(x.GetRequiredService&lt;IUnitOfWork&gt;(), &lt;How to figure out if its a create or an update&gt;));</code></li>
<li>On Top of that I will have to also add two lines to the ""Startup.cs"" file to create the Scoped DependencyInjection of the ""CompanyValidation"" and the ""RoleValidation"" to be used inside of the ""UserValidation"" and both of those validation classes will also pass in whether or not it is an update or a create.</li>
</ol>

<p>Any help/suggestions would be appreciated. I am really stuck on this issue.  If anyone needs anymore clarification on the issues I am facing please do not hesitate to ask.</p>

<p>Thank You</p>
",https://stackoverflow.com/questions/56202570/using-fluentvalidation-in-net-core-with-dependency-injection,"['c#', '.net-core', 'dependency-injection', 'fluentvalidation']",25026,True,7,1
Unit Testing Factory/Service Locator - Static class,"<p>Recently, I saw this code.  Since I am trying to learn few things at once, I am having issues with this code but dont know how to resolve.  I would like to be able to unit test this code</p>

<pre><code>public static class CarFactory
{
    private static readonly IDictionary&lt;string, Type&gt; CarsRegistry = new Dictionary&lt;string, Type&gt;();

    public static void Register&lt;TCar&gt;(string car) where TCar : CarBase, new()
    {
        if (!CarsRegistry.ContainsKey(car))
        {
            CarsRegistry.Add(car, typeof(TCar));
        }
    }

    public static ICar Create(string car)
    {
        if (CarsRegistry.ContainsKey(car))
        {
            CarBase newCar = (CarBase)Activator.CreateInstance(CarsRegistry[car]);
            return newCar;
        }

        throw new NotSupportedException($""Unknown '{car}'"");
    }
}
</code></pre>

<p>I have few problems with this code.</p>

<ol>
<li>Name is CarFactory but this does not look like a Factory Pattern to me.  It looks more like Locator Pattern</li>
<li>The class is static - and I heard static classes are bad for unit testing in frameworks like Moq and that they also hide dependencies.  Say a method in another regular class uses this, for unit test, there is no way to know that that method depend on this static class</li>
</ol>

<p>I would like to ensure this class is called properly and I think based on my reading that this is Locator Pattern.</p>

<p>I would also like to unit test this class and need help to make it unit testable using Moq.  </p>

<p>Thanks to @ErikPhillips explanation below, I now understand that other classes using this class will be not testable.  So, if I have a class like below:</p>

<pre><code>public class CarConsumer
{
   public void ICar GetRedCar()
   {
     var result = CarFactory.Create(""Tesla"");
     result.Color = Color.Red;
     return result;
   }
}
</code></pre>

<p>, GetRedCar() method will be difficult to test because it uses CarFactory static class and for a unit test or an outside client, there is nothing in GetRedCar() method API that suggest it is depending on this static class.</p>

<p><strong>I would like to refactor CarFactory class so other classes using it like in example above CarConsumer class can be tested properly.</strong>  </p>
",https://stackoverflow.com/questions/54545120/unit-testing-factory-service-locator-static-class,"['c#', 'unit-testing', 'moq', 'factory-pattern', 'service-locator']",346,True,0,1
Mapper already initialized issue when using Automapper and xUnit for unit testing,"<p>I am a bit new to unit testing with xUnit, and I have some problems with AutoMapper. I am getting the <strong>Mapper already initialized</strong> issue.</p>

<p>I am using Automapper 8.0.0., ASP.NET Core 2.2 and xUnit 2.4.1.</p>

<p>I am writing unit tests for my controllers.
I have unit tests in 3 different classes. Each class looks basically like this:</p>

<pre><code>/* Constructor */
public ControllerGetTests()
{
    /// Initialize AutoMapper
    AutoMapper.Mapper.Reset();
    MapperConfig.RegisterMaps();

    /* Some mocking code here using Moq */

    _controller = new MyController();
}


[Fact]
public async void Get_WhenCalled_ReturnsOkResult()
{
    // Act
    var okResult = await _controller.Get();

    // Assert
    Assert.IsType&lt;OkObjectResult&gt;(okResult);
}

/* etc. */
</code></pre>

<p>All three classes are similar and are basic tests for controllers.
All controllers are using AutoMapper.
I am using the same static class MapperConfig to register my mappings:</p>

<pre><code>public static class MapperConfig
{
    public static void RegisterMaps()
    {
        AutoMapper.Mapper.Initialize(config =&gt;
        {
            config.CreateMap&lt;SomeClass, SomeClassViewModel&gt;();    
            config.CreateMap&lt;SomeClassViewModel, SomeClass&gt;();

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

<p>I call this method in the constructor of each of the 3 test classes.
Before calling it, I call the Mapper.Reset() - some answers here suggest that:
<a href=""https://stackoverflow.com/questions/47241708/automapper-mapper-already-initialized-error"">Automapper - Mapper already initialized error</a></p>

<p>In the Test Explorer in VS when I select one test class and choose ""Run selected tests"", they all pass. However, when I select the main ""Run all"", some tests fail with the message <strong>Mapper already initialized</strong>. And each time it is different tests in different classes that fail. </p>

<p>I assume that different threads are created for different methods, but they are all trying to initialize the same mapper instance which throws an error.</p>

<p>However, I am not sure where am I supposed to call the initialization in one (and only one) place and have that same initialization be used for all my test classes (like I do in Startup.cs Configure method).</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/55616503/mapper-already-initialized-issue-when-using-automapper-and-xunit-for-unit-testin,"['c#', 'unit-testing', '.net-core', 'automapper', 'xunit']",2138,True,0,2
Link problems in Xcode unit test of iOS app with embedded C++ code,"<p>I'm trying to fix our unit tests. The iOS app is complex, with a number of open-source libraries statically linked into the application binary, including Google protobuf and Boost. These are built as static-link libraries in separate targets in our iOS app Project, and linked into the main app.</p>

<p>Up until now, those libraries were also linked directly into the test target, even though the app hosts the testing. But I ran into an issue early in Google Protobuf initialization that makes me think the presence of that library both in the test target and in the main application target is a problem. So I removed the static libraries from the test target, thinking that the Objective-C++ methods that reference stuff in that library would still find it in the main app executable. This does not seem to be the case, as the linker is failing to link test files that reference C++ code defined in the static library linked into the application binary.</p>

<p>Objective-C and Swift code does seem to link correctly.</p>

<p>I'm not sure what to do to resolve this situation. As I understand Xcode unit testing, one normally does not include the code of the main application in the test target. But I'm not sure how to tell Xcode that my test files need to be able to link against arbitrary code in the app.</p>

<p>This is all in Xcode 10.1.</p>
",https://stackoverflow.com/questions/55643710/link-problems-in-xcode-unit-test-of-ios-app-with-embedded-c-code,"['xcode', 'xctest', 'xcode10.1', 'xctestcase']",226,False,0,1
C# - WebDriver - MSTest framework Parallel Execution,"<p>I am currently working on C# - Webdriver - MSTest based testing framework. We are using testsettings file for enabling parallel execution. Also the tests are executed on a machine with 4 processors and we use Selenium Grid for executing the tests. Below are some of the challenges faced in over night execution. </p>

<ul>
<li>Since we have almost 100+ test cases, the time taken to complete on a single thread is around 3 hours. We wanted to reduce the execution time to nearly 15 minutes. But when we increase the thread count in testsettings file, there are lots of false failures. Is there a better way to achieve better pass rate by reducing execution time?</li>
<li>I came across some blog ""<a href=""https://blogs.msdn.microsoft.com/devops/2016/02/08/parallel-and-context-sensitive-test-execution-with-visual-studio-2015-update-1/"" rel=""nofollow noreferrer"">https://blogs.msdn.microsoft.com/devops/2016/02/08/parallel-and-context-sensitive-test-execution-with-visual-studio-2015-update-1/</a>"" which states that the number of parallel tests that can be executed is directly proportional to the number of CPU core of that machine. If this is right, with a 4 core machine, I wont be able to execute more than 4 thread at a time. Is there a way to over come this, if I use other Unit testing framework like xUnit, nUnit etc? I previously worked in Java - WebDriver using TestNG framework, and we could execute more than 15+ thread at a time. </li>
</ul>

<p>Please help if any one is working on any C# based framework and successfully execute tests in more parallel threads.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/54120428/c-webdriver-mstest-framework-parallel-execution,"['multithreading', 'selenium-webdriver', 'mstest', 'selenium-grid']",1873,False,0,1
Multiple microservices in a single dotnet core solution + git repo?,"<p>I'm looking into options for a new architecture solution for an API layer.  We have decided to use dotnet core, and we'd like to have each part of our app's functionality broken into microservices.  We use azure devops to handle the build/test/release CI/CD workflows.</p>

<p>Based on a broad analysis, I'd estimate our current back end solution could be broken out into 10-15 seperate microservices.  Unfortunately, most of these would have a similar back-end dependency, but I'd still like to break them apart so we could isolate unit testing, have smaller CI/CD footprints, and have the project start with a solid separation of concerns.</p>

<p>However, at the same time, I'd like to avoid having 10-15 different git repos, solutions, and CI flows to facilitate this workflow.  This would become a bit of a nightmare for ease of development, to have devs regularly needing to change workspaces (the 'Open Recent' list in any IDE would completely overflow!), maintaining and syncing 10-15 CI/CD.</p>

<p>The ideal result in my eyes would be a single solution, git repo, and build process with each microservice separated as a project within the solution.  When code gets committed, I'd like to fire a process in Azure devops that would only build/test/deploy those services that were changed in the commit.</p>

<p>Is this possible or am I dreaming?  I have not had much luck with Google but maybe I'm not entering just the right phrase for this...</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/55501971/multiple-microservices-in-a-single-dotnet-core-solution-git-repo,"['git', '.net-core', 'azure-devops', 'microservices']",3176,True,6,2
"How to test generic types in Typescript? Not an implementation of the generic type, but as a typeguard?","<p>I'm working on extending a bunch of typescript types into a utility library as a personal ""do I really understand Typescript?"" project. </p>

<p>I'm just having a LOT of trouble figuring out how to unit test the damn thing. </p>

<p>The problem is that I want to test that when I pass the wrong type into a function that calls for a type, that the TSC will catch it. Which it does. Brilliantly. But there's a teensy little flaw with that, in that the unit testing library I use (Jest) will throw an error (the desired behavior) and then refuse to run the rest of the test suite because it threw an error. I can't even even use ""will throw error"" because it's not a Javascript error but a Typescript error.  </p>

<p>Here's the code I have so far. I'm using Jest, but my solution doesn't need to be Jest specific, I have a funny feeling I might need some sort of specialized testing library. </p>

<pre class=""lang-js prettyprint-override""><code>// src/Either/Either.ts
export type Either&lt;Base, Either, Or&gt; = (Base &amp; Either) | (Base &amp; Or);
</code></pre>

<pre class=""lang-js prettyprint-override""><code>// src/either/Either.spec.ts

import { Either } from ""./Either"";

interface Pet {
  name: string;
}
interface Dog {
  says: ""awoo"" | ""ruff"" | ""yip"" | ""bork"" | ""bark"" | ""grr"";
  willFetch: true;
}
interface Cat {
  says: ""meow"" | ""hiss"";
  willFetch: false;
}

describe(""Either&lt;Base, Either, Or&gt;"", () =&gt; {
  it(""allows one extension OR the other, but not both, and not neither"", () =&gt; {
    type CommonPet = Either&lt;Pet, Dog, Cat&gt;;
    const whatAmI = (pet: CommonPet): ""dog"" | ""cat"" =&gt; {
      if (pet.willFetch === true) {
        return ""dog"";
      }
      return ""cat"";
    };
    expect(whatAmI({ name: ""Rex"", willFetch: true, says: ""awoo"" })).toBe(""dog"");
    expect(whatAmI({ name: ""Psycho"", says: ""hiss"", willFetch: false })).toBe(
      ""cat""
    );
    // these lines will throw a typescript error (desired)
    /* 
     const freak = whatAmI({ name: ""Freak"", says: ""meow"", willFetch: true });
     const uncommonPet = whatAmI({ name: ""Nagini"", says: 'hiss', willFetch: false, isSnake: true });
    */

    // but how to I tell Jest that I WANT it to throw a typescript error?
    interface AristoCat {
      knowsWhereItsAt: boolean;
    }
    interface JellicleCat {
      nightmareFuel: number;
    }
    type MusicalCat = Either&lt;Pet &amp; Cat, AristoCat, JellicleCat&gt;;
    const isGood = (cat: MusicalCat): boolean | never =&gt; {
      if (""knowsWhereItsAt"" in cat) {
        return true;
      }
      if (cat.nightmareFuel &gt; 0) {
        throw new Error(""NOOOOOO!"");
      }
      return false;
    };
    expect(
      isGood({
        name: ""Duchess"",
        says: ""meow"",
        willFetch: false,
        knowsWhereItsAt: true
      })
    ).toBe(true);
    expect(
      isGood({
        name: ""MacCavity (stage)"",
        willFetch: false,
        says: ""meow"",
        nightmareFuel: 0
      })
    ).toBe(false);
    const filmIt = () =&gt;
      isGood({
        name: ""MacCavity"",
        willFetch: false,
        says: ""meow"",
        nightmareFuel: 9001
      });
    expect(filmIt).toThrowErrorMatchingInlineSnapshot(`""NOOOOOO!""`);

    // again, we expect this to throw in TYPESCRIPT because it has BOTH.
    /* 
    const dreamIHadOnAcid = isGood({
      name: 'Cheshire', 
      says: 'meow', 
      willFetch: false, 
      knowsWhereItsAt: true, 
      nightmareFuel: 5/7
    })
    */
    // again, we expect this to throw in TYPESCRIPT because it has NEITHER.
    /* 
    const dreamIHadOnAcid = isGood({
      name: 'Tardar Sauce', 
      says: 'meow', 
      willFetch: false, 
    })
    */
  });
});
</code></pre>

<p>-- EDIT:</p>

<p>There's an additional difficulty.  In that I'm not sure my Either type is working the way it should (or if it is, that the compiler can't pick it up.) </p>

<p>I'm using the Typescript playground for this...</p>

<pre><code>export type Either&lt;Base, Either, Or&gt; = (Base &amp; Either) | (Base &amp; Or);

type Pet = {
  name: string;
  says?: string;
}
type DogExtension = {
  playHours: number;
}
type CatExtension = {
  sleepHours: number;
}

type CommonPet = Either&lt;Pet, DogExtension, CatExtension&gt;;

const dog: CommonPet = { name: ""rex"", says: ""awoo"", playHours: 5 };
const cat: CommonPet = { name: ""manx"", says: ""meow"", sleepHours: 14 };

const testPet = (testName: string, pet: CommonPet): CommonPet =&gt; { 
  return pet
}; 

testPet(""dog should pass"", dog);
testPet(""cat should pass"", cat);
testPet(""catdog should not pass"", { ...dog, ...cat }); /* should throw a type error, but doesn't */
</code></pre>

<p>This may be a bug in the typescript compiler... and an easy one to make.  Dog is a CommonPet, Cat is a CommonPet, so why wouldn't {...dog, ...cat} be a common pet? Unless - the far more likely solution, my Either =(T&amp;E) | (T&amp;O) just don't work the way I thought it would. </p>
",https://stackoverflow.com/questions/59494889/how-to-test-generic-types-in-typescript-not-an-implementation-of-the-generic-ty,"['typescript', 'unit-testing', 'typescript-generics']",2124,True,5,2
Is it possible to enable VT100/ANSI escape codes from PHP 5 in Windows,"<p>I'm in the process of upgrading an old PHP 5 app to PHP 7. I'm using Codeception for unit testing because it has nice colour output, making it easy to see if all the tests have passed or not.</p>

<p>Things I have tried:</p>

<ul>
<li>Upgrade to PHP 7: the app crashes</li>
<li>Run Codeception with no special flags: ANSI escape codes are printed to screen making the output hard to read</li>
<li>Run Codeception with the <code>--no-colors</code> flag: output is a single colour taking longer to recognise a 100% passing run, or which tests have failed</li>
<li>Use ANSICON instead of Windows Command Prompt: PHP 5 runs incredibly slowly, taking an hour to produce a report with coverage, when the same run under the Command Prompt only takes 2 minutes</li>
</ul>

<p>Things I have not tried:</p>

<ul>
<li>Setting a registry value so that ANSI escape codes are always on unless turned of by the running program: this solution is not portable to other developers</li>
</ul>

<p>I'd like to do the same as the source code listed further below, except within PHP. Something like:</p>

<pre><code>if (is_windows_console()) {
  if (has_vt100_extensions()) {
    if (are_vt100_extensions_disabled()) {
      vt100_extensions-&gt;on();
    }
  }
}
</code></pre>

<p>I have no idea if it's even possible to issue commands to the Command Prompt API from within PHP.</p>

<p>The following C code is from the <a href=""https://github.com/php/php-src/commit/33301d5bae4964f74fd1fc8c4fc485abfde0378e#diff-7bf2a3854a43584d8930739e4b1b93ab"" rel=""nofollow noreferrer"">PHP 7 source</a>:</p>

<pre><code>PHP_WINUTIL_API BOOL php_win32_console_fileno_set_vt100(zend_long fileno, BOOL enable)
{
    BOOL result = FALSE;
    HANDLE handle = (HANDLE) _get_osfhandle(fileno);

    if (handle != INVALID_HANDLE_VALUE) {
        DWORD events;

        if (fileno != 0 &amp;&amp; !GetNumberOfConsoleInputEvents(handle, &amp;events)) {
            // Not STDIN
            DWORD mode;

            if (GetConsoleMode(handle, &amp;mode)) {
                DWORD newMode;

                if (enable) {
                    newMode = mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
                }
                else {
                    newMode = mode &amp; ~ENABLE_VIRTUAL_TERMINAL_PROCESSING;
                }
                if (newMode == mode) {
                    result = TRUE;
                }
                else {
                    if (SetConsoleMode(handle, newMode)) {
                        result = TRUE;
                    }
                }
            }
        }
    }
    return result;
}
</code></pre>

<p>Is there a way to emulate this functionality from within a PHP 5 script?</p>

<p>I've found the following related questions but I'm still no closer to even starting:</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/3155827/how-to-call-winapi-functions-from-php"">How to call winapi functions from PHP?</a></li>
<li><a href=""https://stackoverflow.com/questions/1411657/how-do-i-make-win32-api-calls-from-php"">How do I make Win32 API calls from PHP?</a></li>
<li><a href=""https://stackoverflow.com/questions/7874544/how-to-create-c-sharp-dll-to-use-in-php"">How to create C# DLL to use in PHP</a></li>
</ul>
",https://stackoverflow.com/questions/58775351/is-it-possible-to-enable-vt100-ansi-escape-codes-from-php-5-in-windows,"['php', 'windows-10', 'ansi-escape', 'vt100']",225,False,4,0
Uncaught Error: listen EADDRINUSE: address already in use :::3000 when mocha unit testing,"<p>I'm getting this error when unit testing code,</p>

<blockquote>
  <p>2 passing (14ms)   1 failing</p>
  
  <p>1) Uncaught error outside test suite:
       Uncaught Error: listen EADDRINUSE: address already in use :::3000
        at Server.setupListenHandle [as _listen2] (net.js:1255:14)
        at listenInCluster (net.js:1303:12)
        at Server.listen (net.js:1391:7)
        at Function.listen (node_modules/express/lib/application.js:618:24)
        at Object.listen (main.js:39:5)
        at Module._compile (internal/modules/cjs/loader.js:721:30)
        at Module._compile (node_modules/pirates/lib/index.js:99:24)
        at Module._extensions..js (internal/modules/cjs/loader.js:732:10)
        at Object.newLoader [as .js] (node_modules/pirates/lib/index.js:104:7)
        at Module.load (internal/modules/cjs/loader.js:620:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
        at Function.Module._load (internal/modules/cjs/loader.js:552:3)
        at Module.require (internal/modules/cjs/loader.js:657:17)
        at require (internal/modules/cjs/helpers.js:22:18)
        at Object. (test/main.test.js:4:1)
        at Module._compile (internal/modules/cjs/loader.js:721:30)
        at Module._compile (node_modules/pirates/lib/index.js:99:24)
        at Module._extensions..js (internal/modules/cjs/loader.js:732:10)
        at Object.newLoader [as .js] (node_modules/pirates/lib/index.js:104:7)
        at Module.load (internal/modules/cjs/loader.js:620:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
        at Function.Module._load (internal/modules/cjs/loader.js:552:3)
        at Module.require (internal/modules/cjs/loader.js:657:17)
        at require (internal/modules/cjs/helpers.js:22:18)
        at Array.forEach ()
        at StatWatcher.onchange (internal/fs/watchers.js:50:8)</p>
</blockquote>

<p>I'm using <a href=""https://mochajs.org"" rel=""nofollow noreferrer"">mocha</a>, and i have <code>--watch</code> on my package.json. I'm using an es6 approach to express. </p>

<p><strong>Package.json</strong></p>

<pre><code>{
  ""name"": ""elies6express"",
  ""version"": ""1.0.0"",
  ""description"": """",
  ""main"": ""index.js"",
  ""scripts"": {
    ""test"": ""./node_modules/.bin/mocha --watch --require @babel/register"",
    ""start"": ""nodemon --exec babel-node main.js""
  },
  ""author"": """",
  ""license"": ""ISC"",
  ""dependencies"": {
    ""body-parser"": ""^1.19.0"",
    ""bookshelf"": ""^0.14.2"",
    ""chai-http"": ""^4.3.0"",
    ""cookie-parser"": ""^1.4.4"",
    ""cors"": ""^2.8.5"",
    ""dotenv"": ""^8.0.0"",
    ""express"": ""^4.17.0"",
    ""knex"": ""^0.16.5"",
    ""morgan"": ""^1.9.1"",
    ""path"": ""^0.12.7"",
    ""pg"": ""^7.11.0""
  },
  ""devDependencies"": {
    ""@babel/cli"": ""^7.4.4"",
    ""@babel/core"": ""^7.4.5"",
    ""@babel/node"": ""^7.4.5"",
    ""@babel/preset-env"": ""^7.4.5"",
    ""@babel/register"": ""^7.4.4"",
    ""chai"": ""^4.2.0"",
    ""mocha"": ""^6.1.4"",
    ""nodemon"": ""^1.19.0"",
    ""reify"": ""^0.19.1"",
    ""request"": ""^2.88.0""
  }
}
</code></pre>

<p><strong>main.js</strong></p>

<pre><code>import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from 'morgan';
import path from 'path';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import userRoute from './routes/users';

const app = express();

app.use(cors());
app.use(logger('dev'));
// For React Stuff if need be
// app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
app.use(cookieParser());
app.use(bodyParser.json());

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

app.use('/users', userRoute);

app.use(() =&gt; (req, res, next)  =&gt;{
  res.locals.user = req.user; // This is the important line
  // req.session.user = user
  console.log(res.locals.user);
  next();
});
app.use(bodyParser.urlencoded({ extended:false})); 

//build mode
// app.get('*', (req, res) =&gt; {
//   res.sendFile(path.join(__dirname+'/client/public/index.html'));
// })

app.listen(process.env.PORT, () =&gt;
  console.log(`Example app listening on port ${process.env.PORT}!`),
);

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

<p><strong>main.test.js</strong></p>

<pre><code>import chai from ""chai""
import chaiHttp from 'chai-http';
import request from 'request';
import server from '../main';
const expect = chai.expect;
const should = chai.should();


chai.use(chaiHttp);

// should get / 

describe('should GET /',  () =&gt; {
    it('should get 200 status', (done) =&gt;{
        chai.request(server)
        .get('/')
        .end( (err, res) =&gt; {
            res.should.have.status(200);
            done();
        });
    });

})
// should check for Hello World!
describe('Should check for Hello World! text', () =&gt; {
    it('should check for hello world text', (done) =&gt;{
        chai.request(server)
        .get('/')
        .end( (err, res) =&gt; {
            expect(res.body).to.be.an('object') // works
            expect(res.text).to.equal('Hello World!')  // use res.text to check for res.send() text
            done();
        })
    })

})
</code></pre>
",https://stackoverflow.com/questions/56308581/uncaught-error-listen-eaddrinuse-address-already-in-use-3000-when-mocha-uni,"['node.js', 'express', 'mocha.js']",8706,True,4,5
What is the purpose of ReactiveUI&#39;s IViewFor&lt;T&gt; (and its implementing types) in WPF?,"<p>I am in the process of learning ReactiveUI and so far I love it but I now realise that the framework encompasses XAML (i.e. the view layer) as well, offering things like <code>ReactiveUserControl</code> and <code>ReactiveView</code>.</p>

<p>Why do I need, or want these? System.Reactive/ReactiveUI offer massive advantages on the Model/ViewModel side but what are the advantages on the View side, again, in the context of a WPF app? Unit testing perhaps? </p>

<p><strong>Note:</strong> I like WPF, I like its data binding. All my XAML bindings are strongly-typed and easy to refactor, customise, re-skin, debug and whatnot. I learned to use but not over-use the converters so never have a prob with those either. I never felt a need to override the UserControl class. With that said, I never had a problem with the WPF <em>itself</em>.</p>

<p>If I decide to use the <code>IVIewFor&lt;T&gt;</code> implementations, will my XAML designer go nuts? Will I lose anything? Will I end up debugging memory leaks, UI stutter and strange CPU spikes? We'll be making a very large app so we go by the 'better safe than sorry' principle as we were burnt by the CAB framework before.</p>

<p>If I decide against, what benefits of the ReactiveUI will we lose? Would I be heathens for doing this, or is it more of an optional aspect of the framework? </p>

<p>So far I understand the benefits in case of WinForms or Android (it offers binding support as I understood) but not WPF. While it sure does have its quirks, I don't feel the need for another framework on top of it.</p>
",https://stackoverflow.com/questions/54670692/what-is-the-purpose-of-reactiveuis-iviewfort-and-its-implementing-types-in,"['c#', 'wpf', 'reactiveui']",1286,True,3,1
Can you set a breakpoint for a specific exception type?,"<p>We're trying to debug some unit tests which are randomly failing.  We believe this is because the codebase improperly mixes UI interaction as part of unit testing (i.e. instantiates ViewControllers while firing off service requests that update them.)</p>

<p>I'm trying to go through and clean this up, but I keep getting things like this...</p>

<blockquote>
  <p>2019-01-15 11:05:37.500086-0500 [NAME REDACTED][78259:9742813] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete section 1, but there are only 0 sections before the update'</p>
</blockquote>

<p>The trouble is we have no idea which test (or tests) is causing the table to be updated. Worse, we don't even know which table it is! The call stack improperly hangs on a <code>WaitForExpectations</code> call in a unit test which tests service-calls and responses and which doesn't even reference, let alone instantiate anything to do with the UI.</p>

<p>Our guess is its happening from an earlier test that fires up some UI component which internally fires off some request, and the response comes back long after the original unit test was finished.  That would explain why it's breaking in a completely-unrelated test.  But it's just a guess because we're not sure how to actually break on the line that's causing the true, underlying exception.</p>

<p>So as the title says, how can you break on a specific exception?  I've tried symbolic breakpoints to no avail, and the regular <code>All Exceptions</code> breakpoint catches way too much to the point of being more intrusive than useful.  We only want to break on that one exception. Is it possible?</p>
",https://stackoverflow.com/questions/54205058/can-you-set-a-breakpoint-for-a-specific-exception-type,"['ios', 'swift', 'xcode', 'unit-testing', 'exception']",204,False,2,0
EntityFramework Core cache data in memory keeping async operations,"<p>I have a working app utilizing EF Core 3.0 (preview 8 right now). There's one data set that changes very infrequently, but is queried very frequently. The services that actually perform operations on the data are isolated via a very simple interface.</p>

<pre><code>interface IDataProvider
{
    ValueTask&lt;IQueryable&lt;DataRow&gt;&gt; GetDataAsync();
}
</code></pre>

<p>Until now, there was only one implementation of the data provider built upon an actual SQL database. So if we have a DbContext with <code>DbSet&lt;DataRow&gt; Data</code>:</p>

<pre><code>class LiveDataProvider : IDataProvider
{
    private readonly DataDbContext _dbContext;

    public LiveDataProvider(DataDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public ValueTask&lt;IQueryable&lt;DataRow&gt;&gt; GetDataAsync() =&gt; 
        new ValueTask&lt;IQueryable&lt;DataRow&gt;&gt;(_dbContext.Data.AsNoTracking());
}
</code></pre>

<p>Now I'm tasked with adding caching to this application. So the idea is to store the entire <code>Data</code> set in-memory, because retrieving it is a fairly expensive query on the DB, but the amount of data is just a few hundred MB. Since updates are infrequent, the vast majority of request would hit the cache. With this idea, the implementation seemed fairly simple:</p>

<pre><code>class InMemoryDataCache : IDataProvider
{
    private readonly IPicksDbContext _picksDbContext;
    private readonly IMemoryCache _memoryCache;

    public async ValueTask&lt;IQueryable&lt;DataRow&gt;&gt; GetDataAsync()
    {
        var entryKey = GetEntryKey(); // Implementation is irrelevant.

        if (!_memoryCache.TryGetValue(entryKey, out IQueryable&lt;DataRow&gt; data))
        {
            data = (await _dbContext.Data.AsNoTracking().ToListAsync()).AsQueryable();
            _memoryCache.Set(entryKey, data);
        }

        return data;
    }

    InMemoryDataCache(DataDbContext dbContext, IMemoryCache memoryCache)
    {
        _dbContext = dbContext;
        _memoryCache = memoryCache;
    }
}
</code></pre>

<p>Sounds good, doesn't work - the service implementations use asynchronous operations on the <code>IQueryable</code> extensively, so <code>ToListAsync()</code>, <code>AnyAsync()</code> etc. Calling any of these on the cached <code>List</code> will results in EF Core throwing an <code>InvalidOperationException</code> with message <code>Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations.</code></p>

<p>That error is pretty familiar, as unit testing the services threw the same thing. There I mocked an <code>IAsyncQueryProvider</code> implementation (shout-out to <a href=""https://github.com/romantitov/MockQueryable"" rel=""nofollow noreferrer"">MockQueryable</a>), so here I could the same thing.</p>

<p>Alternatively, I could write my own extension methods for <code>ToListAsync</code>, <code>AnyAsync</code>, etc. with an implementation of</p>

<pre><code>public static Task&lt;List&lt;T&gt;&gt; ToListAsync&lt;T&gt;(this IQueryable&lt;T&gt; queryable)
{
    if(queryable is IAsyncEnumerable&lt;T&gt;)
    {
        return Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync(queryable);
    }

    return Task.FromResult(queryable.ToList());
}
</code></pre>

<p>Both are a lot of work and tests for something so stupidly simple. Is there a more robust solution? Or have I chased myself into a corner by tying my services to the EntityFrameworkQueryableExtensions in the first place and I cannot transparently use an in-memory provider.</p>
",https://stackoverflow.com/questions/57711202/entityframework-core-cache-data-in-memory-keeping-async-operations,"['c#', '.net-core', 'entity-framework-core', 'ef-core-3.0']",1901,False,2,0
NUnit test project can&#39;t load assembly for System.Windows.Forms,"<p>I have an NUnit test project dedicated for unit testing which has a Target Framework of .Net Core 2.1. This test project has references of two other Projects one of which is a <em>Windows Form</em> based application and the other is a <em>Class Library</em> based application for database interactions. Both of these projects has a target framework of .Net Framework 4.6.1 </p>

<p>I am writing a test for testing a method of the <em>Class Library</em> based application to test the output of the method. But it's showing the following error, </p>

<p><strong>'System.IO.FileNotFoundException : Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified.'</strong></p>

<p>I have tried the following fixes and none of them worked. </p>

<ul>
<li>Removing the project references and adding them again</li>
<li>Changing build platform target from AnyCPU to X86 and x64</li>
<li>Adding <strong>dependant assemblies</strong> tag inside a .config file. (Interesting things is .NET Core 2.1 doesn't provide with a .config file) </li>
</ul>

<p><em>This is the test class (Test_DataClasses.cs)</em>,</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Data.SQLite;
using SharedDataClasses;
using MantechAutomationControl;
using System.IO;
using System.Reflection;

namespace MAC_Testing
{
[TestFixture]
class Test_DataClasses
{
    #region Tests
    [Test]
    public void t_m_initializeDatabase()
    {
        //Assign
        string v_dbLocation = Path.Combine(""M:\\For_Jabed\\MAC\\MAC\\MantechAutomationControl\\bin\\Debug\\"", ""DB.sqlite"");
        //Act
        DataClasses_v2.m_initializeDatabase();
        //Assert
        Assert.That(new FileInfo(v_dbLocation), Does.Exist);
    }
    #endregion
}
}
</code></pre>

<p><em>And this is the method the above test is trying to validate</em>, </p>

<pre><code>public static class DataClasses_v2
{
    #region Variables 
    #endregion
    #region Methods
    public static void  m_initializeDatabase()
    {
        string v_executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        string v_dbLocation = Path.Combine(v_executableLocation, ""DB.sqlite"");
        if (!File.Exists(v_dbLocation))
        {
            DialogResult o_createDBFileDialogBox = MessageBox.Show(""Could not find the database in the expected location:\n"" + v_dbLocation + ""\n\nWould you like to create a new blank database file?"", ""Warning"", MessageBoxButtons.YesNo);
            if (o_createDBFileDialogBox == DialogResult.Yes)
            {
                SQLiteConnection.CreateFile(v_dbLocation);
                using (SQLiteConnection o_dbConnection = new SQLiteConnection(@""DataSource="" + v_dbLocation + "";Version=3;""))
                {
                    o_dbConnection.Open();
                }
            }
            else
                return;
        }
    }
</code></pre>

<p>I don't really understand whats going on here. Although point to be noted I actually was working towards to use <em>Nunit Form</em> dll to work with Forms (DialogBox) as the method to be tested had a DialogBox to work with. </p>

<p>In the test project there is another class and the tests written inside those class works fine for the Same target 'Class Library' based project to validate a different function. </p>

<p>Hopefully someone will be able to explain whats going on here.</p>
",https://stackoverflow.com/questions/56401372/nunit-test-project-cant-load-assembly-for-system-windows-forms,"['c#', '.net-core', 'visual-studio-2017', 'nunit']",1424,False,2,0
How can I write Unit Tests for classes that run until Keyboard Interrupt and don&#39;t return anything?,"<p>I am working on a Python service that monitors a directory in the filesystem. When it sees that a file has been created or moved there, it sends the path of the file into a Kafka queue. I have the service working exactly like I need it to, but my problem is that I am supposed to have at least 90% coverage with unit tests. I am relatively new to Python, and I haven't ever used unit testing in any language before, so I feel really out of my depth. I just can't wrap my head around how I would go about testing these classes.</p>

<p>This is the class that monitors the file system, I'm using the <a href=""https://pypi.org/project/watchdog/"" rel=""nofollow noreferrer"">watchdog</a> library.</p>

<p>I added the <code>handler=FileHandler</code> parameter to <strong>init</strong> because I figured I could use that to pass the class a fake handler I could use for the tests, but that feels like it's unnecessarily complicated.</p>

<pre class=""lang-py prettyprint-override""><code>class FileSystemMonitor:

    def __init__(self, target_path, kafka_queue, handler=FileHandler):
        self.path = target_path
        self.queue = kafka_queue
        self.handler = handler(self.queue)

    def start(self):
        observer = Observer()
        observer.schedule(self.handler, self.path, recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()

def parse_args():
    path = sys.argv[1] if len(sys.argv) &gt; 1 else '.'
    queue = sys.argv[2] if len(sys.argv) &gt; 2 else 'default'
    return path, queue

if __name__ == ""__main__"":
    path, queue = parse_args()
    monitor = FileSystemMonitor(path, queue)
    monitor.start()
</code></pre>

<hr/>

<p>This is the class I made which handles the events thrown by the monitor, and passes the path to the Kafka Queue.</p>

<pre class=""lang-py prettyprint-override""><code>class FileHandler(PatternMatchingEventHandler):

    def __init__(self, queue):
        super(FileHandler, self).__init__(ignore_patterns=[""*/.DS_Store""], ignore_directories=True)
        self.queue = queue

    def on_any_event(self, event):
        super(FileHandler, self).on_any_event(event)
        #print(event, self.queue)
        result = kafkaProducer.send_msg(self.queue, event.src_path, event.event_type)
        print(""Handler:"", result)
        return result
</code></pre>

<p>I've written some tests for the kafkaProducer class, and I didn't have a very hard time with that, because it actually returns a value that I could test.</p>

<p>FileSystemMonitor runs infinitely and just waits for a keyboard interrupt, and when it does end, it doesn't return anything, so how do I write the unit tests for it? </p>

<p>As for the FileHandler class it depends on events being triggered by the monitor class, so how would I isolate the Handler class to test it?</p>
",https://stackoverflow.com/questions/56894411/how-can-i-write-unit-tests-for-classes-that-run-until-keyboard-interrupt-and-don,"['python-3.x', 'multithreading', 'unit-testing', 'python-unittest', 'python-watchdog']",451,True,2,1
Mockito mocks locally final class but fails in Jenkins,"<p>I have written some unit tests for a static method. The static method takes only one argument. The argument's type is a final class. In terms of code:</p>

<pre><code>public class Utility {

   public static Optional&lt;String&gt; getName(Customer customer) {
       // method's body.
   }
}

public final class Customer {
   // class definition
}
</code></pre>

<p>So for the <code>Utility</code> class I have created a test class <code>UtilityTests</code> in which I have written tests for this method, <code>getName</code>. The unit testing framework is <em>TestNG</em> and the mocking library that is used is <code>Mockito</code>. So a typical test has the following structure:</p>

<pre><code>public class UtilityTests {

   @Test
   public void getNameTest() {
     // Arrange
     Customer customerMock = Mockito.mock(Customer.class);
     Mockito.when(...).thenReturn(...);

     // Act
     Optional&lt;String&gt; name = Utility.getName(customerMock);

     // Assert
     Assert.assertTrue(...);
   }
}
</code></pre>

<p><strong>What is the problem ?</strong></p>

<p>Whereas the tests run successfully locally, inside IntelliJ, they fail on Jenkins (when I push my code in the remote branch, a build is triggered and unit tests run at the end). The error message is sth like the following:</p>

<blockquote>
  <p>org.mockito.exceptions.base.MockitoException:  Cannot mock/spy class
  com.packagename.Customer Mockito
  cannot mock/spy because :
   - final class</p>
</blockquote>

<p><strong>What I tried ?</strong></p>

<p>I searched a bit, in order to find a solution but I didn't make it. I note here that I am <strong>not</strong> allowed to change the fact that <code>Customer</code> is a <strong>final</strong> class. In addition to this, I would like if possible to <strong>not</strong> change it's design at all (e.g. creating an interface, that would hold the methods that I want to mock and state that the Customer class implements that interface, as correctly Jose pointed out in his comment). The thing that I tried is the second option mentioned at <a href=""https://www.baeldung.com/mockito-final"" rel=""noreferrer"">mockito-final</a>. Despite the fact that this fixed the problem, it brake some other unit tests :(, that cannot be fixed in none apparent way. </p>

<p><strong>Questions</strong></p>

<p>So here are the two questions I have:</p>

<ol>
<li>How that is possible in the first place ? Shouldn't the test fail both locally and in Jenkins ? </li>
<li>How this can be fixed based in the constraints I mentioned above ?  </li>
</ol>

<p>Thanks in advance for any help. </p>
",https://stackoverflow.com/questions/58992219/mockito-mocks-locally-final-class-but-fails-in-jenkins,"['java', 'unit-testing', 'mockito', 'testng']",3999,True,13,3
D3js in a React Component Unit Testing using Jest/Enzyme,"<p><strong>Problem:</strong> When I run my code, the SVG appends to the outer div on the component and renders on the page perfectly. However, during testing, the SVG is not appended to the outer div.</p>

<p><strong>Stack:</strong> I am trying to test my d3js element wrapped in a React component using Jest/Enzyme.</p>

<p><strong>Research I did so far:</strong> Looked up a bunch of guides/posts on testing d3js using google and on stackoverflow. Used a guide on unit testing d3js and React with Jasmine. I have also read that testing 3rd party libraries may be difficult with Enzyme so this may be a limitation of the testing framework.</p>

<p>I have included a basic sample of code to test.</p>

<p><strong>Component:</strong></p>

<pre><code>import React from ""react"";
import * as d3 from ""d3"";

export default class Circle extends React.Component {

    componentDidMount = () =&gt; {
        return this.renderCircle();
    }

    renderCircle = () =&gt; {
        d3.select(""#outerDiv"")
            .append(""svg"")
            .attr(""width"", 600)
            .attr(""height"", 300)
            .append(""circle"")
            .attr(""id"", ""d3-el"")
            .attr(""cx"", 300)
            .attr(""cy"", 150)
            .attr(""r"", 30)
            .attr(""fill"", ""#ff0000"")
            .on(""click"", function (d, i) {
                var item = d3.select(this);
                item.attr(""fill"", ""#00ff00"");
            });
    }

    render() {
        return &lt;div id=""outerDiv"" /&gt;;
    }

}
</code></pre>

<p><strong>Test:</strong></p>

<pre><code>import React from ""react"";
import * as d3 from ""d3"";
const jsdom = require(""jsdom"");
const ReactJSDOM = require('react-jsdom');
const { JSDOM } = jsdom;
import Circle from ""./Circle.js"";
import { mount } from ""enzyme"";
import sinon from 'sinon';

describe(""Circle"", () =&gt; {
    it(""d3js element should be appended to outer div"", () =&gt; {
        let wrapper = mount(&lt;Circle /&gt;);
        let instance = wrapper.instance();
        const jsdomElem = ReactJSDOM.render(&lt;html&gt;&lt;body&gt;&lt;p&gt;&lt;Circle /&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;);
        console.log(jsdomElem.querySelector(""#d3-el"")); // returns null
        console.log(wrapper.find(""d3-ele"").get(0));; // returns undefined
        console.log(d3.select(""d3-el"")); // returns null
        expect(wrapper.find(""d3-el"").exists()).toEqual(true);
    }
}
</code></pre>

<p>Doing a find on the d3 element that is supposed to be rendered using wrapper.find(), document.querySelector(), and d3.select() all return undefined or null.</p>

<p><strong>Things I have tried but does not append the SVG element to the outer div:</strong></p>

<ol>
<li><p>Using mount() on the component.</p></li>
<li><p>Using instance() of the mounted component and calling the renderCircle() method directly.</p></li>
<li><p>Using ReactJSDOM to render a whole DOM from top to bottom.</p></li>
<li><p>A bunch of other stuff that probably makes no sense including sinon.spy() and mocking a jest.fn().</p></li>
</ol>

<p>None of these methods work and if I do a find on the outer div, it does not show that the div has any children elements. Doing a debug on the wrapper shows the same thing.</p>

<p>Would love some help to get this SVG appended to the div during testing. Any solutions or other strategies would be greatly appreciated. Please let me know if you have any questions or if I should add more information. Thanks!</p>
",https://stackoverflow.com/questions/55104250/d3js-in-a-react-component-unit-testing-using-jest-enzyme,"['reactjs', 'd3.js', 'jestjs', 'enzyme', 'jsdom']",3493,True,7,2
Corda - Unit Testing Flows That End Up In Hospital,"<p>I am unit testing a flow that I know will fail.</p>
<pre><code>assertFailsWith&lt;JdbcSQLIntegrityConstraintViolationException&gt; {
    nodeA.issueState(...) // Note, issueState is an extension on StartedMockNode
}
</code></pre>
<p>The reason for the failure is that the state being output in the transaction cannot be duplicated due to a unique key/index violation on the schema:</p>
<blockquote>
<p>org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation</p>
</blockquote>
<p>When this happens in a unit test the output displays:</p>
<blockquote>
<p>[INFO] 12:41:22,600 [Mock network] statemachine.StaffedFlowHospital. - Flow error kept for overnight observation by [net.corda.node.services.statemachine.StaffedFlowHospital$TransitionErrorGeneralPractitioner@49a4216e] (error was org.hibernate.exception.ConstraintViolationException: could not execute statement) {actor_id=Only For Testing, actor_owning_identity=O=PartyA, L=London, C=GB, actor_store_id=TEST, fiber-id=10000012, flow-id=932a7d4e-e695-4096-b3d8-efbcdbfa5b21, invocation_id=fcf25c8a-6bf1-4dce-8e65-3c84c96b8523, invocation_timestamp=2019-12-28T12:41:22.402Z, origin=Only For Testing, session_id=fcf25c8a-6bf1-4dce-8e65-3c84c96b8523, session_timestamp=2019-12-28T12:41:22.402Z, thread-id=1309}</p>
<p>[WARN] 12:42:18,805 [FlowHospitalJobTimer] statemachine.StaffedFlowHospital. - There are 1 flows kept for overnight observation. Affected flow ids: 932a7d4e-e695-4096-b3d8-efbcdbfa5b21</p>
<p>[WARN] 12:43:18,804 [FlowHospitalJobTimer] statemachine.StaffedFlowHospital. - There are 1 flows kept for overnight observation. Affected flow ids: 932a7d4e-e695-4096-b3d8-efbcdbfa5b21</p>
</blockquote>
<p>The problem is that the test hangs and never completes. I've managed to get the test to fail by adding a duration to the <code>getOrThrow</code> function on the resulting <code>CordaFuture</code>, but this seems wrong to me, as the flow is failing due to a timeout, rather than because of the underlying exception.</p>
<pre><code>.getOrThrow(Duration.ofSeconds(10))
</code></pre>
<blockquote>
<p>java.lang.AssertionError: Expected an exception of class org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException to be thrown, but was java.util.concurrent.TimeoutException</p>
</blockquote>
<p>What is the correct way to test flows that end up being sent to the flow hospital?</p>
",https://stackoverflow.com/questions/59511061/corda-unit-testing-flows-that-end-up-in-hospital,['corda'],266,True,1,1
How do I make a unit test out of my code in C#,"<p>So I'm doing a simple poker test in which I have to display the players' names and their hands, and the player who has the higher hand wins. For this test, there are no card suits and ranks (e.g. ten of spades, jack of diamonds), just the type of hand the player is supposed to have (e.g. royal flush, straight, high card, etc). The output should be like this:</p>

<pre><code>Player 1, Jane's hand is: Full House
Player 2, John's hand is: One Pair
Winner: Jane (Full House)
</code></pre>

<p>So now, I have all the logic working for this (which you'll see below). However, I'm now supposed to make a unit test for this. I've seen some tutorials but if you see my code below, I don't think it's suitable for a unit test. If anyone can help me fix my code for unit testing, then I highly appreciate it.</p>

<p>Here's the code:</p>

<pre><code>public class PokerGame
{
    static void Main(string[] args)
    {
        // Names of the players
        string player1Name, player2Name;

        // The array of the poker hands
        string[] pokerHands =
        {
            ""High Card"", ""One Pair"", ""Two Pair"", ""Three of a Kind"", ""Straight"", ""Flush"",
            ""Full House"", ""Four of a Kind"", ""Straight Flush"", ""Royal Flush""
        };

        // This will prompt the players to type their name
        Console.Write(""Enter Player 1: "");
        player1Name = Console.ReadLine();
        Console.Write(""Enter Player 2: "");
        player2Name = Console.ReadLine();

        // This Random object will deal random hands accordingly
        Random randomHand = new Random();

        // The random hand index assigned to Player 1
        int hand1 = randomHand.Next(pokerHands.Length);

        // The random hand index assigned to Player 2
        int hand2 = randomHand.Next(pokerHands.Length);

        Console.WriteLine(""Player 1, "" + player1Name + ""'s, hand is: "" + pokerHands[hand1]);
        Console.WriteLine(""Player 2, "" + player2Name + ""'s, hand is: "" + pokerHands[hand2]);

        // If the random hand index for Player 1 is greater than that for Player 2
        if (hand1 &gt; hand2)
        {
            // Then Player 1 wins
            Console.WriteLine(""Winner: "" + player1Name + "" ("" + pokerHands[hand1] + "")."");
        }
        // But if it's the opposite
        else if (hand1 &lt; hand2)
        {
            // Player 2 wins
            Console.WriteLine(""Winner: "" + player2Name + "" ("" + pokerHands[hand2] + "")."");
        }
        // And if they have the same hands
        else
        {
            Console.WriteLine(""It's a tie!"");
        }

        Console.ReadLine();
    }
}
</code></pre>

<p>EDIT: After getting help from some friends and from people on Facebook (LOL), I managed to refactor some of my code into this:</p>

<pre><code>public class PokerDealer
    {
        string[] hands =
            {
                ""High Card"", ""One Pair"", ""Two Pair"", ""Three of a Kind"", ""Straight"", ""Flush"",
                ""Full House"", ""Four of a Kind"", ""Straight Flush"", ""Royal Flush""
            };

        public void DealCards(int hand1, int hand2, string name1, string name2)
        {
            Random randomHand = new Random();

            hand1 = randomHand.Next(hands.Length);
            hand2 = randomHand.Next(hands.Length);

            Console.WriteLine(""Player 1, "" + name1 + ""'s hand: "" + hands[hand1]);
            Console.WriteLine(""Player 2, "" + name2 + ""'s hand: "" + hands[hand2]);

            CheckWinner(hand1, hand2, name1, name2);
        }

        public int CheckWinner(int win1, int win2, string name1, string name2)
        {
            int winner;

            if (win1 &gt; win2)
            {
                winner = win1;
                Console.WriteLine(""Winner: "" + name1 + "" ("" + hands[winner] + "")"");
            }
            else if (win1 &lt; win2)
            {
                winner = win2;
                Console.WriteLine(""Winner: "" + name2 + "" ("" + hands[winner] + "")"");
            }
            else
            {
                winner = 0;
                Console.WriteLine(""It's a tie!"");
            }

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

<p>DealCards() is basically my randomizer (gives out random cards) and CheckWinner(), well, checks who has the winning card. Also, I've already run unit tests for the winning conditions of both players, and they work! Now here are some problems:</p>

<ol>
<li>How will I now test if they have the same card? (The last condition)</li>
<li>I'm trying to run a test for DealCards() to see if the players indeed get random cards and to see if it doesn't go out of the range (0 to 9; probably more important). For this one, I don't know how I will assert the latter condition. Here's the testing method:</li>
</ol>

<pre><code>        [TestMethod]
        public void RandomHand()
        {
            // Tests if players are given a random hand within the range
            PokerDealer pd = new PokerDealer();
            Random randomHand = new Random();

            int randomHandIndex = randomHand.Next(10);
            pd.DealCards(randomHandIndex, randomHandIndex, ""Player 1"", ""Player 2"");
        }
</code></pre>
",https://stackoverflow.com/questions/58970274/how-do-i-make-a-unit-test-out-of-my-code-in-c,"['c#', 'unit-testing']",284,False,1,1
"When mocking Workbook-&gt;Worksheets: variable &#39;p&#39; of type &#39;Microsoft.Office.Interop.Excel.Workbook&#39; referenced from scope &#39;&#39;, but it is not defined","<p>I'm just starting to learn how to use unit testing with NUnit and how to use mocking to fake the objects I need to test.</p>

<p>Currently I'm working with a project that implements a VSTO Excel Addin and would like to start using unit tests with that project.</p>

<p>So I have a function that takes a Workbook as parameter and returns a list of relevant worksheets that I want to process.
This function I would like to test. I ""just"" need to fake the worksheet names, as that function only iterates through all the worksheets and checking their names.</p>

<p>With searching the internet resources I was trying to build the following solution trying to fake a Workbook with a list of Worksheets with the name list ""SheetNames"", which is of type List:</p>

<pre><code>        var fakeWorksheetList = new List&lt;Excel.Worksheet&gt;();
        foreach (string sheetName in SheetNames)
        {
            var sheet = Mock.Of&lt;Excel.Worksheet&gt;();
            sheet.Name = sheetName;
            fakeWorksheetList.Add(sheet);
        }

        var fakeWorkbook = new Mock&lt;Excel.Workbook&gt;();
        fakeWorkbook.Setup(p =&gt; p.Worksheets.GetEnumerator())
            .Returns(() =&gt; fakeWorksheetList.GetEnumerator());
</code></pre>

<p>But when running the test code I get the following error message:</p>

<pre><code>variable ""p"" of type ""Microsoft.Office.Interop.Excel.Workbook"" referenced from scope """", but it is not defined
</code></pre>

<p>What am I'm doing wrong. Why does the lambda expression in Setup() does give me such an error message?
Is there a better way to fake the Worksheets List?</p>

<p>Please forgive me if I show some lack of understanding as I'm really just starting with the mocking topic.</p>

<p>This is the function I want to test, which I need in my add-in to get all the worksheets my add-in has to work with:</p>

<pre><code>    public static Dictionary&lt;int, Excel.Worksheet&gt; GetApplicableYearSheets(Excel.Workbook Workbook, int iCurrentYear = 0)
    {
        if (iCurrentYear &lt;= 0)
            iCurrentYear = DateTime.Now.Year;

        int iFromYear = iCurrentYear - 2;
        Dictionary&lt;int, Excel.Worksheet&gt; YearSheets = new Dictionary&lt;int, Excel.Worksheet&gt;();

        for (int iNr = 1; iNr &lt;= Workbook.Worksheets.Count; iNr++)
        {
            int iYear = 0;
            string sWorksheetName = Workbook.Worksheets[iNr].Name;
            if ((sWorksheetName.Trim().Length == 4) &amp;&amp; (int.TryParse(sWorksheetName, out iYear)))
            {
                if ((iYear &gt;= iFromYear) &amp;&amp; (iYear &lt;= iCurrentYear))
                    YearSheets.Add(iYear, Workbook.Worksheets[iNr]);
            }
        }

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

<p>The sheet names list I want to use for testing, for example is:</p>

<pre><code>        List&lt;string&gt; SheetNames = new List&lt;string&gt;()
        {
            ""2012"",
            ""2013"",
            ""2014"",
            ""2015"",
            ""2016"",
            ""2017"",
            ""2018"",
            ""2019"",
            ""Test"",
            ""Spezialfälle""
        };
</code></pre>

<p>My plan was to test calling this function with the mocked fakeWorkbook, for example in the following way:</p>

<pre><code>Assert.That(InvoicingUtils.GetApplicableYearSheets(FakeWbFullNames, iCurrentYear: 2019), Has.Exactly(3).Items);
</code></pre>

<p>and so on</p>
",https://stackoverflow.com/questions/54708098/when-mocking-workbook-worksheets-variable-p-of-type-microsoft-office-intero,"['c#', 'linq', 'unit-testing', 'mocking', 'excel-interop']",1307,True,1,1
How to mock a function that takes an already defined lambda function and have coverage over lambda function,"<p>I am learning unit testing using googletest and am unsure how to cover a function.
In short, I need to get coverage over lambda function (lets say L), defined inside a mother function M. M calls a function C (defined in another file) that takes as argument lambda function L (a callback). I am writing a unit test for M, and need to call M, mocking the outside function M while also ensuring C is mocked and L is covered properly.</p>

<p>In short, object->M has L and M calls C(L).</p>

<p>Is there a way in google test to do this?</p>

<p>General shape of what I've already tried:</p>

<pre><code>    /* source code */
    /* header */
    struct Object
        {/*struct methods*/ 
        //M declaration
        int M();
        };

    /* cpp file */
    int M()
    {
        /* some operations */
        auto L = [](int number){/* operations, returns 0; */};

        int store; //storing the result of C
        store = C(L);
    }

    /* other file */
    int C(int* L(int))
    {
        /* some operations */
        L(1);

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

<p>Unit test file code:</p>

<pre><code>    #include &lt;gmock/gmock.h&gt;
    #include &lt;gtest.h&gt;

    using ::testing::Return;
    using ::testing::ReturnRef;
    using ::testing::DoAll;
    using ::testing::SetArgReferee;
    using ::testing::SetArgPointee;
    using ::testing::SetArrayArgument;
    using ::testing::_;

   /* mock class*/
   class MockedFunctions
   {
   public:
       /* going to put 5 ints for the sake of the example */
       MOCK_METHOD1(C, int(int));
   };

   class TestObject : public ::testing::Test
   {
   public:
       TestObject(){}
       ~TestObject(){}
   protected:
       Object *objectInstance;
       virtual void SetUp()
       {    objectInstance = new Object;}
       virtual void TearDown()
       {    delete objectInstance;}
   };

   /* test for function */
   TEST_F(TestObject, test_M)
   {
       MockedFunctions test_C;

       EXPECT_CALL(test_C, C(_))
           .Times(1)
           /* don't care about passed number to L */
           .WillOnce(DoALL (SetArgPointee&lt;0&gt;(L(3)), Return(0));
       /* coud put EXPECT_EQ as well */
       objectInstance-&gt;M();
   }
</code></pre>

<p>This gives me an error at .WillOnce stating L was not declared in this scope.</p>

<p>Note that I do not care about the contents of L, as long as they are covered. What I have found so far regarding this topic suggested to mock my lambda function L, which I do not want to do here, since I need coverage over its code as part of function M.</p>

<p>While I am not required, in this case, to use strictly the GTest style (as my tutor did not know how to proceed with this L function coverage) and could use a stub for C that would force the usage of L (I have this version implemented at the moment to be able to compile with the rest of the code), is it nonetheless possible to obtain this coverage using strictly a googletest style?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/55395837/how-to-mock-a-function-that-takes-an-already-defined-lambda-function-and-have-co,"['c++', 'googletest']",939,True,1,1
Set up a mock database in Python for unit testing,"<p>I want to set up a mock database (as opposed to creating a test database if possible) to check if the data is being properly queried and than being converted into a Pandas dataframe. I have some experience with mock and unit testing and have set-up previous test successfully. However, I'm having difficulty in applying how to mock real-life objects like databases for testing.</p>

<p>Currently, I'm having trouble generating a result when my test is run. I believe that I'm not mocking the database object correctly, I'm missing a step involved or my thought process is incorrect. I put my tests and my code to be tested in the same script to simplify things. </p>

<ul>
<li>I've thoroughly read thorough the Python unittest and mock documentation so I know what it does and how it works (For the most part).</li>
<li>I've read countless posts on mocking in Stack and outside of it as well. They were helpful in understanding general concepts and what can be done in those specific circumstances outlined, but I could not get it to work in my situation.</li>
<li>I've tried mocking various aspects of the function including the database connection, query and using the 'pd_read_sql(query, con)' function to no avail. I believe this is the closest I got. </li>
</ul>

<h1>My Most Recent Code for Testing</h1>

<pre><code>import pandas as pd
import pyodbc
import unittest
import pandas.util.testing as tm

from unittest import mock

# Function that I want to test
def p2ctt_data_frame():
    conn = pyodbc.connect(
        r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};'
        r'DBQ=My\Path\To\Actual\Database\Access Database.accdb;'
    )

    query = 'select * from P2CTT_2016_Plus0HHs'

    # I want to make sure this dataframe object is created as intended
    df = pd.read_sql(query, conn) 

    return df


class TestMockDatabase(unittest.TestCase):

    @mock.patch('directory1.script1.pyodbc.connect')  # Mocking connection
    def test_mock_database(self, mock_access_database):

        # The dataframe I expect as the output after query is run on the 'mock database'
        expected_result = pd.DataFrame({
            'POSTAL_CODE':[
                'A0A0A1'
            ],
            'DA_ID':[
                1001001
            ],
            'GHHDS_DA':[
                100
            ]
        })

        # This is the line that I believe is wrong. I want to create a return value that mocks an Access table
        mock_access_database.connect().return_value = [('POSTAL_CODE', 'DA_ID', 'GHHDS_DA'), ('A0A0A1', 1001001, 100)]

        result = p2ctt_data_frame()  # Run original function on the mock database

        tm.assert_frame_equal(result, expected_result) 


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

<p>I expect that the expected dataframe and the result after running the test using the mock database object is one and the same. This is not the case. </p>

<p>Currently, if I print out the result when trying to mock the database I get:</p>

<p>Empty DataFrame
Columns: []
Index: [] </p>

<p>Furthermore, I get the following error after the test is run:</p>

<p>AssertionError: DataFrame are different;<br>
DataFrame shape mismatch
[left]:  (0, 0)
[right]: (1, 3)</p>
",https://stackoverflow.com/questions/55576527/set-up-a-mock-database-in-python-for-unit-testing,"['python-3.x', 'pandas', 'unit-testing', 'ms-access', 'mocking']",27186,True,12,1
Angular (8) - Unit testing service with private variables,"<p>I am wondering if my approach to the service I am building and testing is the right approach or not. I have always designed my classes to be as encapsulated as possible. So when it came to building my angular services, I built them the same way. </p>

<p>Below is a snippet of how my service looks:</p>

<pre class=""lang-js prettyprint-override""><code>private postUrl = 'https://localhost:44359/api/posts';
private currentGetPostsUrl = `${this.postUrl}?page=${this.pageNumber}&amp;pageSize=${this.pageSize}`;

private filteredPostListSource = new Subject&lt;IPostViewDto[]&gt;();
filteredPostList$ = this.filteredPostListSource.asObservable();

// post list returned from the api
private originalPostList: IPostViewDto[];
// filtered list that is displayed to user
private filteredPostList: IPostViewDto[];

//get a list of posts that are paginated
getPosts(): Observable &lt; IPostViewDto[] &gt; {
  const urlToFetch = `${this.postUrl}?page=${this.pageNumber}&amp;pageSize=${this.pageSize}`;

  // if the post list exists, return that post list
  if(this.originalPostList) {
  return of(this.originalPostList);
}

return this.http.get&lt;IPostViewDto[]&gt;(urlToFetch, { observe: 'response' })
  .pipe(
    map((response: HttpResponse&lt;IPostViewDto[]&gt;) =&gt; {
      const paginationHeader = JSON.parse(response.headers.get('X-Pagination'));
      this.totalCount = paginationHeader.totalCount;
      this.originalPostList = response.body;
      this.filteredPostList = [...this.originalPostList];
      return response.body;
    }),
    catchError(err =&gt; this.errorHandler(err))
  );
}
</code></pre>

<p>Per above, I don't allow components to directly access the private variables and instead have methods through which all interaction is done. The issue here is that unit testing is a bit of a mess. If I want to correctly test that my <code>getPosts()</code> method correctly returns the list of posts in my <code>originalPostList</code> if it exists, I'd have to run it once after creating a stub value for the http get to ensure the private field gets set, then run it again and compare my stub value equals the 2nd run of <code>getPosts()</code>.</p>

<p>This seems like its not only a bad unit test, but maybe the service itself is not built correctly to be tested. </p>

<p>What would be the best way to restructure this to be easily testable? Do I just create getters/setters and test against those? Or is my approach I described above valid?</p>

<hr>

<p>Do note that the reason why I designed it this way is because I didn't want child components / other components to accidentally update these properties without an explicit method call (so that I can write tests to ensure that is the case). Its not because a single component is the only one accessing this service.</p>
",https://stackoverflow.com/questions/57471110/angular-8-unit-testing-service-with-private-variables,"['angular', 'unit-testing', 'karma-jasmine']",3080,True,0,2
testing client side javascript on the command line,"<p>I am working on a project which has a lot of client side javascript files</p>

<p>none of these files have any module.export.XXX statements</p>

<p>I understand that jasmine has a stand-alone version which uses a html file to run the tests and a node.js version which uses the cli to run the tests.</p>

<p>When using the stand-alone version of jasmine i can import the js files i want to test with  tags, no problem.</p>

<p>When using the node.js version i cannot use import statements because none of the files that i wish to test have exports.</p>

<p>I am very keen on testing on the command line so that running the tests with our continuous integration package is easier.</p>

<p>I have attempted to solve this using this guide
<a href=""https://www.nfriedly.com/techblog/2013/02/automatically-unit-testing-client-side-javascript-with-jasmine-and-node-js/"" rel=""nofollow noreferrer"">https://www.nfriedly.com/techblog/2013/02/automatically-unit-testing-client-side-javascript-with-jasmine-and-node-js/</a>
however it is very out of date (the jasmine folder structure is different) and i could not fix the JDOM issue which is mentioned. </p>

<p>Is there any way to make this work other than adding export statements?
if no
will adding export statements cause issues in any browsers?
and
most of the existing files are a wrapper functions with all of the functions and other components (variables, event listeners ect) inside it. I intend to call specific individual functions found in the files (not the wrapper functions) from the tests. will this be possible without using prototypes?
will i need to change the architecture  </p>
",https://stackoverflow.com/questions/58309523/testing-client-side-javascript-on-the-command-line,"['javascript', 'node.js', 'jasmine']",123,False,0,0
Maintaining order of execution of tests in Junit,"<p>Currently, I'm working on testing a Class (let's say <code>Message</code> for example) that has CRUD operations. Following the methodology used behind, I want to test all the operations in exact Create, Read, Update and Delete order. </p>

<p>Since the order of execution of test cases in JUnit is dependent on JVM, I need some proper way to ensure that the unit test cases are executed in the given order.</p>

<p>So far, I've come up with following strategies:</p>

<ol>
<li><p>Using <code>@FixMethodOrder(MethodSorters.NAME_ASCENDING)</code> in JUnit 4 to execute methods in ascending order of their names.  However, this requires renaming test cases and didn't seem the best way to me as if in future more test case need to be added existing test cases may need to be refactored.</p></li>
<li><p>Using different <code>Message</code> object for each test case. However, I will need to create/initialize it before and delete it after each test case. This for me seems to go against the notion of unit-testing, as to test <code>update</code> I'll have to call create and delete, which no longer makes this a unit test case. If <code>create</code> fails, this would result in <code>read</code>, <code>update</code> and <code>delete</code> tests in failing as well, even when there's nothing wrong with them.</p></li>
<li><p>Using a single test to call other test methods. This to me seems the more appropriate solution than other two. If <code>create</code> fails, it should stop other three tests from running and such.</p></li>
</ol>

<p>So is there any better way to achieve this or any alternative way to test such a model?</p>

<p>Currently using JUnit4 and thinking of moving to JUnit5 if no solution satisfies my case.</p>
",https://stackoverflow.com/questions/57289294/maintaining-order-of-execution-of-tests-in-junit,"['java', 'unit-testing', 'junit']",407,True,0,2
"EFCore unable to remove many-to-many relation in memory sqlite, but works in production sql","<p>I am trying to create a releational database using EFCore code first. I have successfully created it after some ondelete issues. 
I then thought I was in the clear to create unit tests, but the examples I had run with in an actual implementation of the database didn't work with inmemory providers(EFCore and Sqlite).</p>

<p>The relations are as follows: 
A, B, C are entities
A1-*B has a many to one relation 
BC Is a many to many relation
AC Is the other many to many relation. </p>

<p>And when I try to remove anything while in memory, it throws errors similar to the follwing where I tried to remove a entry from the B col.</p>

<pre><code>'The property 'AId' on entity type 'AC' is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key first delete the dependent and invoke 'SaveChanges' then associate the dependent with the new principal.'
</code></pre>

<p>I tried in memory EFCore straight up but learned that it does not model relational databases, so I tried sqlite in memory. 
The following code works on a sql server.(excluding the sqlite parts) </p>

<pre><code>using (var connection = new SqliteConnection(""DataSource=:memory:""))
            {
                connection.Open();
                var options = new DbContextOptionsBuilder&lt;DBContext&gt;()
                   .UseSqlite(connection)
                   .Options;
                using (var _context = new DBContext(options))
                {
                    SeedData(_context);
                    _context.Database.EnsureCreated();
                    _context.Bs.Remove(_context.Bs.SingleOrDefault(s =&gt; s.Id == 1));

                    _context.SaveChanges();
                }
            }

</code></pre>

<p>But throws the before mentioned error.</p>

<p>This is the relational model in fluentapi</p>

<pre><code> modelBuilder.Entity&lt;A&gt;(pa =&gt;
            {
                pa.HasKey(key =&gt; new { key.Id });
                pa.HasAlternateKey(key =&gt; new { key.Id, key.ExternalUID, key.InstitutionID });
            });

            modelBuilder.Entity&lt;B&gt;(sa =&gt;
            {
                sa.HasKey(key =&gt; new { key.Id });
                sa.HasOne(o =&gt; o.A)
                    .WithMany(s =&gt; s.Bs)
                    .OnDelete(DeleteBehavior.Restrict)
                    .HasForeignKey(k =&gt; k.AId);
                sa.HasAlternateKey(key =&gt; new { key.Id, key.AId });
            });

            modelBuilder.Entity&lt;C&gt;(l =&gt;
            {
                l.HasKey(key =&gt; new { key.Id });

            });



            modelBuilder.Entity&lt;AC&gt;(al =&gt;
            {
                al.HasKey(key =&gt; new { key.AId, key.CId });
                al.HasOne(sa =&gt; sa.A)
                    .WithMany(s =&gt; s.ACs)
                    .OnDelete(DeleteBehavior.Cascade)
                    .HasForeignKey(s =&gt; s.AId);
                al.HasOne(sa =&gt; sa.C)
                    .WithMany(s =&gt; s.ACs)
                    .OnDelete(DeleteBehavior.Cascade)
                    .HasForeignKey(o =&gt; o.CId);
            });

            modelBuilder.Entity&lt;BC&gt;(sal =&gt;
            {
                sal.HasKey(key =&gt; new { key.BId, key.CId});                    
                sal.HasOne(sa =&gt; sa.B)
                    .WithMany(s =&gt; s.BCs)
                    .OnDelete(DeleteBehavior.Cascade)
                    .HasForeignKey(s =&gt; s.BId);
                sal.HasOne(sa =&gt; sa.C)
                    .WithMany(s =&gt; s.BCs)
                    .OnDelete(DeleteBehavior.Cascade)
                    .HasForeignKey(o =&gt; o.CId);
            });
</code></pre>

<p>After changing to sqlite in memory I expected to get a relational database that mirrored what I experience with the real database. 
IE. Deleting entities in the graph and having it only cascade to the relational entries (BC AC) and not touch the primary Entity (Such as A, B, C). 
As in the example where I am trying to delete B but for some reason it wants to modify A.</p>

<p>I would like if you could help me figure out what I am doing wrong, or point me in the direction of a work around for unit testing.</p>
",https://stackoverflow.com/questions/56736652/efcore-unable-to-remove-many-to-many-relation-in-memory-sqlite-but-works-in-pro,"['c#', 'unit-testing', 'many-to-many', 'in-memory-database', 'ef-core-2.1']",371,False,0,0
Cross-Platform C++ development with VisualStudio,"<p>I want to start a cross-platform C++ project with VisualStudio 2019.
After some research I found two possible ways:</p>
<h2>CMake</h2>
<p><a href=""https://learn.microsoft.com/en-us/cpp/build/get-started-linux-cmake?view=vs-2019"" rel=""nofollow noreferrer"">Tutorial: Create C++ cross-platform projects in Visual Studio</a></p>
<p><a href=""https://learn.microsoft.com/en-us/cpp/linux/cmake-linux-project?view=vs-2019"" rel=""nofollow noreferrer"">Create and configure a Linux CMake project</a></p>
<p>CMake is pretty common for cross-platform projects, but I haven't done much with it and it feels like you need to put in much effort to make it run as you want to. But you have a huge amount of possibilities to configure it. <a href=""https://stackoverflow.com/questions/3505639/how-to-setup-visual-studio-for-cross-platform-c-development"">This</a> SO questions also recommends CMake, but says that there are other ways.</p>
<h2>VS Shared Project</h2>
<p><a href=""https://www.c-sharpcorner.com/UploadFile/7ca517/shared-project-an-impressive-features-of-visual-studio-201/"" rel=""nofollow noreferrer"">Shared Project : An Impressive Feature of Visual Studio 2015</a></p>
<p><a href=""https://devblogs.microsoft.com/cppblog/cross-platform-code-sharing-with-visual-c/"" rel=""nofollow noreferrer"">Cross-platform code sharing with Visual C++</a></p>
<p>If you use cross-platform code sharing in VS you have several projects in your solution (one for each platform) and at least one shared project, which includes your source + header files. The platform specific projects include all the configuration settings and the program entry point. The shared code can be used from each project as if it is in the project.
All the configuration is possible in VS. It looks less complex but with limited possibilities.</p>
<h2>Question</h2>
<p>Both ways look like they would fit my needs, but I haven't found a comparison between them. I already coded running examples for both of them, but those small code bases haven't given me the insight I need.</p>
<p>What are the pro's and con's of those two ways? Considering attributes like build-speed, flexibility, time to learn/master/market, VS feature support, unit testing, continuous integration, ...</p>
",https://stackoverflow.com/questions/58874155/cross-platform-c-development-with-visualstudio,"['c++', 'visual-studio', 'cmake', 'cross-platform']",419,False,-1,1
Should pytest be used for integration testing an embedded system?,"<p>I'm working on setting up my team's new unit test and integration test infrastructure and want to make sure I'm starting off by selecting the correct test frameworks. I'm  an embedded developer testing code running on a VxWorks operating system with a C/C++ production codebase. </p>

<p>We need a framework capable of directly testing C/C++ for unit testing, so for our unit tests I chose Googletest as our framework. </p>

<p>However, for integration tests we've generally tested using Python scripts (with no test framework). The Python scripts connect to the embedded system over a network and test cases via sending commands and receiving telemetry. </p>

<p>Would using pytest as a test framework be beneficial to the way we're currently using Python for integration testing an embedded system?  Most of the examples I've seen use pytest in a more unit test fashion by creating assertions for single functions in a Python production codebase.</p>

<p>EDIT:
Per hoefling's comment, i'll provide a (very simplified) example of one of our existing Python integration test cases, and also what I believe its corresponding Pytest implementation would be.</p>

<pre><code>#Current example
def test_command_counter():
    preTestCmdCount = getCmdCountFromSystem()
    sendCommandToSystem()
    postTestCmdCount = getCmdCountFromSystem()

    if (postTestCmdCount != (preTestCmdCount + 1)):
        print(""FAIL: Command count did not increment!"")
    else:
        print(""PASS"")


#Using Pytest?
def test_command_counter():
    preTestCmdCount = getCmdCountFromSystem()
    sendCommandToSystem()
    postTestCmdCount = getCmdCountFromSystem()

    assert postTestCmdCount == (preTestCmdCount + 1)
</code></pre>

<p>So, correct me if I'm wrong, but it appears that the advantages of using Pytest  over plain Python for this simplified case would be:</p>

<ol>
<li><p>Being able to make use of pytest's automated test case discovery, so that I can easily run all of my test functions instead of having to create custom code to do so.</p></li>
<li><p>Being able to make use of the 'assert' syntax which will automatically generate pass/fail statements for each test instead of having to manually implement pass/fail print statements for each test case</p></li>
</ol>
",https://stackoverflow.com/questions/56859750/should-pytest-be-used-for-integration-testing-an-embedded-system,"['python', 'pytest']",3916,True,3,2
Concurrent access to a TreeSet doesn&#39;t seem to work,"<p>I'm creating a Java class IdGenerator that allocates a unique integer ID each time one is requested. It uses a TreeSet to store ranges of free IDs, and each time an ID is requested it looks in the set to find a range, allocates the first ID in the range, deletes the range, and adds a new range that is one smaller. The whole allocation process is synchronized on the set to ensure that different threads don't collide.</p>

<p>This worked fine when I was unit testing the class, but I have just run a test of a different class where an instance of the IdGenerator class is called ten times in quick succession, by different threads, and it returns the same value every time. Logging reveals that on each invocation, the set holding the free ranges has the same contents, although the lastId variable is different: -1 on the first invocation, 0 on the others. This seems to suggest that the different threads are using different copies of the set, although that's not what I would expect from the code.</p>

<p>I'm running using JRE 1.8.0_191, within Eclipse Neon 4.6.3 on Windows 10.</p>

<p>I've tried synchronizing on the generator object rather than the set, wrapping the TreeSet in a synchronizedSortedSet, and using a Lock object instead of the synchronized keyword. None of it made any difference.</p>

<pre><code>private final SortedSet&lt;Range&gt; freeRanges = new TreeSet&lt;&gt;();
private int lastId;


public int allocateId() throws IllegalStateException
{
    int answer;
    synchronized (freeRanges)
    {
        LOG.debug(""lastId = {}, freeRanges = {}"", lastId, freeRanges);
        if (freeRanges.isEmpty())
            throw new IllegalStateException(""All possible IDs are allocated"");
        Range range = Stream
                .of(freeRanges.tailSet(new Range(lastId + 1)), freeRanges)
                .filter(s -&gt; !s.isEmpty())
                .map(SortedSet::first)
                .findFirst()
                .get();
        answer = lastId = range.start;
        freeRanges.remove(range);
        if (range.start != range.end)
            freeRanges.add(new Range(range.start + 1, range.end));
        LOG.debug(""Allocated {}, freeRanges = {}"", answer, freeRanges);
    }
    return answer;
}
</code></pre>

<p>The log output is as shown below. I expect that on the nth invocation, the number allocated is n-1 and the set of free ranges is updated to show a range starting at n and ending at 100. But instead, what I see is this:</p>

<pre><code>16:03:18.554 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - lastId = -1, freeRanges = [Range [start=0, end=100]]
16:03:18.570 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - Allocated 0, freeRanges = [Range [start=1, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - lastId = 0, freeRanges = [Range [start=0, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - Allocated 0, freeRanges = [Range [start=1, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - lastId = 0, freeRanges = [Range [start=0, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - Allocated 0, freeRanges = [Range [start=1, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - lastId = 0, freeRanges = [Range [start=0, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - Allocated 0, freeRanges = [Range [start=1, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - lastId = 0, freeRanges = [Range [start=0, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - Allocated 0, freeRanges = [Range [start=1, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - lastId = 0, freeRanges = [Range [start=0, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - Allocated 0, freeRanges = [Range [start=1, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - lastId = 0, freeRanges = [Range [start=0, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - Allocated 0, freeRanges = [Range [start=1, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - lastId = 0, freeRanges = [Range [start=0, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - Allocated 0, freeRanges = [Range [start=1, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - lastId = 0, freeRanges = [Range [start=0, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - Allocated 0, freeRanges = [Range [start=1, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - lastId = 0, freeRanges = [Range [start=0, end=100]]
16:03:18.586 [main] DEBUG uk.org.thehickses.idgenerator.IdGenerator - Allocated 0, freeRanges = [Range [start=1, end=100]]
</code></pre>
",https://stackoverflow.com/questions/54095862/concurrent-access-to-a-treeset-doesnt-seem-to-work,"['java', 'synchronized', 'treeset']",323,False,3,1
Angular Testing - how to test Data Service with extended base class,"<p>I'm having a hard to setup Tests of my Data Services, I'm trying to use the <code>HttpClientTestingModule</code> as defined in these articles <a href=""https://medium.com/netscape/testing-with-the-angular-httpclient-api-648203820712"" rel=""nofollow noreferrer"">Testing with the Angular HttpClient API</a>, from this <a href=""https://stackoverflow.com/questions/52116993/jasmin-karma-error-unexpected-value-httpclient-imported-by-the-module-dy/52133396"">SO Question</a> and also tried <code>inject</code> from this article <a href=""https://alligator.io/angular/testing-httpclient/"" rel=""nofollow noreferrer"">Testing HttpClient</a> but I can't get it to work. </p>

<p>I believe my problems comes from the fact that I have a global <code>DataService</code> which uses 3 service providers (<code>HttpClient</code>, <a href=""https://www.npmjs.com/package/ngx-logger"" rel=""nofollow noreferrer"">NGXLogger</a> and <a href=""https://www.npmjs.com/package/@ngx-translate/core"" rel=""nofollow noreferrer"">TranslateService</a> from <code>ngx-translate</code>). Then I have multiple Data Services which extends the global <code>DataService</code> like so</p>

<pre><code>@Injectable()
export class UserDataService extends DataService {
  constructor(protected http: HttpClient, protected logger: NGXLogger, protected translate: TranslateService) {
  super(http, logger, translate);
  this.url = `api/users`;
}

getUsers(): Observable&lt;Users[]&gt; {
  return super.getAll&lt;User[]&gt;(this.url);
}
</code></pre>

<p>So as you can see, each extended data services (like <code>UserDataServices</code>) takes care of injecting the 3 necessary dependencies to the <code>super</code> call. </p>

<p>I'm trying to code my test, which is done with <code>Jest</code>, with the following code</p>

<pre><code>describe('User Data Service', () =&gt; {
  let dataService: TemplateDataService;
  let httpTestingController: HttpTestingController;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        TranslateModule.forRoot(),
        LoggerModule.forRoot({ level: NgxLoggerLevel.ERROR, serverLoggingUrl: 'api/logging', serverLogLevel: NgxLoggerLevel.ERROR }),
      ],
      providers: [
        UserDataService
      ]
    });
    dataService = TestBed.get(UserDataService);
    httpTestingController = TestBed.get(HttpTestingController);
  });

it('should return an Observable&lt;User[]&gt;', () =&gt; {
  const dummyUsers = [
    { login: 'John' },
    { login: 'Doe' }
  ];

  dataService.getAll().subscribe((users: User[]) =&gt; {
    expect(users.length).toBe(2);
    expect(users).toEqual(dummyUsers);
  });

  const req = httpTestingController.expectOne(`api/users`);
  expect(req.request.method).toBe('GET');
  req.flush(dummyUsers);
});
</code></pre>

<p>and it keeps throwing the following error</p>

<pre><code>Unexpected value 'HttpClientModule' imported by the module 'HttpClientTestingModule'. Please add a @NgModule annotation.
</code></pre>

<p>I also tried with this piece of code, but I get the same error</p>

<pre><code>it(
  'should get users',
  inject(
    [HttpTestingController, NGXLogger, TranslateService, DataService],
    (
      httpMocker: HttpTestingController,
      logger: NGXLogger,
      translate: TranslateService,
      dataServicer: DataService
    ) =&gt; {
      // ...our test logic here
    }
  )
);
</code></pre>

<p>I'm fairly new to Unit Testing (I started last week) and I'm totally blocked with testing any of my Data Services (on the bright side, I'm ok with testing the component with a data service mock, but I'd like to test these data services as well). </p>

<p>On the technology side, the project uses <code>Angular: ^7.2.10</code> and <code>jest: ^23.6.0</code>. </p>

<p><strong>EDIT</strong></p>

<p>I forgot to mention that <code>DataService</code> is also a Service and I also tried to add it to the <code>providers</code> in the <code>beforeEach()</code> and I still get the same error (<code>Unexpected value 'HttpClientModule'...</code>). As shown below</p>

<pre><code>beforeEach(() =&gt; {
  TestBed.configureTestingModule({
    imports: [
      HttpClientTestingModule,
      TranslateModule.forRoot(),
      LoggerModule.forRoot({ level: NgxLoggerLevel.ERROR, serverLoggingUrl: 'api/logging', serverLogLevel: NgxLoggerLevel.ERROR }),
    ],
    providers: [
      DataService,
      UserDataService
    ]
  });
});
</code></pre>

<p>Also to give a bit more overview of the <code>DataService</code>, here's a strip down version of it. </p>

<pre><code>export class DataService {
  constructor(protected http: HttpClient, protected logger: NGXLogger, protected translate: TranslateService) {}

  get&lt;T&gt;(id?: string, options?: HttpOptions): Observable&lt;T&gt; {
    const caller = findCaller(new Error());
    const uriWithId = id ? `/${id}` : '';
    const requestUrl = this.addGlobalQueryParams(`${this.url}${uriWithId}`);
    this.logger.debug(`DataService - GET method [${caller}] - START - URL:: ${requestUrl}`);

    return this.http.get&lt;T&gt;(requestUrl, options).pipe(map((response: any) =&gt; {
      this.logger.debug(`DataService - GET method [${caller}] - END - URL:: ${requestUrl} - Response:: `, response);
      return response;
    }));
  }

  getAll&lt;T&gt;(url?: string, options?: HttpOptions): Observable&lt;T&gt; {
    const caller = findCaller(new Error());
    if (url) {
      this.logger.debug(`DataService - POST method [${caller}] - START - URL:: `, url);
      return this.http.post&lt;T&gt;(url).pipe(map((response: any) =&gt; {
        this.logger.debug(`DataService - POST method [${caller}] - END - URL:: ${url} - Response:: `, response);
        return response;
      }));
    }
  }
}
</code></pre>

<p><strong>EDIT 2</strong></p>

<p>I guess what I'm looking for is how to Unit Test an Extended Class, which was actually asked in the Angular repo <a href=""https://github.com/angular/quickstart/issues/533"" rel=""nofollow noreferrer"">here</a> but was never answered and closed because it wasn't an issue but more of a question. </p>
",https://stackoverflow.com/questions/55464261/angular-testing-how-to-test-data-service-with-extended-base-class,"['angular', 'unit-testing', 'jasmine', 'jestjs', 'angular-test']",2072,False,2,1
How to prevent automatic inclusion of navigation properties in unit tests,"<p>I am currently developing an app store style API which has the following entities (plus many others, but not relevant to the problem):</p>

<ul>
<li>App (1 to many relationship to AppRevision - contains IEnumerable property)</li>
<li>AppRevision</li>
<li>Installation</li>
</ul>

<p>I have come across an odd problem where the behaviour of EF differs in unit tests to when actually running the API, in that navigation properties are automatically being included when unit testing. </p>

<p>Take the following code snippet from my command handler:</p>

<pre><code>App app = await this.context.Apps
    .Include(a =&gt; a.Installations)
    .FirstOrDefaultAsync(a =&gt; a.Id == command.AppId);

if (app != null) {
    // Code omitted for brevity
}
</code></pre>

<p>When running the API, if I inspect <code>app</code> after this code has been run, the AppRevisions collection on the App entity is empty, as you would expect as I have not expliclity told EF to <code>.Include(a =&gt; a.AppRevisions)</code> - the API then throws an exception when trying to process code later on that needs this data to be there.</p>

<p>Now look at the following unit test for the same handler:</p>

<pre><code>[Fact]
public async void Handle_ShouldAddInstallationRecord_WhenDataIsValid()
{
    Guid testGuid = Guid.NewGuid();

    CreateInstallationCommand command = new CreateInstallationCommand(testGuid, ""ABC"", ""abc@abc.com"", null);

    using (TestContext context = new TestContextFactory().CreateTestContext())
    {
        context.Apps.Add(new App() { Id = testGuid });
        context.AppRevisions.Add(new AppRevision() { Id = Guid.NewGuid(), AppId = testGuid, Status = AppRevisionStatus.Approved, IsListed = true });
        await context.SaveChangesAsync();

        CreateInstallationCommandHandler handler = new CreateInstallationCommandHandler(context);

        CommandResult result = await handler.Handle(command, new CancellationToken());

        Assert.True(result);
        Assert.Single(context.Installations);
    }
}
</code></pre>

<p>If I step through this test, when I get to the handler and inspect the <code>app</code> variable, the AppRevisions collection has automatically been populated. As a result, the test passes because the code that requires the AppRevisions collection to be populated can execute. </p>

<p>The expectation is that this test should actually fail, because I'm not telling EF to include those entities in the query.</p>

<p>I am using a Sqlite in memory database to create the database context for my unit tests and running .NET Core 2.2</p>

<p>I originally thought this was something to do with the changetracker. While disabling this does solve the immediate problem reported above, it creates a load of other problems so isn't a viable solution (and probably wouldn't be the correct one anyway)</p>

<p>Any suggestions gratefully received</p>
",https://stackoverflow.com/questions/57426788/how-to-prevent-automatic-inclusion-of-navigation-properties-in-unit-tests,"['c#', 'sqlite', 'unit-testing', 'entity-framework-core', 'ef-core-2.2']",437,True,2,1
Correct place to query MongoDB in Express API server application with testing?,"<p>I am creating a Node/Express API server to use as a backend for a React single page application. Currently, I am using the MongoDB Node.js driver (not mongoose) to connect to my MongoDB instance. </p>

<p>My question is where is the correct place to store MongoDB queries (insertOne, FindOne, etc...)? I am hoping that someone with experience in a production team can give some insight.</p>

<p>So far I have been given some advice from people with similar experience, but there seems to be quite a lot of contradiction. Here are the two main practices I've seen:</p>

<p><strong>1. Connect to MongoDB and query inside controller functions.</strong></p>

<p>I have been told that it is okay to connect and query the database from inside the controller functions. Here is an example of how that would look:</p>

<p>App structure:</p>

<pre><code>├── app.js
├── controllers
│   └── users.js
├── db
│   └── mongodb.js
├── routes
│   └── users.js
</code></pre>

<p>Connect to MonogoDB in several functions inside <code>/controllers</code>, reusing the same connection throughout the application as recommended. Here is an example <code>/controllers/users.js</code>:</p>

<pre><code>import initMongo from '../db/mongodb';

export const registerUser = (req, res) =&gt; {
  initMongo().then((db) =&gt; {
    // Register User Code Here
  });
};


export const loginUser = (req, res) =&gt; {
  initMongo().then((db) =&gt; {
    // Login User Code Here
  });
};

</code></pre>

<p>Here is an example `/db/mongodb.js':</p>

<pre><code>import { MongoClient } from 'mongodb';

let cachedDb = null;

/**
 * @description Initialzies the DB instance.
 *
 * @returns {Promise} A resolved promise with the DB instance.
 */
export default () =&gt; {
  if (cachedDb &amp;&amp; cachedDb.serverConfig.isConnected()) {
    return Promise.resolve(cachedDb);
  }

  return MongoClient.connect(process.env.MONGO_URL, {
    useNewUrlParser: true,
  }).then(client =&gt; {
    cachedDb = client.db('databaseName');
    return Promise.resolve(cachedDb);
  });
};
</code></pre>

<p>The controller functions are then called by specific routes in <code>/routes/users.js</code>, like so:</p>

<pre><code>router.post('/register', registerUser);
router.post('/login', loginUser);
</code></pre>

<p><strong>2. Create a Models folder and store all DB queries there:</strong></p>

<p>I have also been told to break the DB queries out into a <code>models</code> folder and then reference the queries from there in your controllers like so:</p>

<p>App Structure</p>

<pre><code>├── app.js
├── controllers
│   └── users.js
├── db
│   └── mongodb.js
├── models
│   └── users.js
├── routes
│   └── users.js
</code></pre>

<p>Sample <code>/controllers/users.js</code> file:</p>

<pre><code>import UserModel from '../models/users';

export const registerUser = (req, res) =&gt; {
  const user = new UserModel();
  user.createUser(req.body.user);
};
</code></pre>

<p>Sample <code>/models/users.js</code> file:</p>

<pre><code>export default function User() {
  this.createUser = (newUser) =&gt; {
    // MongoDB insertOne Query
  }
}
</code></pre>

<p>Is there any benefit to using one of these methods of the other? Is there a recommended way in a multi-person production team? Am I an idiot and should just be using Mongoose?</p>

<p>I would also love to hear opinions on which method would be easier for unit testing with a platform such as Jest.</p>
",https://stackoverflow.com/questions/55051558/correct-place-to-query-mongodb-in-express-api-server-application-with-testing,"['node.js', 'mongodb', 'express']",61,False,1,0
